remove unused files
[platform/upstream/gcc48.git] / gcc / cp / decl2.c
1 /* Process declarations and variables for C++ compiler.
2    Copyright (C) 1988-2013 Free Software Foundation, Inc.
3    Hacked by Michael Tiemann (tiemann@cygnus.com)
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it 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,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU 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
22 /* Process declarations and symbol lookup for C++ front end.
23    Also constructs types; the standard scalar types at initialization,
24    and structure, union, array and enum types when they are declared.  */
25
26 /* ??? not all decl nodes are given the most useful possible
27    line numbers.  For example, the CONST_DECLs for enum values.  */
28
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "tm.h"
33 #include "tree.h"
34 #include "flags.h"
35 #include "cp-tree.h"
36 #include "decl.h"
37 #include "toplev.h"
38 #include "timevar.h"
39 #include "cpplib.h"
40 #include "target.h"
41 #include "c-family/c-common.h"
42 #include "c-family/c-objc.h"
43 #include "cgraph.h"
44 #include "tree-inline.h"
45 #include "c-family/c-pragma.h"
46 #include "dumpfile.h"
47 #include "intl.h"
48 #include "gimple.h"
49 #include "pointer-set.h"
50 #include "splay-tree.h"
51 #include "langhooks.h"
52 #include "c-family/c-ada-spec.h"
53
54 extern cpp_reader *parse_in;
55
56 /* This structure contains information about the initializations
57    and/or destructions required for a particular priority level.  */
58 typedef struct priority_info_s {
59   /* Nonzero if there have been any initializations at this priority
60      throughout the translation unit.  */
61   int initializations_p;
62   /* Nonzero if there have been any destructions at this priority
63      throughout the translation unit.  */
64   int destructions_p;
65 } *priority_info;
66
67 static void mark_vtable_entries (tree);
68 static bool maybe_emit_vtables (tree);
69 static bool acceptable_java_type (tree);
70 static tree start_objects (int, int);
71 static void finish_objects (int, int, tree);
72 static tree start_static_storage_duration_function (unsigned);
73 static void finish_static_storage_duration_function (tree);
74 static priority_info get_priority_info (int);
75 static void do_static_initialization_or_destruction (tree, bool);
76 static void one_static_initialization_or_destruction (tree, tree, bool);
77 static void generate_ctor_or_dtor_function (bool, int, location_t *);
78 static int generate_ctor_and_dtor_functions_for_priority (splay_tree_node,
79                                                           void *);
80 static tree prune_vars_needing_no_initialization (tree *);
81 static void write_out_vars (tree);
82 static void import_export_class (tree);
83 static tree get_guard_bits (tree);
84 static void determine_visibility_from_class (tree, tree);
85 static bool determine_hidden_inline (tree);
86 static bool decl_defined_p (tree);
87
88 /* A list of static class variables.  This is needed, because a
89    static class variable can be declared inside the class without
90    an initializer, and then initialized, statically, outside the class.  */
91 static GTY(()) vec<tree, va_gc> *pending_statics;
92
93 /* A list of functions which were declared inline, but which we
94    may need to emit outline anyway.  */
95 static GTY(()) vec<tree, va_gc> *deferred_fns;
96
97 /* A list of decls that use types with no linkage, which we need to make
98    sure are defined.  */
99 static GTY(()) vec<tree, va_gc> *no_linkage_decls;
100
101 /* Nonzero if we're done parsing and into end-of-file activities.  */
102
103 int at_eof;
104
105 \f
106
107 /* Return a member function type (a METHOD_TYPE), given FNTYPE (a
108    FUNCTION_TYPE), CTYPE (class type), and QUALS (the cv-qualifiers
109    that apply to the function).  */
110
111 tree
112 build_memfn_type (tree fntype, tree ctype, cp_cv_quals quals,
113                   cp_ref_qualifier rqual)
114 {
115   tree raises;
116   tree attrs;
117   int type_quals;
118
119   if (fntype == error_mark_node || ctype == error_mark_node)
120     return error_mark_node;
121
122   gcc_assert (TREE_CODE (fntype) == FUNCTION_TYPE
123               || TREE_CODE (fntype) == METHOD_TYPE);
124
125   type_quals = quals & ~TYPE_QUAL_RESTRICT;
126   ctype = cp_build_qualified_type (ctype, type_quals);
127   raises = TYPE_RAISES_EXCEPTIONS (fntype);
128   attrs = TYPE_ATTRIBUTES (fntype);
129   fntype = build_method_type_directly (ctype, TREE_TYPE (fntype),
130                                        (TREE_CODE (fntype) == METHOD_TYPE
131                                         ? TREE_CHAIN (TYPE_ARG_TYPES (fntype))
132                                         : TYPE_ARG_TYPES (fntype)));
133   if (attrs)
134     fntype = cp_build_type_attribute_variant (fntype, attrs);
135   if (rqual)
136     fntype = build_ref_qualified_type (fntype, rqual);
137   if (raises)
138     fntype = build_exception_variant (fntype, raises);
139
140   return fntype;
141 }
142
143 /* Return a variant of FNTYPE, a FUNCTION_TYPE or METHOD_TYPE, with its
144    return type changed to NEW_RET.  */
145
146 tree
147 change_return_type (tree new_ret, tree fntype)
148 {
149   tree newtype;
150   tree args = TYPE_ARG_TYPES (fntype);
151   tree raises = TYPE_RAISES_EXCEPTIONS (fntype);
152   tree attrs = TYPE_ATTRIBUTES (fntype);
153
154   if (new_ret == error_mark_node)
155     return fntype;
156
157   if (same_type_p (new_ret, TREE_TYPE (fntype)))
158     return fntype;
159
160   if (TREE_CODE (fntype) == FUNCTION_TYPE)
161     {
162       newtype = build_function_type (new_ret, args);
163       newtype = apply_memfn_quals (newtype,
164                                    type_memfn_quals (fntype),
165                                    type_memfn_rqual (fntype));
166     }
167   else
168     newtype = build_method_type_directly
169       (class_of_this_parm (fntype), new_ret, TREE_CHAIN (args));
170   if (raises)
171     newtype = build_exception_variant (newtype, raises);
172   if (attrs)
173     newtype = cp_build_type_attribute_variant (newtype, attrs);
174
175   return newtype;
176 }
177
178 /* Build a PARM_DECL with NAME and TYPE, and set DECL_ARG_TYPE
179    appropriately.  */
180
181 tree
182 cp_build_parm_decl (tree name, tree type)
183 {
184   tree parm = build_decl (input_location,
185                           PARM_DECL, name, type);
186   /* DECL_ARG_TYPE is only used by the back end and the back end never
187      sees templates.  */
188   if (!processing_template_decl)
189     DECL_ARG_TYPE (parm) = type_passed_as (type);
190
191   /* If the type is a pack expansion, then we have a function
192      parameter pack. */
193   if (type && TREE_CODE (type) == TYPE_PACK_EXPANSION)
194     FUNCTION_PARAMETER_PACK_P (parm) = 1;
195
196   return parm;
197 }
198
199 /* Returns a PARM_DECL for a parameter of the indicated TYPE, with the
200    indicated NAME.  */
201
202 tree
203 build_artificial_parm (tree name, tree type)
204 {
205   tree parm = cp_build_parm_decl (name, type);
206   DECL_ARTIFICIAL (parm) = 1;
207   /* All our artificial parms are implicitly `const'; they cannot be
208      assigned to.  */
209   TREE_READONLY (parm) = 1;
210   return parm;
211 }
212
213 /* Constructors for types with virtual baseclasses need an "in-charge" flag
214    saying whether this constructor is responsible for initialization of
215    virtual baseclasses or not.  All destructors also need this "in-charge"
216    flag, which additionally determines whether or not the destructor should
217    free the memory for the object.
218
219    This function adds the "in-charge" flag to member function FN if
220    appropriate.  It is called from grokclassfn and tsubst.
221    FN must be either a constructor or destructor.
222
223    The in-charge flag follows the 'this' parameter, and is followed by the
224    VTT parm (if any), then the user-written parms.  */
225
226 void
227 maybe_retrofit_in_chrg (tree fn)
228 {
229   tree basetype, arg_types, parms, parm, fntype;
230
231   /* If we've already add the in-charge parameter don't do it again.  */
232   if (DECL_HAS_IN_CHARGE_PARM_P (fn))
233     return;
234
235   /* When processing templates we can't know, in general, whether or
236      not we're going to have virtual baseclasses.  */
237   if (processing_template_decl)
238     return;
239
240   /* We don't need an in-charge parameter for constructors that don't
241      have virtual bases.  */
242   if (DECL_CONSTRUCTOR_P (fn)
243       && !CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn)))
244     return;
245
246   arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
247   basetype = TREE_TYPE (TREE_VALUE (arg_types));
248   arg_types = TREE_CHAIN (arg_types);
249
250   parms = DECL_CHAIN (DECL_ARGUMENTS (fn));
251
252   /* If this is a subobject constructor or destructor, our caller will
253      pass us a pointer to our VTT.  */
254   if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn)))
255     {
256       parm = build_artificial_parm (vtt_parm_identifier, vtt_parm_type);
257
258       /* First add it to DECL_ARGUMENTS between 'this' and the real args...  */
259       DECL_CHAIN (parm) = parms;
260       parms = parm;
261
262       /* ...and then to TYPE_ARG_TYPES.  */
263       arg_types = hash_tree_chain (vtt_parm_type, arg_types);
264
265       DECL_HAS_VTT_PARM_P (fn) = 1;
266     }
267
268   /* Then add the in-charge parm (before the VTT parm).  */
269   parm = build_artificial_parm (in_charge_identifier, integer_type_node);
270   DECL_CHAIN (parm) = parms;
271   parms = parm;
272   arg_types = hash_tree_chain (integer_type_node, arg_types);
273
274   /* Insert our new parameter(s) into the list.  */
275   DECL_CHAIN (DECL_ARGUMENTS (fn)) = parms;
276
277   /* And rebuild the function type.  */
278   fntype = build_method_type_directly (basetype, TREE_TYPE (TREE_TYPE (fn)),
279                                        arg_types);
280   if (TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn)))
281     fntype = build_exception_variant (fntype,
282                                       TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn)));
283   if (TYPE_ATTRIBUTES (TREE_TYPE (fn)))
284     fntype = (cp_build_type_attribute_variant
285               (fntype, TYPE_ATTRIBUTES (TREE_TYPE (fn))));
286   TREE_TYPE (fn) = fntype;
287
288   /* Now we've got the in-charge parameter.  */
289   DECL_HAS_IN_CHARGE_PARM_P (fn) = 1;
290 }
291
292 /* Classes overload their constituent function names automatically.
293    When a function name is declared in a record structure,
294    its name is changed to it overloaded name.  Since names for
295    constructors and destructors can conflict, we place a leading
296    '$' for destructors.
297
298    CNAME is the name of the class we are grokking for.
299
300    FUNCTION is a FUNCTION_DECL.  It was created by `grokdeclarator'.
301
302    FLAGS contains bits saying what's special about today's
303    arguments.  DTOR_FLAG == DESTRUCTOR.
304
305    If FUNCTION is a destructor, then we must add the `auto-delete' field
306    as a second parameter.  There is some hair associated with the fact
307    that we must "declare" this variable in the manner consistent with the
308    way the rest of the arguments were declared.
309
310    QUALS are the qualifiers for the this pointer.  */
311
312 void
313 grokclassfn (tree ctype, tree function, enum overload_flags flags)
314 {
315   tree fn_name = DECL_NAME (function);
316
317   /* Even within an `extern "C"' block, members get C++ linkage.  See
318      [dcl.link] for details.  */
319   SET_DECL_LANGUAGE (function, lang_cplusplus);
320
321   if (fn_name == NULL_TREE)
322     {
323       error ("name missing for member function");
324       fn_name = get_identifier ("<anonymous>");
325       DECL_NAME (function) = fn_name;
326     }
327
328   DECL_CONTEXT (function) = ctype;
329
330   if (flags == DTOR_FLAG)
331     DECL_DESTRUCTOR_P (function) = 1;
332
333   if (flags == DTOR_FLAG || DECL_CONSTRUCTOR_P (function))
334     maybe_retrofit_in_chrg (function);
335 }
336
337 /* Create an ARRAY_REF, checking for the user doing things backwards
338    along the way.  DECLTYPE_P is for N3276, as in the parser.  */
339
340 tree
341 grok_array_decl (location_t loc, tree array_expr, tree index_exp,
342                  bool decltype_p)
343 {
344   tree type;
345   tree expr;
346   tree orig_array_expr = array_expr;
347   tree orig_index_exp = index_exp;
348
349   if (error_operand_p (array_expr) || error_operand_p (index_exp))
350     return error_mark_node;
351
352   if (processing_template_decl)
353     {
354       if (type_dependent_expression_p (array_expr)
355           || type_dependent_expression_p (index_exp))
356         return build_min_nt_loc (loc, ARRAY_REF, array_expr, index_exp,
357                                  NULL_TREE, NULL_TREE);
358       array_expr = build_non_dependent_expr (array_expr);
359       index_exp = build_non_dependent_expr (index_exp);
360     }
361
362   type = TREE_TYPE (array_expr);
363   gcc_assert (type);
364   type = non_reference (type);
365
366   /* If they have an `operator[]', use that.  */
367   if (MAYBE_CLASS_TYPE_P (type) || MAYBE_CLASS_TYPE_P (TREE_TYPE (index_exp)))
368     {
369       tsubst_flags_t complain = tf_warning_or_error;
370       if (decltype_p)
371         complain |= tf_decltype;
372       expr = build_new_op (loc, ARRAY_REF, LOOKUP_NORMAL, array_expr,
373                            index_exp, NULL_TREE, /*overload=*/NULL, complain);
374     }
375   else
376     {
377       tree p1, p2, i1, i2;
378
379       /* Otherwise, create an ARRAY_REF for a pointer or array type.
380          It is a little-known fact that, if `a' is an array and `i' is
381          an int, you can write `i[a]', which means the same thing as
382          `a[i]'.  */
383       if (TREE_CODE (type) == ARRAY_TYPE || TREE_CODE (type) == VECTOR_TYPE)
384         p1 = array_expr;
385       else
386         p1 = build_expr_type_conversion (WANT_POINTER, array_expr, false);
387
388       if (TREE_CODE (TREE_TYPE (index_exp)) == ARRAY_TYPE)
389         p2 = index_exp;
390       else
391         p2 = build_expr_type_conversion (WANT_POINTER, index_exp, false);
392
393       i1 = build_expr_type_conversion (WANT_INT | WANT_ENUM, array_expr,
394                                        false);
395       i2 = build_expr_type_conversion (WANT_INT | WANT_ENUM, index_exp,
396                                        false);
397
398       if ((p1 && i2) && (i1 && p2))
399         error ("ambiguous conversion for array subscript");
400
401       if (p1 && i2)
402         array_expr = p1, index_exp = i2;
403       else if (i1 && p2)
404         array_expr = p2, index_exp = i1;
405       else
406         {
407           error ("invalid types %<%T[%T]%> for array subscript",
408                  type, TREE_TYPE (index_exp));
409           return error_mark_node;
410         }
411
412       if (array_expr == error_mark_node || index_exp == error_mark_node)
413         error ("ambiguous conversion for array subscript");
414
415       expr = build_array_ref (input_location, array_expr, index_exp);
416     }
417   if (processing_template_decl && expr != error_mark_node)
418     return build_min_non_dep (ARRAY_REF, expr, orig_array_expr, orig_index_exp,
419                               NULL_TREE, NULL_TREE);
420   return expr;
421 }
422
423 /* Given the cast expression EXP, checking out its validity.   Either return
424    an error_mark_node if there was an unavoidable error, return a cast to
425    void for trying to delete a pointer w/ the value 0, or return the
426    call to delete.  If DOING_VEC is true, we handle things differently
427    for doing an array delete.
428    Implements ARM $5.3.4.  This is called from the parser.  */
429
430 tree
431 delete_sanity (tree exp, tree size, bool doing_vec, int use_global_delete,
432                tsubst_flags_t complain)
433 {
434   tree t, type;
435
436   if (exp == error_mark_node)
437     return exp;
438
439   if (processing_template_decl)
440     {
441       t = build_min (DELETE_EXPR, void_type_node, exp, size);
442       DELETE_EXPR_USE_GLOBAL (t) = use_global_delete;
443       DELETE_EXPR_USE_VEC (t) = doing_vec;
444       TREE_SIDE_EFFECTS (t) = 1;
445       return t;
446     }
447
448   /* An array can't have been allocated by new, so complain.  */
449   if (TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE)
450     warning (0, "deleting array %q#E", exp);
451
452   t = build_expr_type_conversion (WANT_POINTER, exp, true);
453
454   if (t == NULL_TREE || t == error_mark_node)
455     {
456       error ("type %q#T argument given to %<delete%>, expected pointer",
457              TREE_TYPE (exp));
458       return error_mark_node;
459     }
460
461   type = TREE_TYPE (t);
462
463   /* As of Valley Forge, you can delete a pointer to const.  */
464
465   /* You can't delete functions.  */
466   if (TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE)
467     {
468       error ("cannot delete a function.  Only pointer-to-objects are "
469              "valid arguments to %<delete%>");
470       return error_mark_node;
471     }
472
473   /* Deleting ptr to void is undefined behavior [expr.delete/3].  */
474   if (TREE_CODE (TREE_TYPE (type)) == VOID_TYPE)
475     {
476       warning (0, "deleting %qT is undefined", type);
477       doing_vec = 0;
478     }
479
480   /* Deleting a pointer with the value zero is valid and has no effect.  */
481   if (integer_zerop (t))
482     return build1 (NOP_EXPR, void_type_node, t);
483
484   if (doing_vec)
485     return build_vec_delete (t, /*maxindex=*/NULL_TREE,
486                              sfk_deleting_destructor,
487                              use_global_delete, complain);
488   else
489     return build_delete (type, t, sfk_deleting_destructor,
490                          LOOKUP_NORMAL, use_global_delete,
491                          complain);
492 }
493
494 /* Report an error if the indicated template declaration is not the
495    sort of thing that should be a member template.  */
496
497 void
498 check_member_template (tree tmpl)
499 {
500   tree decl;
501
502   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
503   decl = DECL_TEMPLATE_RESULT (tmpl);
504
505   if (TREE_CODE (decl) == FUNCTION_DECL
506       || DECL_ALIAS_TEMPLATE_P (tmpl)
507       || (TREE_CODE (decl) == TYPE_DECL
508           && MAYBE_CLASS_TYPE_P (TREE_TYPE (decl))))
509     {
510       /* The parser rejects template declarations in local classes.  */
511       gcc_assert (!current_function_decl);
512       /* The parser rejects any use of virtual in a function template.  */
513       gcc_assert (!(TREE_CODE (decl) == FUNCTION_DECL
514                     && DECL_VIRTUAL_P (decl)));
515
516       /* The debug-information generating code doesn't know what to do
517          with member templates.  */
518       DECL_IGNORED_P (tmpl) = 1;
519     }
520   else
521     error ("template declaration of %q#D", decl);
522 }
523
524 /* Return true iff TYPE is a valid Java parameter or return type.  */
525
526 static bool
527 acceptable_java_type (tree type)
528 {
529   if (type == error_mark_node)
530     return false;
531
532   if (TREE_CODE (type) == VOID_TYPE || TYPE_FOR_JAVA (type))
533     return true;
534   if (TREE_CODE (type) == POINTER_TYPE || TREE_CODE (type) == REFERENCE_TYPE)
535     {
536       type = TREE_TYPE (type);
537       if (TREE_CODE (type) == RECORD_TYPE)
538         {
539           tree args;  int i;
540           if (! TYPE_FOR_JAVA (type))
541             return false;
542           if (! CLASSTYPE_TEMPLATE_INFO (type))
543             return true;
544           args = CLASSTYPE_TI_ARGS (type);
545           i = TREE_VEC_LENGTH (args);
546           while (--i >= 0)
547             {
548               type = TREE_VEC_ELT (args, i);
549               if (TREE_CODE (type) == POINTER_TYPE)
550                 type = TREE_TYPE (type);
551               if (! TYPE_FOR_JAVA (type))
552                 return false;
553             }
554           return true;
555         }
556     }
557   return false;
558 }
559
560 /* For a METHOD in a Java class CTYPE, return true if
561    the parameter and return types are valid Java types.
562    Otherwise, print appropriate error messages, and return false.  */
563
564 bool
565 check_java_method (tree method)
566 {
567   bool jerr = false;
568   tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (method));
569   tree ret_type = TREE_TYPE (TREE_TYPE (method));
570
571   if (!acceptable_java_type (ret_type))
572     {
573       error ("Java method %qD has non-Java return type %qT",
574              method, ret_type);
575       jerr = true;
576     }
577
578   arg_types = TREE_CHAIN (arg_types);
579   if (DECL_HAS_IN_CHARGE_PARM_P (method))
580     arg_types = TREE_CHAIN (arg_types);
581   if (DECL_HAS_VTT_PARM_P (method))
582     arg_types = TREE_CHAIN (arg_types);
583
584   for (; arg_types != NULL_TREE; arg_types = TREE_CHAIN (arg_types))
585     {
586       tree type = TREE_VALUE (arg_types);
587       if (!acceptable_java_type (type))
588         {
589           if (type != error_mark_node)
590             error ("Java method %qD has non-Java parameter type %qT",
591                    method, type);
592           jerr = true;
593         }
594     }
595   return !jerr;
596 }
597
598 /* Sanity check: report error if this function FUNCTION is not
599    really a member of the class (CTYPE) it is supposed to belong to.
600    TEMPLATE_PARMS is used to specify the template parameters of a member
601    template passed as FUNCTION_DECL. If the member template is passed as a
602    TEMPLATE_DECL, it can be NULL since the parameters can be extracted
603    from the declaration. If the function is not a function template, it
604    must be NULL.
605    It returns the original declaration for the function, NULL_TREE if
606    no declaration was found, error_mark_node if an error was emitted.  */
607
608 tree
609 check_classfn (tree ctype, tree function, tree template_parms)
610 {
611   int ix;
612   bool is_template;
613   tree pushed_scope;
614   
615   if (DECL_USE_TEMPLATE (function)
616       && !(TREE_CODE (function) == TEMPLATE_DECL
617            && DECL_TEMPLATE_SPECIALIZATION (function))
618       && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (function)))
619     /* Since this is a specialization of a member template,
620        we're not going to find the declaration in the class.
621        For example, in:
622
623          struct S { template <typename T> void f(T); };
624          template <> void S::f(int);
625
626        we're not going to find `S::f(int)', but there's no
627        reason we should, either.  We let our callers know we didn't
628        find the method, but we don't complain.  */
629     return NULL_TREE;
630
631   /* Basic sanity check: for a template function, the template parameters
632      either were not passed, or they are the same of DECL_TEMPLATE_PARMS.  */
633   if (TREE_CODE (function) == TEMPLATE_DECL)
634     {
635       if (template_parms
636           && !comp_template_parms (template_parms,
637                                    DECL_TEMPLATE_PARMS (function)))
638         {
639           error ("template parameter lists provided don%'t match the "
640                  "template parameters of %qD", function);
641           return error_mark_node;
642         }
643       template_parms = DECL_TEMPLATE_PARMS (function);
644     }
645
646   /* OK, is this a definition of a member template?  */
647   is_template = (template_parms != NULL_TREE);
648
649   /* We must enter the scope here, because conversion operators are
650      named by target type, and type equivalence relies on typenames
651      resolving within the scope of CTYPE.  */
652   pushed_scope = push_scope (ctype);
653   ix = class_method_index_for_fn (complete_type (ctype), function);
654   if (ix >= 0)
655     {
656       vec<tree, va_gc> *methods = CLASSTYPE_METHOD_VEC (ctype);
657       tree fndecls, fndecl = 0;
658       bool is_conv_op;
659       const char *format = NULL;
660
661       for (fndecls = (*methods)[ix];
662            fndecls; fndecls = OVL_NEXT (fndecls))
663         {
664           tree p1, p2;
665
666           fndecl = OVL_CURRENT (fndecls);
667           p1 = TYPE_ARG_TYPES (TREE_TYPE (function));
668           p2 = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
669
670           /* We cannot simply call decls_match because this doesn't
671              work for static member functions that are pretending to
672              be methods, and because the name may have been changed by
673              asm("new_name").  */
674
675            /* Get rid of the this parameter on functions that become
676               static.  */
677           if (DECL_STATIC_FUNCTION_P (fndecl)
678               && TREE_CODE (TREE_TYPE (function)) == METHOD_TYPE)
679             p1 = TREE_CHAIN (p1);
680
681           /* A member template definition only matches a member template
682              declaration.  */
683           if (is_template != (TREE_CODE (fndecl) == TEMPLATE_DECL))
684             continue;
685
686           /* ref-qualifier or absence of same must match.  */
687           if (type_memfn_rqual (TREE_TYPE (function))
688               != type_memfn_rqual (TREE_TYPE (fndecl)))
689             continue;
690
691           /* While finding a match, same types and params are not enough
692              if the function is versioned.  Also check version ("target")
693              attributes.  */
694           if (same_type_p (TREE_TYPE (TREE_TYPE (function)),
695                            TREE_TYPE (TREE_TYPE (fndecl)))
696               && compparms (p1, p2)
697               && !targetm.target_option.function_versions (function, fndecl)
698               && (!is_template
699                   || comp_template_parms (template_parms,
700                                           DECL_TEMPLATE_PARMS (fndecl)))
701               && (DECL_TEMPLATE_SPECIALIZATION (function)
702                   == DECL_TEMPLATE_SPECIALIZATION (fndecl))
703               && (!DECL_TEMPLATE_SPECIALIZATION (function)
704                   || (DECL_TI_TEMPLATE (function)
705                       == DECL_TI_TEMPLATE (fndecl))))
706             break;
707         }
708       if (fndecls)
709         {
710           if (pushed_scope)
711             pop_scope (pushed_scope);
712           return OVL_CURRENT (fndecls);
713         }
714       
715       error_at (DECL_SOURCE_LOCATION (function),
716                 "prototype for %q#D does not match any in class %qT",
717                 function, ctype);
718       is_conv_op = DECL_CONV_FN_P (fndecl);
719
720       if (is_conv_op)
721         ix = CLASSTYPE_FIRST_CONVERSION_SLOT;
722       fndecls = (*methods)[ix];
723       while (fndecls)
724         {
725           fndecl = OVL_CURRENT (fndecls);
726           fndecls = OVL_NEXT (fndecls);
727
728           if (!fndecls && is_conv_op)
729             {
730               if (methods->length () > (size_t) ++ix)
731                 {
732                   fndecls = (*methods)[ix];
733                   if (!DECL_CONV_FN_P (OVL_CURRENT (fndecls)))
734                     {
735                       fndecls = NULL_TREE;
736                       is_conv_op = false;
737                     }
738                 }
739               else
740                 is_conv_op = false;
741             }
742           if (format)
743             format = "                %+#D";
744           else if (fndecls)
745             format = N_("candidates are: %+#D");
746           else
747             format = N_("candidate is: %+#D");
748           error (format, fndecl);
749         }
750     }
751   else if (!COMPLETE_TYPE_P (ctype))
752     cxx_incomplete_type_error (function, ctype);
753   else
754     error ("no %q#D member function declared in class %qT",
755            function, ctype);
756
757   if (pushed_scope)
758     pop_scope (pushed_scope);
759   return error_mark_node;
760 }
761
762 /* DECL is a function with vague linkage.  Remember it so that at the
763    end of the translation unit we can decide whether or not to emit
764    it.  */
765
766 void
767 note_vague_linkage_fn (tree decl)
768 {
769   DECL_DEFER_OUTPUT (decl) = 1;
770   vec_safe_push (deferred_fns, decl);
771 }
772
773 /* We have just processed the DECL, which is a static data member.
774    The other parameters are as for cp_finish_decl.  */
775
776 void
777 finish_static_data_member_decl (tree decl,
778                                 tree init, bool init_const_expr_p,
779                                 tree asmspec_tree,
780                                 int flags)
781 {
782   DECL_CONTEXT (decl) = current_class_type;
783
784   /* We cannot call pushdecl here, because that would fill in the
785      TREE_CHAIN of our decl.  Instead, we modify cp_finish_decl to do
786      the right thing, namely, to put this decl out straight away.  */
787
788   if (! processing_template_decl)
789     vec_safe_push (pending_statics, decl);
790
791   if (LOCAL_CLASS_P (current_class_type)
792       /* We already complained about the template definition.  */
793       && !DECL_TEMPLATE_INSTANTIATION (decl))
794     permerror (input_location, "local class %q#T shall not have static data member %q#D",
795                current_class_type, decl);
796
797   DECL_IN_AGGR_P (decl) = 1;
798
799   if (TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE
800       && TYPE_DOMAIN (TREE_TYPE (decl)) == NULL_TREE)
801     SET_VAR_HAD_UNKNOWN_BOUND (decl);
802
803   cp_finish_decl (decl, init, init_const_expr_p, asmspec_tree, flags);
804 }
805
806 /* DECLARATOR and DECLSPECS correspond to a class member.  The other
807    parameters are as for cp_finish_decl.  Return the DECL for the
808    class member declared.  */
809
810 tree
811 grokfield (const cp_declarator *declarator,
812            cp_decl_specifier_seq *declspecs,
813            tree init, bool init_const_expr_p,
814            tree asmspec_tree,
815            tree attrlist)
816 {
817   tree value;
818   const char *asmspec = 0;
819   int flags;
820   tree name;
821
822   if (init
823       && TREE_CODE (init) == TREE_LIST
824       && TREE_VALUE (init) == error_mark_node
825       && TREE_CHAIN (init) == NULL_TREE)
826     init = NULL_TREE;
827
828   value = grokdeclarator (declarator, declspecs, FIELD, init != 0, &attrlist);
829   if (! value || error_operand_p (value))
830     /* friend or constructor went bad.  */
831     return error_mark_node;
832
833   if (TREE_CODE (value) == TYPE_DECL && init)
834     {
835       error ("typedef %qD is initialized (use decltype instead)", value);
836       init = NULL_TREE;
837     }
838
839   /* Pass friendly classes back.  */
840   if (value == void_type_node)
841     return value;
842
843   /* Pass friend decls back.  */
844   if ((TREE_CODE (value) == FUNCTION_DECL
845        || TREE_CODE (value) == TEMPLATE_DECL)
846       && DECL_CONTEXT (value) != current_class_type)
847     return value;
848
849   name = DECL_NAME (value);
850
851   if (name != NULL_TREE)
852     {
853       if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
854         {
855           error ("explicit template argument list not allowed");
856           return error_mark_node;
857         }
858
859       if (IDENTIFIER_POINTER (name)[0] == '_'
860           && ! strcmp (IDENTIFIER_POINTER (name), "_vptr"))
861         error ("member %qD conflicts with virtual function table field name",
862                value);
863     }
864
865   /* Stash away type declarations.  */
866   if (TREE_CODE (value) == TYPE_DECL)
867     {
868       DECL_NONLOCAL (value) = 1;
869       DECL_CONTEXT (value) = current_class_type;
870
871       if (attrlist)
872         {
873           int attrflags = 0;
874
875           /* If this is a typedef that names the class for linkage purposes
876              (7.1.3p8), apply any attributes directly to the type.  */
877           if (TAGGED_TYPE_P (TREE_TYPE (value))
878               && value == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value))))
879             attrflags = ATTR_FLAG_TYPE_IN_PLACE;
880
881           cplus_decl_attributes (&value, attrlist, attrflags);
882         }
883
884       if (decl_spec_seq_has_spec_p (declspecs, ds_typedef)
885           && TREE_TYPE (value) != error_mark_node
886           && TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value))) != value)
887         set_underlying_type (value);
888
889       /* It's important that push_template_decl below follows
890          set_underlying_type above so that the created template
891          carries the properly set type of VALUE.  */
892       if (processing_template_decl)
893         value = push_template_decl (value);
894
895       record_locally_defined_typedef (value);
896       return value;
897     }
898
899   if (DECL_IN_AGGR_P (value))
900     {
901       error ("%qD is already defined in %qT", value, DECL_CONTEXT (value));
902       return void_type_node;
903     }
904
905   if (asmspec_tree && asmspec_tree != error_mark_node)
906     asmspec = TREE_STRING_POINTER (asmspec_tree);
907
908   if (init)
909     {
910       if (TREE_CODE (value) == FUNCTION_DECL)
911         {
912           /* Initializers for functions are rejected early in the parser.
913              If we get here, it must be a pure specifier for a method.  */
914           if (init == ridpointers[(int)RID_DELETE])
915             {
916               DECL_DELETED_FN (value) = 1;
917               DECL_DECLARED_INLINE_P (value) = 1;
918               DECL_INITIAL (value) = error_mark_node;
919             }
920           else if (init == ridpointers[(int)RID_DEFAULT])
921             {
922               if (defaultable_fn_check (value))
923                 {
924                   DECL_DEFAULTED_FN (value) = 1;
925                   DECL_INITIALIZED_IN_CLASS_P (value) = 1;
926                   DECL_DECLARED_INLINE_P (value) = 1;
927                 }
928             }
929           else if (TREE_CODE (init) == DEFAULT_ARG)
930             error ("invalid initializer for member function %qD", value);
931           else if (TREE_CODE (TREE_TYPE (value)) == METHOD_TYPE)
932             {
933               if (integer_zerop (init))
934                 DECL_PURE_VIRTUAL_P (value) = 1;
935               else if (error_operand_p (init))
936                 ; /* An error has already been reported.  */
937               else
938                 error ("invalid initializer for member function %qD",
939                        value);
940             }
941           else
942             {
943               gcc_assert (TREE_CODE (TREE_TYPE (value)) == FUNCTION_TYPE);
944               error ("initializer specified for static member function %qD",
945                      value);
946             }
947         }
948       else if (TREE_CODE (value) == FIELD_DECL)
949         /* C++11 NSDMI, keep going.  */;
950       else if (TREE_CODE (value) != VAR_DECL)
951         gcc_unreachable ();
952       else if (!processing_template_decl)
953         {
954           if (TREE_CODE (init) == CONSTRUCTOR)
955             init = digest_init (TREE_TYPE (value), init, tf_warning_or_error);
956           init = maybe_constant_init (init);
957
958           if (init != error_mark_node && !TREE_CONSTANT (init))
959             {
960               /* We can allow references to things that are effectively
961                  static, since references are initialized with the
962                  address.  */
963               if (TREE_CODE (TREE_TYPE (value)) != REFERENCE_TYPE
964                   || (TREE_STATIC (init) == 0
965                       && (!DECL_P (init) || DECL_EXTERNAL (init) == 0)))
966                 {
967                   error ("field initializer is not constant");
968                   init = error_mark_node;
969                 }
970             }
971         }
972     }
973
974   if (processing_template_decl
975       && (TREE_CODE (value) == VAR_DECL || TREE_CODE (value) == FUNCTION_DECL))
976     {
977       value = push_template_decl (value);
978       if (error_operand_p (value))
979         return error_mark_node;
980     }
981
982   if (attrlist)
983     cplus_decl_attributes (&value, attrlist, 0);
984
985   if (init && BRACE_ENCLOSED_INITIALIZER_P (init)
986       && CONSTRUCTOR_IS_DIRECT_INIT (init))
987     flags = LOOKUP_NORMAL;
988   else
989     flags = LOOKUP_IMPLICIT;
990
991   switch (TREE_CODE (value))
992     {
993     case VAR_DECL:
994       finish_static_data_member_decl (value, init, init_const_expr_p,
995                                       asmspec_tree, flags);
996       return value;
997
998     case FIELD_DECL:
999       if (asmspec)
1000         error ("%<asm%> specifiers are not permitted on non-static data members");
1001       if (DECL_INITIAL (value) == error_mark_node)
1002         init = error_mark_node;
1003       cp_finish_decl (value, init, /*init_const_expr_p=*/false,
1004                       NULL_TREE, flags);
1005       DECL_IN_AGGR_P (value) = 1;
1006       return value;
1007
1008     case  FUNCTION_DECL:
1009       if (asmspec)
1010         set_user_assembler_name (value, asmspec);
1011
1012       cp_finish_decl (value,
1013                       /*init=*/NULL_TREE,
1014                       /*init_const_expr_p=*/false,
1015                       asmspec_tree, flags);
1016
1017       /* Pass friends back this way.  */
1018       if (DECL_FRIEND_P (value))
1019         return void_type_node;
1020
1021       DECL_IN_AGGR_P (value) = 1;
1022       return value;
1023
1024     default:
1025       gcc_unreachable ();
1026     }
1027   return NULL_TREE;
1028 }
1029
1030 /* Like `grokfield', but for bitfields.
1031    WIDTH is non-NULL for bit fields only, and is an INTEGER_CST node.  */
1032
1033 tree
1034 grokbitfield (const cp_declarator *declarator,
1035               cp_decl_specifier_seq *declspecs, tree width,
1036               tree attrlist)
1037 {
1038   tree value = grokdeclarator (declarator, declspecs, BITFIELD, 0, &attrlist);
1039
1040   if (value == error_mark_node) 
1041     return NULL_TREE; /* friends went bad.  */
1042
1043   /* Pass friendly classes back.  */
1044   if (TREE_CODE (value) == VOID_TYPE)
1045     return void_type_node;
1046
1047   if (!INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (value))
1048       && (POINTER_TYPE_P (value)
1049           || !dependent_type_p (TREE_TYPE (value))))
1050     {
1051       error ("bit-field %qD with non-integral type", value);
1052       return error_mark_node;
1053     }
1054
1055   if (TREE_CODE (value) == TYPE_DECL)
1056     {
1057       error ("cannot declare %qD to be a bit-field type", value);
1058       return NULL_TREE;
1059     }
1060
1061   /* Usually, finish_struct_1 catches bitfields with invalid types.
1062      But, in the case of bitfields with function type, we confuse
1063      ourselves into thinking they are member functions, so we must
1064      check here.  */
1065   if (TREE_CODE (value) == FUNCTION_DECL)
1066     {
1067       error ("cannot declare bit-field %qD with function type",
1068              DECL_NAME (value));
1069       return NULL_TREE;
1070     }
1071
1072   if (DECL_IN_AGGR_P (value))
1073     {
1074       error ("%qD is already defined in the class %qT", value,
1075              DECL_CONTEXT (value));
1076       return void_type_node;
1077     }
1078
1079   if (TREE_STATIC (value))
1080     {
1081       error ("static member %qD cannot be a bit-field", value);
1082       return NULL_TREE;
1083     }
1084   cp_finish_decl (value, NULL_TREE, false, NULL_TREE, 0);
1085
1086   if (width != error_mark_node)
1087     {
1088       /* The width must be an integer type.  */
1089       if (!type_dependent_expression_p (width)
1090           && !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (width)))
1091         error ("width of bit-field %qD has non-integral type %qT", value,
1092                TREE_TYPE (width));
1093       DECL_INITIAL (value) = width;
1094       SET_DECL_C_BIT_FIELD (value);
1095     }
1096
1097   DECL_IN_AGGR_P (value) = 1;
1098
1099   if (attrlist)
1100     cplus_decl_attributes (&value, attrlist, /*flags=*/0);
1101
1102   return value;
1103 }
1104
1105 \f
1106 /* Returns true iff ATTR is an attribute which needs to be applied at
1107    instantiation time rather than template definition time.  */
1108
1109 static bool
1110 is_late_template_attribute (tree attr, tree decl)
1111 {
1112   tree name = get_attribute_name (attr);
1113   tree args = TREE_VALUE (attr);
1114   const struct attribute_spec *spec = lookup_attribute_spec (name);
1115   tree arg;
1116
1117   if (!spec)
1118     /* Unknown attribute.  */
1119     return false;
1120
1121   /* Attribute weak handling wants to write out assembly right away.  */
1122   if (is_attribute_p ("weak", name))
1123     return true;
1124
1125   /* Attribute unused is applied directly, as it appertains to
1126      decls. */
1127   if (is_attribute_p ("unused", name))
1128     return false;
1129
1130   /* If any of the arguments are dependent expressions, we can't evaluate
1131      the attribute until instantiation time.  */
1132   for (arg = args; arg; arg = TREE_CHAIN (arg))
1133     {
1134       tree t = TREE_VALUE (arg);
1135
1136       /* If the first attribute argument is an identifier, only consider
1137          second and following arguments.  Attributes like mode, format,
1138          cleanup and several target specific attributes aren't late
1139          just because they have an IDENTIFIER_NODE as first argument.  */
1140       if (arg == args && TREE_CODE (t) == IDENTIFIER_NODE)
1141         continue;
1142
1143       if (value_dependent_expression_p (t)
1144           || type_dependent_expression_p (t))
1145         return true;
1146     }
1147
1148   if (TREE_CODE (decl) == TYPE_DECL
1149       || TYPE_P (decl)
1150       || spec->type_required)
1151     {
1152       tree type = TYPE_P (decl) ? decl : TREE_TYPE (decl);
1153
1154       /* We can't apply any attributes to a completely unknown type until
1155          instantiation time.  */
1156       enum tree_code code = TREE_CODE (type);
1157       if (code == TEMPLATE_TYPE_PARM
1158           || code == BOUND_TEMPLATE_TEMPLATE_PARM
1159           || code == TYPENAME_TYPE)
1160         return true;
1161       /* Also defer most attributes on dependent types.  This is not
1162          necessary in all cases, but is the better default.  */
1163       else if (dependent_type_p (type)
1164                /* But attribute visibility specifically works on
1165                   templates.  */
1166                && !is_attribute_p ("visibility", name))
1167         return true;
1168       else
1169         return false;
1170     }
1171   else
1172     return false;
1173 }
1174
1175 /* ATTR_P is a list of attributes.  Remove any attributes which need to be
1176    applied at instantiation time and return them.  If IS_DEPENDENT is true,
1177    the declaration itself is dependent, so all attributes should be applied
1178    at instantiation time.  */
1179
1180 static tree
1181 splice_template_attributes (tree *attr_p, tree decl)
1182 {
1183   tree *p = attr_p;
1184   tree late_attrs = NULL_TREE;
1185   tree *q = &late_attrs;
1186
1187   if (!p)
1188     return NULL_TREE;
1189
1190   for (; *p; )
1191     {
1192       if (is_late_template_attribute (*p, decl))
1193         {
1194           ATTR_IS_DEPENDENT (*p) = 1;
1195           *q = *p;
1196           *p = TREE_CHAIN (*p);
1197           q = &TREE_CHAIN (*q);
1198           *q = NULL_TREE;
1199         }
1200       else
1201         p = &TREE_CHAIN (*p);
1202     }
1203
1204   return late_attrs;
1205 }
1206
1207 /* Remove any late attributes from the list in ATTR_P and attach them to
1208    DECL_P.  */
1209
1210 static void
1211 save_template_attributes (tree *attr_p, tree *decl_p)
1212 {
1213   tree late_attrs = splice_template_attributes (attr_p, *decl_p);
1214   tree *q;
1215   tree old_attrs = NULL_TREE;
1216
1217   if (!late_attrs)
1218     return;
1219
1220   if (DECL_P (*decl_p))
1221     q = &DECL_ATTRIBUTES (*decl_p);
1222   else
1223     q = &TYPE_ATTRIBUTES (*decl_p);
1224
1225   old_attrs = *q;
1226
1227   /* Merge the late attributes at the beginning with the attribute
1228      list.  */
1229   late_attrs = merge_attributes (late_attrs, *q);
1230   *q = late_attrs;
1231
1232   if (!DECL_P (*decl_p) && *decl_p == TYPE_MAIN_VARIANT (*decl_p))
1233     {
1234       /* We've added new attributes directly to the main variant, so
1235          now we need to update all of the other variants to include
1236          these new attributes.  */
1237       tree variant;
1238       for (variant = TYPE_NEXT_VARIANT (*decl_p); variant;
1239            variant = TYPE_NEXT_VARIANT (variant))
1240         {
1241           gcc_assert (TYPE_ATTRIBUTES (variant) == old_attrs);
1242           TYPE_ATTRIBUTES (variant) = TYPE_ATTRIBUTES (*decl_p);
1243         }
1244     }
1245 }
1246
1247 /* Like reconstruct_complex_type, but handle also template trees.  */
1248
1249 tree
1250 cp_reconstruct_complex_type (tree type, tree bottom)
1251 {
1252   tree inner, outer;
1253
1254   if (TREE_CODE (type) == POINTER_TYPE)
1255     {
1256       inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1257       outer = build_pointer_type_for_mode (inner, TYPE_MODE (type),
1258                                            TYPE_REF_CAN_ALIAS_ALL (type));
1259     }
1260   else if (TREE_CODE (type) == REFERENCE_TYPE)
1261     {
1262       inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1263       outer = build_reference_type_for_mode (inner, TYPE_MODE (type),
1264                                              TYPE_REF_CAN_ALIAS_ALL (type));
1265     }
1266   else if (TREE_CODE (type) == ARRAY_TYPE)
1267     {
1268       inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1269       outer = build_cplus_array_type (inner, TYPE_DOMAIN (type));
1270       /* Don't call cp_build_qualified_type on ARRAY_TYPEs, the
1271          element type qualification will be handled by the recursive
1272          cp_reconstruct_complex_type call and cp_build_qualified_type
1273          for ARRAY_TYPEs changes the element type.  */
1274       return outer;
1275     }
1276   else if (TREE_CODE (type) == FUNCTION_TYPE)
1277     {
1278       inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1279       outer = build_function_type (inner, TYPE_ARG_TYPES (type));
1280       outer = apply_memfn_quals (outer,
1281                                  type_memfn_quals (type),
1282                                  type_memfn_rqual (type));
1283     }
1284   else if (TREE_CODE (type) == METHOD_TYPE)
1285     {
1286       inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1287       /* The build_method_type_directly() routine prepends 'this' to argument list,
1288          so we must compensate by getting rid of it.  */
1289       outer
1290         = build_method_type_directly
1291             (class_of_this_parm (type), inner,
1292              TREE_CHAIN (TYPE_ARG_TYPES (type)));
1293     }
1294   else if (TREE_CODE (type) == OFFSET_TYPE)
1295     {
1296       inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1297       outer = build_offset_type (TYPE_OFFSET_BASETYPE (type), inner);
1298     }
1299   else
1300     return bottom;
1301
1302   if (TYPE_ATTRIBUTES (type))
1303     outer = cp_build_type_attribute_variant (outer, TYPE_ATTRIBUTES (type));
1304   return cp_build_qualified_type (outer, cp_type_quals (type));
1305 }
1306
1307 /* Replaces any constexpr expression that may be into the attributes
1308    arguments with their reduced value.  */
1309
1310 static void
1311 cp_check_const_attributes (tree attributes)
1312 {
1313   tree attr;
1314   for (attr = attributes; attr; attr = TREE_CHAIN (attr))
1315     {
1316       tree arg;
1317       for (arg = TREE_VALUE (attr); arg; arg = TREE_CHAIN (arg))
1318         {
1319           tree expr = TREE_VALUE (arg);
1320           if (EXPR_P (expr))
1321             TREE_VALUE (arg) = maybe_constant_value (expr);
1322         }
1323     }
1324 }
1325
1326 /* Like decl_attributes, but handle C++ complexity.  */
1327
1328 void
1329 cplus_decl_attributes (tree *decl, tree attributes, int flags)
1330 {
1331   if (*decl == NULL_TREE || *decl == void_type_node
1332       || *decl == error_mark_node)
1333     return;
1334
1335   if (processing_template_decl)
1336     {
1337       if (check_for_bare_parameter_packs (attributes))
1338         return;
1339
1340       save_template_attributes (&attributes, decl);
1341     }
1342
1343   cp_check_const_attributes (attributes);
1344
1345   if (TREE_CODE (*decl) == TEMPLATE_DECL)
1346     decl = &DECL_TEMPLATE_RESULT (*decl);
1347
1348   decl_attributes (decl, attributes, flags);
1349
1350   if (TREE_CODE (*decl) == TYPE_DECL)
1351     SET_IDENTIFIER_TYPE_VALUE (DECL_NAME (*decl), TREE_TYPE (*decl));
1352 }
1353 \f
1354 /* Walks through the namespace- or function-scope anonymous union
1355    OBJECT, with the indicated TYPE, building appropriate VAR_DECLs.
1356    Returns one of the fields for use in the mangled name.  */
1357
1358 static tree
1359 build_anon_union_vars (tree type, tree object)
1360 {
1361   tree main_decl = NULL_TREE;
1362   tree field;
1363
1364   /* Rather than write the code to handle the non-union case,
1365      just give an error.  */
1366   if (TREE_CODE (type) != UNION_TYPE)
1367     {
1368       error ("anonymous struct not inside named type");
1369       return error_mark_node;
1370     }
1371
1372   for (field = TYPE_FIELDS (type);
1373        field != NULL_TREE;
1374        field = DECL_CHAIN (field))
1375     {
1376       tree decl;
1377       tree ref;
1378
1379       if (DECL_ARTIFICIAL (field))
1380         continue;
1381       if (TREE_CODE (field) != FIELD_DECL)
1382         {
1383           permerror (input_location, "%q+#D invalid; an anonymous union can only "
1384                      "have non-static data members", field);
1385           continue;
1386         }
1387
1388       if (TREE_PRIVATE (field))
1389         permerror (input_location, "private member %q+#D in anonymous union", field);
1390       else if (TREE_PROTECTED (field))
1391         permerror (input_location, "protected member %q+#D in anonymous union", field);
1392
1393       if (processing_template_decl)
1394         ref = build_min_nt_loc (UNKNOWN_LOCATION, COMPONENT_REF, object,
1395                                 DECL_NAME (field), NULL_TREE);
1396       else
1397         ref = build_class_member_access_expr (object, field, NULL_TREE,
1398                                               false, tf_warning_or_error);
1399
1400       if (DECL_NAME (field))
1401         {
1402           tree base;
1403
1404           decl = build_decl (input_location,
1405                              VAR_DECL, DECL_NAME (field), TREE_TYPE (field));
1406           DECL_ANON_UNION_VAR_P (decl) = 1;
1407           DECL_ARTIFICIAL (decl) = 1;
1408
1409           base = get_base_address (object);
1410           TREE_PUBLIC (decl) = TREE_PUBLIC (base);
1411           TREE_STATIC (decl) = TREE_STATIC (base);
1412           DECL_EXTERNAL (decl) = DECL_EXTERNAL (base);
1413
1414           SET_DECL_VALUE_EXPR (decl, ref);
1415           DECL_HAS_VALUE_EXPR_P (decl) = 1;
1416
1417           decl = pushdecl (decl);
1418         }
1419       else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1420         decl = build_anon_union_vars (TREE_TYPE (field), ref);
1421       else
1422         decl = 0;
1423
1424       if (main_decl == NULL_TREE)
1425         main_decl = decl;
1426     }
1427
1428   return main_decl;
1429 }
1430
1431 /* Finish off the processing of a UNION_TYPE structure.  If the union is an
1432    anonymous union, then all members must be laid out together.  PUBLIC_P
1433    is nonzero if this union is not declared static.  */
1434
1435 void
1436 finish_anon_union (tree anon_union_decl)
1437 {
1438   tree type;
1439   tree main_decl;
1440   bool public_p;
1441
1442   if (anon_union_decl == error_mark_node)
1443     return;
1444
1445   type = TREE_TYPE (anon_union_decl);
1446   public_p = TREE_PUBLIC (anon_union_decl);
1447
1448   /* The VAR_DECL's context is the same as the TYPE's context.  */
1449   DECL_CONTEXT (anon_union_decl) = DECL_CONTEXT (TYPE_NAME (type));
1450
1451   if (TYPE_FIELDS (type) == NULL_TREE)
1452     return;
1453
1454   if (public_p)
1455     {
1456       error ("namespace-scope anonymous aggregates must be static");
1457       return;
1458     }
1459
1460   main_decl = build_anon_union_vars (type, anon_union_decl);
1461   if (main_decl == error_mark_node)
1462     return;
1463   if (main_decl == NULL_TREE)
1464     {
1465       warning (0, "anonymous union with no members");
1466       return;
1467     }
1468
1469   if (!processing_template_decl)
1470     {
1471       /* Use main_decl to set the mangled name.  */
1472       DECL_NAME (anon_union_decl) = DECL_NAME (main_decl);
1473       maybe_commonize_var (anon_union_decl);
1474       if (TREE_STATIC (anon_union_decl) || DECL_EXTERNAL (anon_union_decl))
1475         mangle_decl (anon_union_decl);
1476       DECL_NAME (anon_union_decl) = NULL_TREE;
1477     }
1478
1479   pushdecl (anon_union_decl);
1480   cp_finish_decl (anon_union_decl, NULL_TREE, false, NULL_TREE, 0);
1481 }
1482 \f
1483 /* Auxiliary functions to make type signatures for
1484    `operator new' and `operator delete' correspond to
1485    what compiler will be expecting.  */
1486
1487 tree
1488 coerce_new_type (tree type)
1489 {
1490   int e = 0;
1491   tree args = TYPE_ARG_TYPES (type);
1492
1493   gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
1494
1495   if (!same_type_p (TREE_TYPE (type), ptr_type_node))
1496     {
1497       e = 1;
1498       error ("%<operator new%> must return type %qT", ptr_type_node);
1499     }
1500
1501   if (args && args != void_list_node)
1502     {
1503       if (TREE_PURPOSE (args))
1504         {
1505           /* [basic.stc.dynamic.allocation]
1506              
1507              The first parameter shall not have an associated default
1508              argument.  */
1509           error ("the first parameter of %<operator new%> cannot "
1510                  "have a default argument");
1511           /* Throw away the default argument.  */
1512           TREE_PURPOSE (args) = NULL_TREE;
1513         }
1514
1515       if (!same_type_p (TREE_VALUE (args), size_type_node))
1516         {
1517           e = 2;
1518           args = TREE_CHAIN (args);
1519         }
1520     }
1521   else
1522     e = 2;
1523
1524   if (e == 2)
1525     permerror (input_location, "%<operator new%> takes type %<size_t%> (%qT) "
1526                "as first parameter", size_type_node);
1527
1528   switch (e)
1529   {
1530     case 2:
1531       args = tree_cons (NULL_TREE, size_type_node, args);
1532       /* Fall through.  */
1533     case 1:
1534       type = build_exception_variant
1535               (build_function_type (ptr_type_node, args),
1536                TYPE_RAISES_EXCEPTIONS (type));
1537       /* Fall through.  */
1538     default:;
1539   }
1540   return type;
1541 }
1542
1543 tree
1544 coerce_delete_type (tree type)
1545 {
1546   int e = 0;
1547   tree args = TYPE_ARG_TYPES (type);
1548
1549   gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
1550
1551   if (!same_type_p (TREE_TYPE (type), void_type_node))
1552     {
1553       e = 1;
1554       error ("%<operator delete%> must return type %qT", void_type_node);
1555     }
1556
1557   if (!args || args == void_list_node
1558       || !same_type_p (TREE_VALUE (args), ptr_type_node))
1559     {
1560       e = 2;
1561       if (args && args != void_list_node)
1562         args = TREE_CHAIN (args);
1563       error ("%<operator delete%> takes type %qT as first parameter",
1564              ptr_type_node);
1565     }
1566   switch (e)
1567   {
1568     case 2:
1569       args = tree_cons (NULL_TREE, ptr_type_node, args);
1570       /* Fall through.  */
1571     case 1:
1572       type = build_exception_variant
1573               (build_function_type (void_type_node, args),
1574                TYPE_RAISES_EXCEPTIONS (type));
1575       /* Fall through.  */
1576     default:;
1577   }
1578
1579   return type;
1580 }
1581 \f
1582 /* DECL is a VAR_DECL for a vtable: walk through the entries in the vtable
1583    and mark them as needed.  */
1584
1585 static void
1586 mark_vtable_entries (tree decl)
1587 {
1588   tree fnaddr;
1589   unsigned HOST_WIDE_INT idx;
1590
1591   FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (DECL_INITIAL (decl)),
1592                               idx, fnaddr)
1593     {
1594       tree fn;
1595
1596       STRIP_NOPS (fnaddr);
1597
1598       if (TREE_CODE (fnaddr) != ADDR_EXPR
1599           && TREE_CODE (fnaddr) != FDESC_EXPR)
1600         /* This entry is an offset: a virtual base class offset, a
1601            virtual call offset, an RTTI offset, etc.  */
1602         continue;
1603
1604       fn = TREE_OPERAND (fnaddr, 0);
1605       TREE_ADDRESSABLE (fn) = 1;
1606       /* When we don't have vcall offsets, we output thunks whenever
1607          we output the vtables that contain them.  With vcall offsets,
1608          we know all the thunks we'll need when we emit a virtual
1609          function, so we emit the thunks there instead.  */
1610       if (DECL_THUNK_P (fn))
1611         use_thunk (fn, /*emit_p=*/0);
1612       mark_used (fn);
1613     }
1614 }
1615
1616 /* Set DECL up to have the closest approximation of "initialized common"
1617    linkage available.  */
1618
1619 void
1620 comdat_linkage (tree decl)
1621 {
1622   if (flag_weak)
1623     make_decl_one_only (decl, cxx_comdat_group (decl));
1624   else if (TREE_CODE (decl) == FUNCTION_DECL
1625            || (TREE_CODE (decl) == VAR_DECL && DECL_ARTIFICIAL (decl)))
1626     /* We can just emit function and compiler-generated variables
1627        statically; having multiple copies is (for the most part) only
1628        a waste of space.
1629
1630        There are two correctness issues, however: the address of a
1631        template instantiation with external linkage should be the
1632        same, independent of what translation unit asks for the
1633        address, and this will not hold when we emit multiple copies of
1634        the function.  However, there's little else we can do.
1635
1636        Also, by default, the typeinfo implementation assumes that
1637        there will be only one copy of the string used as the name for
1638        each type.  Therefore, if weak symbols are unavailable, the
1639        run-time library should perform a more conservative check; it
1640        should perform a string comparison, rather than an address
1641        comparison.  */
1642     TREE_PUBLIC (decl) = 0;
1643   else
1644     {
1645       /* Static data member template instantiations, however, cannot
1646          have multiple copies.  */
1647       if (DECL_INITIAL (decl) == 0
1648           || DECL_INITIAL (decl) == error_mark_node)
1649         DECL_COMMON (decl) = 1;
1650       else if (EMPTY_CONSTRUCTOR_P (DECL_INITIAL (decl)))
1651         {
1652           DECL_COMMON (decl) = 1;
1653           DECL_INITIAL (decl) = error_mark_node;
1654         }
1655       else if (!DECL_EXPLICIT_INSTANTIATION (decl))
1656         {
1657           /* We can't do anything useful; leave vars for explicit
1658              instantiation.  */
1659           DECL_EXTERNAL (decl) = 1;
1660           DECL_NOT_REALLY_EXTERN (decl) = 0;
1661         }
1662     }
1663
1664   DECL_COMDAT (decl) = 1;
1665 }
1666
1667 /* For win32 we also want to put explicit instantiations in
1668    linkonce sections, so that they will be merged with implicit
1669    instantiations; otherwise we get duplicate symbol errors.
1670    For Darwin we do not want explicit instantiations to be
1671    linkonce.  */
1672
1673 void
1674 maybe_make_one_only (tree decl)
1675 {
1676   /* We used to say that this was not necessary on targets that support weak
1677      symbols, because the implicit instantiations will defer to the explicit
1678      one.  However, that's not actually the case in SVR4; a strong definition
1679      after a weak one is an error.  Also, not making explicit
1680      instantiations one_only means that we can end up with two copies of
1681      some template instantiations.  */
1682   if (! flag_weak)
1683     return;
1684
1685   /* We can't set DECL_COMDAT on functions, or cp_finish_file will think
1686      we can get away with not emitting them if they aren't used.  We need
1687      to for variables so that cp_finish_decl will update their linkage,
1688      because their DECL_INITIAL may not have been set properly yet.  */
1689
1690   if (!TARGET_WEAK_NOT_IN_ARCHIVE_TOC
1691       || (! DECL_EXPLICIT_INSTANTIATION (decl)
1692           && ! DECL_TEMPLATE_SPECIALIZATION (decl)))
1693     {
1694       make_decl_one_only (decl, cxx_comdat_group (decl));
1695
1696       if (TREE_CODE (decl) == VAR_DECL)
1697         {
1698           DECL_COMDAT (decl) = 1;
1699           /* Mark it needed so we don't forget to emit it.  */
1700           mark_decl_referenced (decl);
1701           TREE_USED (decl) = 1;
1702         }
1703     }
1704 }
1705
1706 /* Returns true iff DECL, a FUNCTION_DECL or VAR_DECL, has vague linkage.
1707    This predicate will give the right answer during parsing of the
1708    function, which other tests may not.  */
1709
1710 bool
1711 vague_linkage_p (tree decl)
1712 {
1713   /* Unfortunately, import_export_decl has not always been called
1714      before the function is processed, so we cannot simply check
1715      DECL_COMDAT.  */
1716   return (DECL_COMDAT (decl)
1717           || (((TREE_CODE (decl) == FUNCTION_DECL
1718                 && DECL_DECLARED_INLINE_P (decl))
1719                || (DECL_LANG_SPECIFIC (decl)
1720                    && DECL_TEMPLATE_INSTANTIATION (decl)))
1721               && TREE_PUBLIC (decl)));
1722 }
1723
1724 /* Determine whether or not we want to specifically import or export CTYPE,
1725    using various heuristics.  */
1726
1727 static void
1728 import_export_class (tree ctype)
1729 {
1730   /* -1 for imported, 1 for exported.  */
1731   int import_export = 0;
1732
1733   /* It only makes sense to call this function at EOF.  The reason is
1734      that this function looks at whether or not the first non-inline
1735      non-abstract virtual member function has been defined in this
1736      translation unit.  But, we can't possibly know that until we've
1737      seen the entire translation unit.  */
1738   gcc_assert (at_eof);
1739
1740   if (CLASSTYPE_INTERFACE_KNOWN (ctype))
1741     return;
1742
1743   /* If MULTIPLE_SYMBOL_SPACES is set and we saw a #pragma interface,
1744      we will have CLASSTYPE_INTERFACE_ONLY set but not
1745      CLASSTYPE_INTERFACE_KNOWN.  In that case, we don't want to use this
1746      heuristic because someone will supply a #pragma implementation
1747      elsewhere, and deducing it here would produce a conflict.  */
1748   if (CLASSTYPE_INTERFACE_ONLY (ctype))
1749     return;
1750
1751   if (lookup_attribute ("dllimport", TYPE_ATTRIBUTES (ctype)))
1752     import_export = -1;
1753   else if (lookup_attribute ("dllexport", TYPE_ATTRIBUTES (ctype)))
1754     import_export = 1;
1755   else if (CLASSTYPE_IMPLICIT_INSTANTIATION (ctype)
1756            && !flag_implicit_templates)
1757     /* For a template class, without -fimplicit-templates, check the
1758        repository.  If the virtual table is assigned to this
1759        translation unit, then export the class; otherwise, import
1760        it.  */
1761       import_export = repo_export_class_p (ctype) ? 1 : -1;
1762   else if (TYPE_POLYMORPHIC_P (ctype))
1763     {
1764       /* The ABI specifies that the virtual table and associated
1765          information are emitted with the key method, if any.  */
1766       tree method = CLASSTYPE_KEY_METHOD (ctype);
1767       /* If weak symbol support is not available, then we must be
1768          careful not to emit the vtable when the key function is
1769          inline.  An inline function can be defined in multiple
1770          translation units.  If we were to emit the vtable in each
1771          translation unit containing a definition, we would get
1772          multiple definition errors at link-time.  */
1773       if (method && (flag_weak || ! DECL_DECLARED_INLINE_P (method)))
1774         import_export = (DECL_REALLY_EXTERN (method) ? -1 : 1);
1775     }
1776
1777   /* When MULTIPLE_SYMBOL_SPACES is set, we cannot count on seeing
1778      a definition anywhere else.  */
1779   if (MULTIPLE_SYMBOL_SPACES && import_export == -1)
1780     import_export = 0;
1781
1782   /* Allow back ends the chance to overrule the decision.  */
1783   if (targetm.cxx.import_export_class)
1784     import_export = targetm.cxx.import_export_class (ctype, import_export);
1785
1786   if (import_export)
1787     {
1788       SET_CLASSTYPE_INTERFACE_KNOWN (ctype);
1789       CLASSTYPE_INTERFACE_ONLY (ctype) = (import_export < 0);
1790     }
1791 }
1792
1793 /* Return true if VAR has already been provided to the back end; in that
1794    case VAR should not be modified further by the front end.  */
1795 static bool
1796 var_finalized_p (tree var)
1797 {
1798   return varpool_node_for_decl (var)->finalized;
1799 }
1800
1801 /* DECL is a VAR_DECL or FUNCTION_DECL which, for whatever reason,
1802    must be emitted in this translation unit.  Mark it as such.  */
1803
1804 void
1805 mark_needed (tree decl)
1806 {
1807   TREE_USED (decl) = 1;
1808   mark_decl_referenced (decl);
1809 }
1810
1811 /* DECL is either a FUNCTION_DECL or a VAR_DECL.  This function
1812    returns true if a definition of this entity should be provided in
1813    this object file.  Callers use this function to determine whether
1814    or not to let the back end know that a definition of DECL is
1815    available in this translation unit.  */
1816
1817 bool
1818 decl_needed_p (tree decl)
1819 {
1820   gcc_assert (TREE_CODE (decl) == VAR_DECL
1821               || TREE_CODE (decl) == FUNCTION_DECL);
1822   /* This function should only be called at the end of the translation
1823      unit.  We cannot be sure of whether or not something will be
1824      COMDAT until that point.  */
1825   gcc_assert (at_eof);
1826
1827   /* All entities with external linkage that are not COMDAT should be
1828      emitted; they may be referred to from other object files.  */
1829   if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl))
1830     return true;
1831   /* If this entity was used, let the back end see it; it will decide
1832      whether or not to emit it into the object file.  */
1833   if (TREE_USED (decl))
1834       return true;
1835   /* Functions marked "dllexport" must be emitted so that they are
1836      visible to other DLLs.  */
1837   if (flag_keep_inline_dllexport
1838       && lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))
1839     return true;
1840   /* Otherwise, DECL does not need to be emitted -- yet.  A subsequent
1841      reference to DECL might cause it to be emitted later.  */
1842   return false;
1843 }
1844
1845 /* If necessary, write out the vtables for the dynamic class CTYPE.
1846    Returns true if any vtables were emitted.  */
1847
1848 static bool
1849 maybe_emit_vtables (tree ctype)
1850 {
1851   tree vtbl;
1852   tree primary_vtbl;
1853   int needed = 0;
1854   struct varpool_node *current = NULL, *last = NULL;
1855
1856   /* If the vtables for this class have already been emitted there is
1857      nothing more to do.  */
1858   primary_vtbl = CLASSTYPE_VTABLES (ctype);
1859   if (var_finalized_p (primary_vtbl))
1860     return false;
1861   /* Ignore dummy vtables made by get_vtable_decl.  */
1862   if (TREE_TYPE (primary_vtbl) == void_type_node)
1863     return false;
1864
1865   /* On some targets, we cannot determine the key method until the end
1866      of the translation unit -- which is when this function is
1867      called.  */
1868   if (!targetm.cxx.key_method_may_be_inline ())
1869     determine_key_method (ctype);
1870
1871   /* See if any of the vtables are needed.  */
1872   for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl))
1873     {
1874       import_export_decl (vtbl);
1875       if (DECL_NOT_REALLY_EXTERN (vtbl) && decl_needed_p (vtbl))
1876         needed = 1;
1877     }
1878   if (!needed)
1879     {
1880       /* If the references to this class' vtables are optimized away,
1881          still emit the appropriate debugging information.  See
1882          dfs_debug_mark.  */
1883       if (DECL_COMDAT (primary_vtbl)
1884           && CLASSTYPE_DEBUG_REQUESTED (ctype))
1885         note_debug_info_needed (ctype);
1886       return false;
1887     }
1888
1889   /* The ABI requires that we emit all of the vtables if we emit any
1890      of them.  */
1891   for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl))
1892     {
1893       /* Mark entities references from the virtual table as used.  */
1894       mark_vtable_entries (vtbl);
1895
1896       if (TREE_TYPE (DECL_INITIAL (vtbl)) == 0)
1897         {
1898           vec<tree, va_gc> *cleanups = NULL;
1899           tree expr = store_init_value (vtbl, DECL_INITIAL (vtbl), &cleanups,
1900                                         LOOKUP_NORMAL);
1901
1902           /* It had better be all done at compile-time.  */
1903           gcc_assert (!expr && !cleanups);
1904         }
1905
1906       /* Write it out.  */
1907       DECL_EXTERNAL (vtbl) = 0;
1908       rest_of_decl_compilation (vtbl, 1, 1);
1909
1910       /* Because we're only doing syntax-checking, we'll never end up
1911          actually marking the variable as written.  */
1912       if (flag_syntax_only)
1913         TREE_ASM_WRITTEN (vtbl) = 1;
1914       else if (DECL_ONE_ONLY (vtbl))
1915         {
1916           current = varpool_node_for_decl (vtbl);
1917           if (last)
1918             symtab_add_to_same_comdat_group ((symtab_node) current, (symtab_node) last);
1919           last = current;
1920         }
1921     }
1922
1923   /* Since we're writing out the vtable here, also write the debug
1924      info.  */
1925   note_debug_info_needed (ctype);
1926
1927   return true;
1928 }
1929
1930 /* A special return value from type_visibility meaning internal
1931    linkage.  */
1932
1933 enum { VISIBILITY_ANON = VISIBILITY_INTERNAL+1 };
1934
1935 /* walk_tree helper function for type_visibility.  */
1936
1937 static tree
1938 min_vis_r (tree *tp, int *walk_subtrees, void *data)
1939 {
1940   int *vis_p = (int *)data;
1941   if (! TYPE_P (*tp))
1942     {
1943       *walk_subtrees = 0;
1944     }
1945   else if (TAGGED_TYPE_P (*tp)
1946            && !TREE_PUBLIC (TYPE_MAIN_DECL (*tp)))
1947     {
1948       *vis_p = VISIBILITY_ANON;
1949       return *tp;
1950     }
1951   else if (CLASS_TYPE_P (*tp)
1952            && CLASSTYPE_VISIBILITY (*tp) > *vis_p)
1953     *vis_p = CLASSTYPE_VISIBILITY (*tp);
1954   return NULL;
1955 }
1956
1957 /* Returns the visibility of TYPE, which is the minimum visibility of its
1958    component types.  */
1959
1960 static int
1961 type_visibility (tree type)
1962 {
1963   int vis = VISIBILITY_DEFAULT;
1964   cp_walk_tree_without_duplicates (&type, min_vis_r, &vis);
1965   return vis;
1966 }
1967
1968 /* Limit the visibility of DECL to VISIBILITY, if not explicitly
1969    specified (or if VISIBILITY is static).  If TMPL is true, this
1970    constraint is for a template argument, and takes precedence
1971    over explicitly-specified visibility on the template.  */
1972
1973 static void
1974 constrain_visibility (tree decl, int visibility, bool tmpl)
1975 {
1976   if (visibility == VISIBILITY_ANON)
1977     {
1978       /* extern "C" declarations aren't affected by the anonymous
1979          namespace.  */
1980       if (!DECL_EXTERN_C_P (decl))
1981         {
1982           TREE_PUBLIC (decl) = 0;
1983           DECL_WEAK (decl) = 0;
1984           DECL_COMMON (decl) = 0;
1985           DECL_COMDAT_GROUP (decl) = NULL_TREE;
1986           DECL_INTERFACE_KNOWN (decl) = 1;
1987           if (DECL_LANG_SPECIFIC (decl))
1988             DECL_NOT_REALLY_EXTERN (decl) = 1;
1989         }
1990     }
1991   else if (visibility > DECL_VISIBILITY (decl)
1992            && (tmpl || !DECL_VISIBILITY_SPECIFIED (decl)))
1993     {
1994       DECL_VISIBILITY (decl) = (enum symbol_visibility) visibility;
1995       /* This visibility was not specified.  */
1996       DECL_VISIBILITY_SPECIFIED (decl) = false;
1997     }
1998 }
1999
2000 /* Constrain the visibility of DECL based on the visibility of its template
2001    arguments.  */
2002
2003 static void
2004 constrain_visibility_for_template (tree decl, tree targs)
2005 {
2006   /* If this is a template instantiation, check the innermost
2007      template args for visibility constraints.  The outer template
2008      args are covered by the class check.  */
2009   tree args = INNERMOST_TEMPLATE_ARGS (targs);
2010   int i;
2011   for (i = TREE_VEC_LENGTH (args); i > 0; --i)
2012     {
2013       int vis = 0;
2014
2015       tree arg = TREE_VEC_ELT (args, i-1);
2016       if (TYPE_P (arg))
2017         vis = type_visibility (arg);
2018       else if (TREE_TYPE (arg) && POINTER_TYPE_P (TREE_TYPE (arg)))
2019         {
2020           STRIP_NOPS (arg);
2021           if (TREE_CODE (arg) == ADDR_EXPR)
2022             arg = TREE_OPERAND (arg, 0);
2023           if (TREE_CODE (arg) == VAR_DECL
2024               || TREE_CODE (arg) == FUNCTION_DECL)
2025             {
2026               if (! TREE_PUBLIC (arg))
2027                 vis = VISIBILITY_ANON;
2028               else
2029                 vis = DECL_VISIBILITY (arg);
2030             }
2031         }
2032       if (vis)
2033         constrain_visibility (decl, vis, true);
2034     }
2035 }
2036
2037 /* Like c_determine_visibility, but with additional C++-specific
2038    behavior.
2039
2040    Function-scope entities can rely on the function's visibility because
2041    it is set in start_preparsed_function.
2042
2043    Class-scope entities cannot rely on the class's visibility until the end
2044    of the enclosing class definition.
2045
2046    Note that because namespaces have multiple independent definitions,
2047    namespace visibility is handled elsewhere using the #pragma visibility
2048    machinery rather than by decorating the namespace declaration.
2049
2050    The goal is for constraints from the type to give a diagnostic, and
2051    other constraints to be applied silently.  */
2052
2053 void
2054 determine_visibility (tree decl)
2055 {
2056   tree class_type = NULL_TREE;
2057   bool use_template;
2058   bool orig_visibility_specified;
2059   enum symbol_visibility orig_visibility;
2060
2061   /* Remember that all decls get VISIBILITY_DEFAULT when built.  */
2062
2063   /* Only relevant for names with external linkage.  */
2064   if (!TREE_PUBLIC (decl))
2065     return;
2066
2067   /* Cloned constructors and destructors get the same visibility as
2068      the underlying function.  That should be set up in
2069      maybe_clone_body.  */
2070   gcc_assert (!DECL_CLONED_FUNCTION_P (decl));
2071
2072   orig_visibility_specified = DECL_VISIBILITY_SPECIFIED (decl);
2073   orig_visibility = DECL_VISIBILITY (decl);
2074
2075   if (TREE_CODE (decl) == TYPE_DECL)
2076     {
2077       if (CLASS_TYPE_P (TREE_TYPE (decl)))
2078         use_template = CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl));
2079       else if (TYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
2080         use_template = 1;
2081       else
2082         use_template = 0;
2083     }
2084   else if (DECL_LANG_SPECIFIC (decl))
2085     use_template = DECL_USE_TEMPLATE (decl);
2086   else
2087     use_template = 0;
2088
2089   /* If DECL is a member of a class, visibility specifiers on the
2090      class can influence the visibility of the DECL.  */
2091   if (DECL_CLASS_SCOPE_P (decl))
2092     class_type = DECL_CONTEXT (decl);
2093   else
2094     {
2095       /* Not a class member.  */
2096
2097       /* Virtual tables have DECL_CONTEXT set to their associated class,
2098          so they are automatically handled above.  */
2099       gcc_assert (TREE_CODE (decl) != VAR_DECL
2100                   || !DECL_VTABLE_OR_VTT_P (decl));
2101
2102       if (DECL_FUNCTION_SCOPE_P (decl) && ! DECL_VISIBILITY_SPECIFIED (decl))
2103         {
2104           /* Local statics and classes get the visibility of their
2105              containing function by default, except that
2106              -fvisibility-inlines-hidden doesn't affect them.  */
2107           tree fn = DECL_CONTEXT (decl);
2108           if (DECL_VISIBILITY_SPECIFIED (fn))
2109             {
2110               DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn);
2111               DECL_VISIBILITY_SPECIFIED (decl) = 
2112                 DECL_VISIBILITY_SPECIFIED (fn);
2113             }
2114           else
2115             {
2116               if (DECL_CLASS_SCOPE_P (fn))
2117                 determine_visibility_from_class (decl, DECL_CONTEXT (fn));
2118               else if (determine_hidden_inline (fn))
2119                 {
2120                   DECL_VISIBILITY (decl) = default_visibility;
2121                   DECL_VISIBILITY_SPECIFIED (decl) =
2122                     visibility_options.inpragma;
2123                 }
2124               else
2125                 {
2126                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn);
2127                   DECL_VISIBILITY_SPECIFIED (decl) =
2128                     DECL_VISIBILITY_SPECIFIED (fn);
2129                 }
2130             }
2131
2132           /* Local classes in templates have CLASSTYPE_USE_TEMPLATE set,
2133              but have no TEMPLATE_INFO, so don't try to check it.  */
2134           use_template = 0;
2135         }
2136       else if (TREE_CODE (decl) == VAR_DECL && DECL_TINFO_P (decl)
2137                && flag_visibility_ms_compat)
2138         {
2139           /* Under -fvisibility-ms-compat, types are visible by default,
2140              even though their contents aren't.  */
2141           tree underlying_type = TREE_TYPE (DECL_NAME (decl));
2142           int underlying_vis = type_visibility (underlying_type);
2143           if (underlying_vis == VISIBILITY_ANON
2144               || (CLASS_TYPE_P (underlying_type)
2145                   && CLASSTYPE_VISIBILITY_SPECIFIED (underlying_type)))
2146             constrain_visibility (decl, underlying_vis, false);
2147           else
2148             DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
2149         }
2150       else if (TREE_CODE (decl) == VAR_DECL && DECL_TINFO_P (decl))
2151         {
2152           /* tinfo visibility is based on the type it's for.  */
2153           constrain_visibility
2154             (decl, type_visibility (TREE_TYPE (DECL_NAME (decl))), false);
2155
2156           /* Give the target a chance to override the visibility associated
2157              with DECL.  */
2158           if (TREE_PUBLIC (decl)
2159               && !DECL_REALLY_EXTERN (decl)
2160               && CLASS_TYPE_P (TREE_TYPE (DECL_NAME (decl)))
2161               && !CLASSTYPE_VISIBILITY_SPECIFIED (TREE_TYPE (DECL_NAME (decl))))
2162             targetm.cxx.determine_class_data_visibility (decl);
2163         }
2164       else if (use_template)
2165         /* Template instantiations and specializations get visibility based
2166            on their template unless they override it with an attribute.  */;
2167       else if (! DECL_VISIBILITY_SPECIFIED (decl))
2168         {
2169           if (determine_hidden_inline (decl))
2170             DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2171           else
2172             {
2173               /* Set default visibility to whatever the user supplied with
2174                  #pragma GCC visibility or a namespace visibility attribute.  */
2175               DECL_VISIBILITY (decl) = default_visibility;
2176               DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma;
2177             }
2178         }
2179     }
2180
2181   if (use_template)
2182     {
2183       /* If the specialization doesn't specify visibility, use the
2184          visibility from the template.  */
2185       tree tinfo = (TREE_CODE (decl) == TYPE_DECL
2186                     ? TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
2187                     : DECL_TEMPLATE_INFO (decl));
2188       tree args = TI_ARGS (tinfo);
2189       tree attribs = (TREE_CODE (decl) == TYPE_DECL
2190                       ? TYPE_ATTRIBUTES (TREE_TYPE (decl))
2191                       : DECL_ATTRIBUTES (decl));
2192       
2193       if (args != error_mark_node)
2194         {
2195           tree pattern = DECL_TEMPLATE_RESULT (TI_TEMPLATE (tinfo));
2196
2197           if (!DECL_VISIBILITY_SPECIFIED (decl))
2198             {
2199               if (!DECL_VISIBILITY_SPECIFIED (pattern)
2200                   && determine_hidden_inline (decl))
2201                 DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2202               else
2203                 {
2204                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (pattern);
2205                   DECL_VISIBILITY_SPECIFIED (decl)
2206                     = DECL_VISIBILITY_SPECIFIED (pattern);
2207                 }
2208             }
2209
2210           if (args
2211               /* Template argument visibility outweighs #pragma or namespace
2212                  visibility, but not an explicit attribute.  */
2213               && !lookup_attribute ("visibility", attribs))
2214             {
2215               int depth = TMPL_ARGS_DEPTH (args);
2216               if (DECL_VISIBILITY_SPECIFIED (decl))
2217                 {
2218                   /* A class template member with explicit visibility
2219                      overrides the class visibility, so we need to apply
2220                      all the levels of template args directly.  */
2221                   int i;
2222                   for (i = 1; i <= depth; ++i)
2223                     {
2224                       tree lev = TMPL_ARGS_LEVEL (args, i);
2225                       constrain_visibility_for_template (decl, lev);
2226                     }
2227                 }
2228               else if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
2229                 /* Limit visibility based on its template arguments.  */
2230                 constrain_visibility_for_template (decl, args);
2231             }
2232         }
2233     }
2234
2235   if (class_type)
2236     determine_visibility_from_class (decl, class_type);
2237
2238   if (decl_anon_ns_mem_p (decl))
2239     /* Names in an anonymous namespace get internal linkage.
2240        This might change once we implement export.  */
2241     constrain_visibility (decl, VISIBILITY_ANON, false);
2242   else if (TREE_CODE (decl) != TYPE_DECL)
2243     {
2244       /* Propagate anonymity from type to decl.  */
2245       int tvis = type_visibility (TREE_TYPE (decl));
2246       if (tvis == VISIBILITY_ANON
2247           || ! DECL_VISIBILITY_SPECIFIED (decl))
2248         constrain_visibility (decl, tvis, false);
2249     }
2250   else if (no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/true))
2251     /* DR 757: A type without linkage shall not be used as the type of a
2252        variable or function with linkage, unless
2253        o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
2254        o the variable or function is not used (3.2 [basic.def.odr]) or is
2255        defined in the same translation unit.
2256
2257        Since non-extern "C" decls need to be defined in the same
2258        translation unit, we can make the type internal.  */
2259     constrain_visibility (decl, VISIBILITY_ANON, false);
2260
2261   /* If visibility changed and DECL already has DECL_RTL, ensure
2262      symbol flags are updated.  */
2263   if ((DECL_VISIBILITY (decl) != orig_visibility
2264        || DECL_VISIBILITY_SPECIFIED (decl) != orig_visibility_specified)
2265       && ((TREE_CODE (decl) == VAR_DECL && TREE_STATIC (decl))
2266           || TREE_CODE (decl) == FUNCTION_DECL)
2267       && DECL_RTL_SET_P (decl))
2268     make_decl_rtl (decl);
2269 }
2270
2271 /* By default, static data members and function members receive
2272    the visibility of their containing class.  */
2273
2274 static void
2275 determine_visibility_from_class (tree decl, tree class_type)
2276 {
2277   if (DECL_VISIBILITY_SPECIFIED (decl))
2278     return;
2279
2280   if (determine_hidden_inline (decl))
2281     DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2282   else
2283     {
2284       /* Default to the class visibility.  */
2285       DECL_VISIBILITY (decl) = CLASSTYPE_VISIBILITY (class_type);
2286       DECL_VISIBILITY_SPECIFIED (decl)
2287         = CLASSTYPE_VISIBILITY_SPECIFIED (class_type);
2288     }
2289
2290   /* Give the target a chance to override the visibility associated
2291      with DECL.  */
2292   if (TREE_CODE (decl) == VAR_DECL
2293       && (DECL_TINFO_P (decl)
2294           || (DECL_VTABLE_OR_VTT_P (decl)
2295               /* Construction virtual tables are not exported because
2296                  they cannot be referred to from other object files;
2297                  their name is not standardized by the ABI.  */
2298               && !DECL_CONSTRUCTION_VTABLE_P (decl)))
2299       && TREE_PUBLIC (decl)
2300       && !DECL_REALLY_EXTERN (decl)
2301       && !CLASSTYPE_VISIBILITY_SPECIFIED (class_type))
2302     targetm.cxx.determine_class_data_visibility (decl);
2303 }
2304
2305 /* Returns true iff DECL is an inline that should get hidden visibility
2306    because of -fvisibility-inlines-hidden.  */
2307
2308 static bool
2309 determine_hidden_inline (tree decl)
2310 {
2311   return (visibility_options.inlines_hidden
2312           /* Don't do this for inline templates; specializations might not be
2313              inline, and we don't want them to inherit the hidden
2314              visibility.  We'll set it here for all inline instantiations.  */
2315           && !processing_template_decl
2316           && TREE_CODE (decl) == FUNCTION_DECL
2317           && DECL_DECLARED_INLINE_P (decl)
2318           && (! DECL_LANG_SPECIFIC (decl)
2319               || ! DECL_EXPLICIT_INSTANTIATION (decl)));
2320 }
2321
2322 /* Constrain the visibility of a class TYPE based on the visibility of its
2323    field types.  Warn if any fields require lesser visibility.  */
2324
2325 void
2326 constrain_class_visibility (tree type)
2327 {
2328   tree binfo;
2329   tree t;
2330   int i;
2331
2332   int vis = type_visibility (type);
2333
2334   if (vis == VISIBILITY_ANON
2335       || DECL_IN_SYSTEM_HEADER (TYPE_MAIN_DECL (type)))
2336     return;
2337
2338   /* Don't warn about visibility if the class has explicit visibility.  */
2339   if (CLASSTYPE_VISIBILITY_SPECIFIED (type))
2340     vis = VISIBILITY_INTERNAL;
2341
2342   for (t = TYPE_FIELDS (type); t; t = DECL_CHAIN (t))
2343     if (TREE_CODE (t) == FIELD_DECL && TREE_TYPE (t) != error_mark_node)
2344       {
2345         tree ftype = strip_pointer_or_array_types (TREE_TYPE (t));
2346         int subvis = type_visibility (ftype);
2347
2348         if (subvis == VISIBILITY_ANON)
2349           {
2350             if (!in_main_input_context ())
2351               warning (0, "\
2352 %qT has a field %qD whose type uses the anonymous namespace",
2353                        type, t);
2354           }
2355         else if (MAYBE_CLASS_TYPE_P (ftype)
2356                  && vis < VISIBILITY_HIDDEN
2357                  && subvis >= VISIBILITY_HIDDEN)
2358           warning (OPT_Wattributes, "\
2359 %qT declared with greater visibility than the type of its field %qD",
2360                    type, t);
2361       }
2362
2363   binfo = TYPE_BINFO (type);
2364   for (i = 0; BINFO_BASE_ITERATE (binfo, i, t); ++i)
2365     {
2366       int subvis = type_visibility (TREE_TYPE (t));
2367
2368       if (subvis == VISIBILITY_ANON)
2369         {
2370           if (!in_main_input_context())
2371             warning (0, "\
2372 %qT has a base %qT whose type uses the anonymous namespace",
2373                      type, TREE_TYPE (t));
2374         }
2375       else if (vis < VISIBILITY_HIDDEN
2376                && subvis >= VISIBILITY_HIDDEN)
2377         warning (OPT_Wattributes, "\
2378 %qT declared with greater visibility than its base %qT",
2379                  type, TREE_TYPE (t));
2380     }
2381 }
2382
2383 /* DECL is a FUNCTION_DECL or VAR_DECL.  If the object file linkage
2384    for DECL has not already been determined, do so now by setting
2385    DECL_EXTERNAL, DECL_COMDAT and other related flags.  Until this
2386    function is called entities with vague linkage whose definitions
2387    are available must have TREE_PUBLIC set.
2388
2389    If this function decides to place DECL in COMDAT, it will set
2390    appropriate flags -- but will not clear DECL_EXTERNAL.  It is up to
2391    the caller to decide whether or not to clear DECL_EXTERNAL.  Some
2392    callers defer that decision until it is clear that DECL is actually
2393    required.  */
2394
2395 void
2396 import_export_decl (tree decl)
2397 {
2398   int emit_p;
2399   bool comdat_p;
2400   bool import_p;
2401   tree class_type = NULL_TREE;
2402
2403   if (DECL_INTERFACE_KNOWN (decl))
2404     return;
2405
2406   /* We cannot determine what linkage to give to an entity with vague
2407      linkage until the end of the file.  For example, a virtual table
2408      for a class will be defined if and only if the key method is
2409      defined in this translation unit.  As a further example, consider
2410      that when compiling a translation unit that uses PCH file with
2411      "-frepo" it would be incorrect to make decisions about what
2412      entities to emit when building the PCH; those decisions must be
2413      delayed until the repository information has been processed.  */
2414   gcc_assert (at_eof);
2415   /* Object file linkage for explicit instantiations is handled in
2416      mark_decl_instantiated.  For static variables in functions with
2417      vague linkage, maybe_commonize_var is used.
2418
2419      Therefore, the only declarations that should be provided to this
2420      function are those with external linkage that are:
2421
2422      * implicit instantiations of function templates
2423
2424      * inline function
2425
2426      * implicit instantiations of static data members of class
2427        templates
2428
2429      * virtual tables
2430
2431      * typeinfo objects
2432
2433      Furthermore, all entities that reach this point must have a
2434      definition available in this translation unit.
2435
2436      The following assertions check these conditions.  */
2437   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
2438               || TREE_CODE (decl) == VAR_DECL);
2439   /* Any code that creates entities with TREE_PUBLIC cleared should
2440      also set DECL_INTERFACE_KNOWN.  */
2441   gcc_assert (TREE_PUBLIC (decl));
2442   if (TREE_CODE (decl) == FUNCTION_DECL)
2443     gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
2444                 || DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
2445                 || DECL_DECLARED_INLINE_P (decl));
2446   else
2447     gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
2448                 || DECL_VTABLE_OR_VTT_P (decl)
2449                 || DECL_TINFO_P (decl));
2450   /* Check that a definition of DECL is available in this translation
2451      unit.  */
2452   gcc_assert (!DECL_REALLY_EXTERN (decl));
2453
2454   /* Assume that DECL will not have COMDAT linkage.  */
2455   comdat_p = false;
2456   /* Assume that DECL will not be imported into this translation
2457      unit.  */
2458   import_p = false;
2459
2460   /* See if the repository tells us whether or not to emit DECL in
2461      this translation unit.  */
2462   emit_p = repo_emit_p (decl);
2463   if (emit_p == 0)
2464     import_p = true;
2465   else if (emit_p == 1)
2466     {
2467       /* The repository indicates that this entity should be defined
2468          here.  Make sure the back end honors that request.  */
2469       if (TREE_CODE (decl) == VAR_DECL)
2470         mark_needed (decl);
2471       else if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl)
2472                || DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (decl))
2473         {
2474           tree clone;
2475           FOR_EACH_CLONE (clone, decl)
2476             mark_needed (clone);
2477         }
2478       else
2479         mark_needed (decl);
2480       /* Output the definition as an ordinary strong definition.  */
2481       DECL_EXTERNAL (decl) = 0;
2482       DECL_INTERFACE_KNOWN (decl) = 1;
2483       return;
2484     }
2485
2486   if (import_p)
2487     /* We have already decided what to do with this DECL; there is no
2488        need to check anything further.  */
2489     ;
2490   else if (TREE_CODE (decl) == VAR_DECL && DECL_VTABLE_OR_VTT_P (decl))
2491     {
2492       class_type = DECL_CONTEXT (decl);
2493       import_export_class (class_type);
2494       if (TYPE_FOR_JAVA (class_type))
2495         import_p = true;
2496       else if (CLASSTYPE_INTERFACE_KNOWN (class_type)
2497                && CLASSTYPE_INTERFACE_ONLY (class_type))
2498         import_p = true;
2499       else if ((!flag_weak || TARGET_WEAK_NOT_IN_ARCHIVE_TOC)
2500                && !CLASSTYPE_USE_TEMPLATE (class_type)
2501                && CLASSTYPE_KEY_METHOD (class_type)
2502                && !DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type)))
2503         /* The ABI requires that all virtual tables be emitted with
2504            COMDAT linkage.  However, on systems where COMDAT symbols
2505            don't show up in the table of contents for a static
2506            archive, or on systems without weak symbols (where we
2507            approximate COMDAT linkage by using internal linkage), the
2508            linker will report errors about undefined symbols because
2509            it will not see the virtual table definition.  Therefore,
2510            in the case that we know that the virtual table will be
2511            emitted in only one translation unit, we make the virtual
2512            table an ordinary definition with external linkage.  */
2513         DECL_EXTERNAL (decl) = 0;
2514       else if (CLASSTYPE_INTERFACE_KNOWN (class_type))
2515         {
2516           /* CLASS_TYPE is being exported from this translation unit,
2517              so DECL should be defined here.  */
2518           if (!flag_weak && CLASSTYPE_EXPLICIT_INSTANTIATION (class_type))
2519             /* If a class is declared in a header with the "extern
2520                template" extension, then it will not be instantiated,
2521                even in translation units that would normally require
2522                it.  Often such classes are explicitly instantiated in
2523                one translation unit.  Therefore, the explicit
2524                instantiation must be made visible to other translation
2525                units.  */
2526             DECL_EXTERNAL (decl) = 0;
2527           else
2528             {
2529               /* The generic C++ ABI says that class data is always
2530                  COMDAT, even if there is a key function.  Some
2531                  variants (e.g., the ARM EABI) says that class data
2532                  only has COMDAT linkage if the class data might be
2533                  emitted in more than one translation unit.  When the
2534                  key method can be inline and is inline, we still have
2535                  to arrange for comdat even though
2536                  class_data_always_comdat is false.  */
2537               if (!CLASSTYPE_KEY_METHOD (class_type)
2538                   || DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type))
2539                   || targetm.cxx.class_data_always_comdat ())
2540                 {
2541                   /* The ABI requires COMDAT linkage.  Normally, we
2542                      only emit COMDAT things when they are needed;
2543                      make sure that we realize that this entity is
2544                      indeed needed.  */
2545                   comdat_p = true;
2546                   mark_needed (decl);
2547                 }
2548             }
2549         }
2550       else if (!flag_implicit_templates
2551                && CLASSTYPE_IMPLICIT_INSTANTIATION (class_type))
2552         import_p = true;
2553       else
2554         comdat_p = true;
2555     }
2556   else if (TREE_CODE (decl) == VAR_DECL && DECL_TINFO_P (decl))
2557     {
2558       tree type = TREE_TYPE (DECL_NAME (decl));
2559       if (CLASS_TYPE_P (type))
2560         {
2561           class_type = type;
2562           import_export_class (type);
2563           if (CLASSTYPE_INTERFACE_KNOWN (type)
2564               && TYPE_POLYMORPHIC_P (type)
2565               && CLASSTYPE_INTERFACE_ONLY (type)
2566               /* If -fno-rtti was specified, then we cannot be sure
2567                  that RTTI information will be emitted with the
2568                  virtual table of the class, so we must emit it
2569                  wherever it is used.  */
2570               && flag_rtti)
2571             import_p = true;
2572           else
2573             {
2574               if (CLASSTYPE_INTERFACE_KNOWN (type)
2575                   && !CLASSTYPE_INTERFACE_ONLY (type))
2576                 {
2577                   comdat_p = (targetm.cxx.class_data_always_comdat ()
2578                               || (CLASSTYPE_KEY_METHOD (type)
2579                                   && DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (type))));
2580                   mark_needed (decl);
2581                   if (!flag_weak)
2582                     {
2583                       comdat_p = false;
2584                       DECL_EXTERNAL (decl) = 0;
2585                     }
2586                 }
2587               else
2588                 comdat_p = true;
2589             }
2590         }
2591       else
2592         comdat_p = true;
2593     }
2594   else if (DECL_TEMPLATE_INSTANTIATION (decl)
2595            || DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl))
2596     {
2597       /* DECL is an implicit instantiation of a function or static
2598          data member.  */
2599       if ((flag_implicit_templates
2600            && !flag_use_repository)
2601           || (flag_implicit_inline_templates
2602               && TREE_CODE (decl) == FUNCTION_DECL
2603               && DECL_DECLARED_INLINE_P (decl)))
2604         comdat_p = true;
2605       else
2606         /* If we are not implicitly generating templates, then mark
2607            this entity as undefined in this translation unit.  */
2608         import_p = true;
2609     }
2610   else if (DECL_FUNCTION_MEMBER_P (decl))
2611     {
2612       if (!DECL_DECLARED_INLINE_P (decl))
2613         {
2614           tree ctype = DECL_CONTEXT (decl);
2615           import_export_class (ctype);
2616           if (CLASSTYPE_INTERFACE_KNOWN (ctype))
2617             {
2618               DECL_NOT_REALLY_EXTERN (decl)
2619                 = ! (CLASSTYPE_INTERFACE_ONLY (ctype)
2620                      || (DECL_DECLARED_INLINE_P (decl)
2621                          && ! flag_implement_inlines
2622                          && !DECL_VINDEX (decl)));
2623
2624               if (!DECL_NOT_REALLY_EXTERN (decl))
2625                 DECL_EXTERNAL (decl) = 1;
2626
2627               /* Always make artificials weak.  */
2628               if (DECL_ARTIFICIAL (decl) && flag_weak)
2629                 comdat_p = true;
2630               else
2631                 maybe_make_one_only (decl);
2632             }
2633         }
2634       else
2635         comdat_p = true;
2636     }
2637   else
2638     comdat_p = true;
2639
2640   if (import_p)
2641     {
2642       /* If we are importing DECL into this translation unit, mark is
2643          an undefined here.  */
2644       DECL_EXTERNAL (decl) = 1;
2645       DECL_NOT_REALLY_EXTERN (decl) = 0;
2646     }
2647   else if (comdat_p)
2648     {
2649       /* If we decided to put DECL in COMDAT, mark it accordingly at
2650          this point.  */
2651       comdat_linkage (decl);
2652     }
2653
2654   DECL_INTERFACE_KNOWN (decl) = 1;
2655 }
2656
2657 /* Return an expression that performs the destruction of DECL, which
2658    must be a VAR_DECL whose type has a non-trivial destructor, or is
2659    an array whose (innermost) elements have a non-trivial destructor.  */
2660
2661 tree
2662 build_cleanup (tree decl)
2663 {
2664   tree temp;
2665   tree type = TREE_TYPE (decl);
2666
2667   /* This function should only be called for declarations that really
2668      require cleanups.  */
2669   gcc_assert (!TYPE_HAS_TRIVIAL_DESTRUCTOR (type));
2670
2671   /* Treat all objects with destructors as used; the destructor may do
2672      something substantive.  */
2673   mark_used (decl);
2674
2675   if (TREE_CODE (type) == ARRAY_TYPE)
2676     temp = decl;
2677   else
2678     temp = build_address (decl);
2679   temp = build_delete (TREE_TYPE (temp), temp,
2680                        sfk_complete_destructor,
2681                        LOOKUP_NORMAL|LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR, 0,
2682                        tf_warning_or_error);
2683   return temp;
2684 }
2685
2686 /* Returns the initialization guard variable for the variable DECL,
2687    which has static storage duration.  */
2688
2689 tree
2690 get_guard (tree decl)
2691 {
2692   tree sname;
2693   tree guard;
2694
2695   sname = mangle_guard_variable (decl);
2696   guard = IDENTIFIER_GLOBAL_VALUE (sname);
2697   if (! guard)
2698     {
2699       tree guard_type;
2700
2701       /* We use a type that is big enough to contain a mutex as well
2702          as an integer counter.  */
2703       guard_type = targetm.cxx.guard_type ();
2704       guard = build_decl (DECL_SOURCE_LOCATION (decl),
2705                           VAR_DECL, sname, guard_type);
2706
2707       /* The guard should have the same linkage as what it guards.  */
2708       TREE_PUBLIC (guard) = TREE_PUBLIC (decl);
2709       TREE_STATIC (guard) = TREE_STATIC (decl);
2710       DECL_COMMON (guard) = DECL_COMMON (decl);
2711       DECL_COMDAT (guard) = DECL_COMDAT (decl);
2712       DECL_TLS_MODEL (guard) = DECL_TLS_MODEL (decl);
2713       if (DECL_ONE_ONLY (decl))
2714         make_decl_one_only (guard, cxx_comdat_group (guard));
2715       if (TREE_PUBLIC (decl))
2716         DECL_WEAK (guard) = DECL_WEAK (decl);
2717       DECL_VISIBILITY (guard) = DECL_VISIBILITY (decl);
2718       DECL_VISIBILITY_SPECIFIED (guard) = DECL_VISIBILITY_SPECIFIED (decl);
2719
2720       DECL_ARTIFICIAL (guard) = 1;
2721       DECL_IGNORED_P (guard) = 1;
2722       TREE_USED (guard) = 1;
2723       pushdecl_top_level_and_finish (guard, NULL_TREE);
2724     }
2725   return guard;
2726 }
2727
2728 /* Return those bits of the GUARD variable that should be set when the
2729    guarded entity is actually initialized.  */
2730
2731 static tree
2732 get_guard_bits (tree guard)
2733 {
2734   if (!targetm.cxx.guard_mask_bit ())
2735     {
2736       /* We only set the first byte of the guard, in order to leave room
2737          for a mutex in the high-order bits.  */
2738       guard = build1 (ADDR_EXPR,
2739                       build_pointer_type (TREE_TYPE (guard)),
2740                       guard);
2741       guard = build1 (NOP_EXPR,
2742                       build_pointer_type (char_type_node),
2743                       guard);
2744       guard = build1 (INDIRECT_REF, char_type_node, guard);
2745     }
2746
2747   return guard;
2748 }
2749
2750 /* Return an expression which determines whether or not the GUARD
2751    variable has already been initialized.  */
2752
2753 tree
2754 get_guard_cond (tree guard)
2755 {
2756   tree guard_value;
2757
2758   /* Check to see if the GUARD is zero.  */
2759   guard = get_guard_bits (guard);
2760
2761   /* Mask off all but the low bit.  */
2762   if (targetm.cxx.guard_mask_bit ())
2763     {
2764       guard_value = integer_one_node;
2765       if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
2766         guard_value = convert (TREE_TYPE (guard), guard_value);
2767       guard = cp_build_binary_op (input_location,
2768                                   BIT_AND_EXPR, guard, guard_value,
2769                                   tf_warning_or_error);
2770     }
2771
2772   guard_value = integer_zero_node;
2773   if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
2774     guard_value = convert (TREE_TYPE (guard), guard_value);
2775   return cp_build_binary_op (input_location,
2776                              EQ_EXPR, guard, guard_value,
2777                              tf_warning_or_error);
2778 }
2779
2780 /* Return an expression which sets the GUARD variable, indicating that
2781    the variable being guarded has been initialized.  */
2782
2783 tree
2784 set_guard (tree guard)
2785 {
2786   tree guard_init;
2787
2788   /* Set the GUARD to one.  */
2789   guard = get_guard_bits (guard);
2790   guard_init = integer_one_node;
2791   if (!same_type_p (TREE_TYPE (guard_init), TREE_TYPE (guard)))
2792     guard_init = convert (TREE_TYPE (guard), guard_init);
2793   return cp_build_modify_expr (guard, NOP_EXPR, guard_init, 
2794                                tf_warning_or_error);
2795 }
2796
2797 /* Returns true iff we can tell that VAR does not have a dynamic
2798    initializer.  */
2799
2800 static bool
2801 var_defined_without_dynamic_init (tree var)
2802 {
2803   /* If it's defined in another TU, we can't tell.  */
2804   if (DECL_EXTERNAL (var))
2805     return false;
2806   /* If it has a non-trivial destructor, registering the destructor
2807      counts as dynamic initialization.  */
2808   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (var)))
2809     return false;
2810   /* If it's in this TU, its initializer has been processed.  */
2811   gcc_assert (DECL_INITIALIZED_P (var));
2812   /* If it has no initializer or a constant one, it's not dynamic.  */
2813   return (!DECL_NONTRIVIALLY_INITIALIZED_P (var)
2814           || DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var));
2815 }
2816
2817 /* Returns true iff VAR is a variable that needs uses to be
2818    wrapped for possible dynamic initialization.  */
2819
2820 static bool
2821 var_needs_tls_wrapper (tree var)
2822 {
2823   return (!error_operand_p (var)
2824           && DECL_THREAD_LOCAL_P (var)
2825           && !DECL_GNU_TLS_P (var)
2826           && !DECL_FUNCTION_SCOPE_P (var)
2827           && !var_defined_without_dynamic_init (var));
2828 }
2829
2830 /* Get the FUNCTION_DECL for the shared TLS init function for this
2831    translation unit.  */
2832
2833 static tree
2834 get_local_tls_init_fn (void)
2835 {
2836   tree sname = get_identifier ("__tls_init");
2837   tree fn = IDENTIFIER_GLOBAL_VALUE (sname);
2838   if (!fn)
2839     {
2840       fn = build_lang_decl (FUNCTION_DECL, sname,
2841                              build_function_type (void_type_node,
2842                                                   void_list_node));
2843       SET_DECL_LANGUAGE (fn, lang_c);
2844       TREE_PUBLIC (fn) = false;
2845       DECL_ARTIFICIAL (fn) = true;
2846       mark_used (fn);
2847       SET_IDENTIFIER_GLOBAL_VALUE (sname, fn);
2848     }
2849   return fn;
2850 }
2851
2852 /* Get a FUNCTION_DECL for the init function for the thread_local
2853    variable VAR.  The init function will be an alias to the function
2854    that initializes all the non-local TLS variables in the translation
2855    unit.  The init function is only used by the wrapper function.  */
2856
2857 static tree
2858 get_tls_init_fn (tree var)
2859 {
2860   /* Only C++11 TLS vars need this init fn.  */
2861   if (!var_needs_tls_wrapper (var))
2862     return NULL_TREE;
2863
2864   /* If -fno-extern-tls-init, assume that we don't need to call
2865      a tls init function for a variable defined in another TU.  */
2866   if (!flag_extern_tls_init && DECL_EXTERNAL (var))
2867     return NULL_TREE;
2868
2869 #ifdef ASM_OUTPUT_DEF
2870   /* If the variable is internal, or if we can't generate aliases,
2871      call the local init function directly.  */
2872   if (!TREE_PUBLIC (var))
2873 #endif
2874     return get_local_tls_init_fn ();
2875
2876   tree sname = mangle_tls_init_fn (var);
2877   tree fn = IDENTIFIER_GLOBAL_VALUE (sname);
2878   if (!fn)
2879     {
2880       fn = build_lang_decl (FUNCTION_DECL, sname,
2881                             build_function_type (void_type_node,
2882                                                  void_list_node));
2883       SET_DECL_LANGUAGE (fn, lang_c);
2884       TREE_PUBLIC (fn) = TREE_PUBLIC (var);
2885       DECL_ARTIFICIAL (fn) = true;
2886       DECL_COMDAT (fn) = DECL_COMDAT (var);
2887       DECL_EXTERNAL (fn) = true;
2888       if (DECL_ONE_ONLY (var))
2889         make_decl_one_only (fn, cxx_comdat_group (fn));
2890       if (TREE_PUBLIC (var))
2891         {
2892           tree obtype = strip_array_types (non_reference (TREE_TYPE (var)));
2893           /* If the variable is defined somewhere else and might have static
2894              initialization, make the init function a weak reference.  */
2895           if ((!TYPE_NEEDS_CONSTRUCTING (obtype)
2896                || TYPE_HAS_CONSTEXPR_CTOR (obtype))
2897               && TYPE_HAS_TRIVIAL_DESTRUCTOR (obtype)
2898               && DECL_EXTERNAL (var))
2899             declare_weak (fn);
2900           else
2901             DECL_WEAK (fn) = DECL_WEAK (var);
2902         }
2903       DECL_VISIBILITY (fn) = DECL_VISIBILITY (var);
2904       DECL_VISIBILITY_SPECIFIED (fn) = DECL_VISIBILITY_SPECIFIED (var);
2905       DECL_DLLIMPORT_P (fn) = DECL_DLLIMPORT_P (var);
2906       DECL_IGNORED_P (fn) = 1;
2907       mark_used (fn);
2908
2909       DECL_BEFRIENDING_CLASSES (fn) = var;
2910
2911       SET_IDENTIFIER_GLOBAL_VALUE (sname, fn);
2912     }
2913   return fn;
2914 }
2915
2916 /* Get a FUNCTION_DECL for the init wrapper function for the thread_local
2917    variable VAR.  The wrapper function calls the init function (if any) for
2918    VAR and then returns a reference to VAR.  The wrapper function is used
2919    in place of VAR everywhere VAR is mentioned.  */
2920
2921 tree
2922 get_tls_wrapper_fn (tree var)
2923 {
2924   /* Only C++11 TLS vars need this wrapper fn.  */
2925   if (!var_needs_tls_wrapper (var))
2926     return NULL_TREE;
2927
2928   tree sname = mangle_tls_wrapper_fn (var);
2929   tree fn = IDENTIFIER_GLOBAL_VALUE (sname);
2930   if (!fn)
2931     {
2932       /* A named rvalue reference is an lvalue, so the wrapper should
2933          always return an lvalue reference.  */
2934       tree type = non_reference (TREE_TYPE (var));
2935       type = build_reference_type (type);
2936       tree fntype = build_function_type (type, void_list_node);
2937       fn = build_lang_decl (FUNCTION_DECL, sname, fntype);
2938       SET_DECL_LANGUAGE (fn, lang_c);
2939       TREE_PUBLIC (fn) = TREE_PUBLIC (var);
2940       DECL_ARTIFICIAL (fn) = true;
2941       DECL_IGNORED_P (fn) = 1;
2942       /* The wrapper is inline and emitted everywhere var is used.  */
2943       DECL_DECLARED_INLINE_P (fn) = true;
2944       if (TREE_PUBLIC (var))
2945         {
2946           comdat_linkage (fn);
2947 #ifdef HAVE_GAS_HIDDEN
2948           /* Make the wrapper bind locally; there's no reason to share
2949              the wrapper between multiple shared objects.  */
2950           DECL_VISIBILITY (fn) = VISIBILITY_INTERNAL;
2951           DECL_VISIBILITY_SPECIFIED (fn) = true;
2952 #endif
2953         }
2954       if (!TREE_PUBLIC (fn))
2955         DECL_INTERFACE_KNOWN (fn) = true;
2956       mark_used (fn);
2957       note_vague_linkage_fn (fn);
2958
2959 #if 0
2960       /* We want CSE to commonize calls to the wrapper, but marking it as
2961          pure is unsafe since it has side-effects.  I guess we need a new
2962          ECF flag even weaker than ECF_PURE.  FIXME!  */
2963       DECL_PURE_P (fn) = true;
2964 #endif
2965
2966       DECL_BEFRIENDING_CLASSES (fn) = var;
2967
2968       SET_IDENTIFIER_GLOBAL_VALUE (sname, fn);
2969     }
2970   return fn;
2971 }
2972
2973 /* At EOF, generate the definition for the TLS wrapper function FN:
2974
2975    T& var_wrapper() {
2976      if (init_fn) init_fn();
2977      return var;
2978    }  */
2979
2980 static void
2981 generate_tls_wrapper (tree fn)
2982 {
2983   tree var = DECL_BEFRIENDING_CLASSES (fn);
2984
2985   start_preparsed_function (fn, NULL_TREE, SF_DEFAULT | SF_PRE_PARSED);
2986   tree body = begin_function_body ();
2987   /* Only call the init fn if there might be one.  */
2988   if (tree init_fn = get_tls_init_fn (var))
2989     {
2990       tree if_stmt = NULL_TREE;
2991       /* If init_fn is a weakref, make sure it exists before calling.  */
2992       if (lookup_attribute ("weak", DECL_ATTRIBUTES (init_fn)))
2993         {
2994           if_stmt = begin_if_stmt ();
2995           tree addr = cp_build_addr_expr (init_fn, tf_warning_or_error);
2996           tree cond = cp_build_binary_op (DECL_SOURCE_LOCATION (var),
2997                                           NE_EXPR, addr, nullptr_node,
2998                                           tf_warning_or_error);
2999           finish_if_stmt_cond (cond, if_stmt);
3000         }
3001       finish_expr_stmt (build_cxx_call
3002                         (init_fn, 0, NULL, tf_warning_or_error));
3003       if (if_stmt)
3004         {
3005           finish_then_clause (if_stmt);
3006           finish_if_stmt (if_stmt);
3007         }
3008     }
3009   else
3010     /* If there's no initialization, the wrapper is a constant function.  */
3011     TREE_READONLY (fn) = true;
3012   finish_return_stmt (convert_from_reference (var));
3013   finish_function_body (body);
3014   expand_or_defer_fn (finish_function (0));
3015 }
3016
3017 /* Start the process of running a particular set of global constructors
3018    or destructors.  Subroutine of do_[cd]tors.  */
3019
3020 static tree
3021 start_objects (int method_type, int initp)
3022 {
3023   tree body;
3024   tree fndecl;
3025   char type[14];
3026
3027   /* Make ctor or dtor function.  METHOD_TYPE may be 'I' or 'D'.  */
3028
3029   if (initp != DEFAULT_INIT_PRIORITY)
3030     {
3031       char joiner;
3032
3033 #ifdef JOINER
3034       joiner = JOINER;
3035 #else
3036       joiner = '_';
3037 #endif
3038
3039       sprintf (type, "sub_%c%c%.5u", method_type, joiner, initp);
3040     }
3041   else
3042     sprintf (type, "sub_%c", method_type);
3043
3044   fndecl = build_lang_decl (FUNCTION_DECL,
3045                             get_file_function_name (type),
3046                             build_function_type_list (void_type_node,
3047                                                       NULL_TREE));
3048   start_preparsed_function (fndecl, /*attrs=*/NULL_TREE, SF_PRE_PARSED);
3049
3050   TREE_PUBLIC (current_function_decl) = 0;
3051
3052   /* Mark as artificial because it's not explicitly in the user's
3053      source code.  */
3054   DECL_ARTIFICIAL (current_function_decl) = 1;
3055
3056   /* Mark this declaration as used to avoid spurious warnings.  */
3057   TREE_USED (current_function_decl) = 1;
3058
3059   /* Mark this function as a global constructor or destructor.  */
3060   if (method_type == 'I')
3061     DECL_GLOBAL_CTOR_P (current_function_decl) = 1;
3062   else
3063     DECL_GLOBAL_DTOR_P (current_function_decl) = 1;
3064
3065   body = begin_compound_stmt (BCS_FN_BODY);
3066
3067   return body;
3068 }
3069
3070 /* Finish the process of running a particular set of global constructors
3071    or destructors.  Subroutine of do_[cd]tors.  */
3072
3073 static void
3074 finish_objects (int method_type, int initp, tree body)
3075 {
3076   tree fn;
3077
3078   /* Finish up.  */
3079   finish_compound_stmt (body);
3080   fn = finish_function (0);
3081
3082   if (method_type == 'I')
3083     {
3084       DECL_STATIC_CONSTRUCTOR (fn) = 1;
3085       decl_init_priority_insert (fn, initp);
3086     }
3087   else
3088     {
3089       DECL_STATIC_DESTRUCTOR (fn) = 1;
3090       decl_fini_priority_insert (fn, initp);
3091     }
3092
3093   expand_or_defer_fn (fn);
3094 }
3095
3096 /* The names of the parameters to the function created to handle
3097    initializations and destructions for objects with static storage
3098    duration.  */
3099 #define INITIALIZE_P_IDENTIFIER "__initialize_p"
3100 #define PRIORITY_IDENTIFIER "__priority"
3101
3102 /* The name of the function we create to handle initializations and
3103    destructions for objects with static storage duration.  */
3104 #define SSDF_IDENTIFIER "__static_initialization_and_destruction"
3105
3106 /* The declaration for the __INITIALIZE_P argument.  */
3107 static GTY(()) tree initialize_p_decl;
3108
3109 /* The declaration for the __PRIORITY argument.  */
3110 static GTY(()) tree priority_decl;
3111
3112 /* The declaration for the static storage duration function.  */
3113 static GTY(()) tree ssdf_decl;
3114
3115 /* All the static storage duration functions created in this
3116    translation unit.  */
3117 static GTY(()) vec<tree, va_gc> *ssdf_decls;
3118
3119 /* A map from priority levels to information about that priority
3120    level.  There may be many such levels, so efficient lookup is
3121    important.  */
3122 static splay_tree priority_info_map;
3123
3124 /* Begins the generation of the function that will handle all
3125    initialization and destruction of objects with static storage
3126    duration.  The function generated takes two parameters of type
3127    `int': __INITIALIZE_P and __PRIORITY.  If __INITIALIZE_P is
3128    nonzero, it performs initializations.  Otherwise, it performs
3129    destructions.  It only performs those initializations or
3130    destructions with the indicated __PRIORITY.  The generated function
3131    returns no value.
3132
3133    It is assumed that this function will only be called once per
3134    translation unit.  */
3135
3136 static tree
3137 start_static_storage_duration_function (unsigned count)
3138 {
3139   tree type;
3140   tree body;
3141   char id[sizeof (SSDF_IDENTIFIER) + 1 /* '\0' */ + 32];
3142
3143   /* Create the identifier for this function.  It will be of the form
3144      SSDF_IDENTIFIER_<number>.  */
3145   sprintf (id, "%s_%u", SSDF_IDENTIFIER, count);
3146
3147   type = build_function_type_list (void_type_node,
3148                                    integer_type_node, integer_type_node,
3149                                    NULL_TREE);
3150
3151   /* Create the FUNCTION_DECL itself.  */
3152   ssdf_decl = build_lang_decl (FUNCTION_DECL,
3153                                get_identifier (id),
3154                                type);
3155   TREE_PUBLIC (ssdf_decl) = 0;
3156   DECL_ARTIFICIAL (ssdf_decl) = 1;
3157
3158   /* Put this function in the list of functions to be called from the
3159      static constructors and destructors.  */
3160   if (!ssdf_decls)
3161     {
3162       vec_alloc (ssdf_decls, 32);
3163
3164       /* Take this opportunity to initialize the map from priority
3165          numbers to information about that priority level.  */
3166       priority_info_map = splay_tree_new (splay_tree_compare_ints,
3167                                           /*delete_key_fn=*/0,
3168                                           /*delete_value_fn=*/
3169                                           (splay_tree_delete_value_fn) &free);
3170
3171       /* We always need to generate functions for the
3172          DEFAULT_INIT_PRIORITY so enter it now.  That way when we walk
3173          priorities later, we'll be sure to find the
3174          DEFAULT_INIT_PRIORITY.  */
3175       get_priority_info (DEFAULT_INIT_PRIORITY);
3176     }
3177
3178   vec_safe_push (ssdf_decls, ssdf_decl);
3179
3180   /* Create the argument list.  */
3181   initialize_p_decl = cp_build_parm_decl
3182     (get_identifier (INITIALIZE_P_IDENTIFIER), integer_type_node);
3183   DECL_CONTEXT (initialize_p_decl) = ssdf_decl;
3184   TREE_USED (initialize_p_decl) = 1;
3185   priority_decl = cp_build_parm_decl
3186     (get_identifier (PRIORITY_IDENTIFIER), integer_type_node);
3187   DECL_CONTEXT (priority_decl) = ssdf_decl;
3188   TREE_USED (priority_decl) = 1;
3189
3190   DECL_CHAIN (initialize_p_decl) = priority_decl;
3191   DECL_ARGUMENTS (ssdf_decl) = initialize_p_decl;
3192
3193   /* Put the function in the global scope.  */
3194   pushdecl (ssdf_decl);
3195
3196   /* Start the function itself.  This is equivalent to declaring the
3197      function as:
3198
3199        static void __ssdf (int __initialize_p, init __priority_p);
3200
3201      It is static because we only need to call this function from the
3202      various constructor and destructor functions for this module.  */
3203   start_preparsed_function (ssdf_decl,
3204                             /*attrs=*/NULL_TREE,
3205                             SF_PRE_PARSED);
3206
3207   /* Set up the scope of the outermost block in the function.  */
3208   body = begin_compound_stmt (BCS_FN_BODY);
3209
3210   return body;
3211 }
3212
3213 /* Finish the generation of the function which performs initialization
3214    and destruction of objects with static storage duration.  After
3215    this point, no more such objects can be created.  */
3216
3217 static void
3218 finish_static_storage_duration_function (tree body)
3219 {
3220   /* Close out the function.  */
3221   finish_compound_stmt (body);
3222   expand_or_defer_fn (finish_function (0));
3223 }
3224
3225 /* Return the information about the indicated PRIORITY level.  If no
3226    code to handle this level has yet been generated, generate the
3227    appropriate prologue.  */
3228
3229 static priority_info
3230 get_priority_info (int priority)
3231 {
3232   priority_info pi;
3233   splay_tree_node n;
3234
3235   n = splay_tree_lookup (priority_info_map,
3236                          (splay_tree_key) priority);
3237   if (!n)
3238     {
3239       /* Create a new priority information structure, and insert it
3240          into the map.  */
3241       pi = XNEW (struct priority_info_s);
3242       pi->initializations_p = 0;
3243       pi->destructions_p = 0;
3244       splay_tree_insert (priority_info_map,
3245                          (splay_tree_key) priority,
3246                          (splay_tree_value) pi);
3247     }
3248   else
3249     pi = (priority_info) n->value;
3250
3251   return pi;
3252 }
3253
3254 /* The effective initialization priority of a DECL.  */
3255
3256 #define DECL_EFFECTIVE_INIT_PRIORITY(decl)                                    \
3257         ((!DECL_HAS_INIT_PRIORITY_P (decl) || DECL_INIT_PRIORITY (decl) == 0) \
3258          ? DEFAULT_INIT_PRIORITY : DECL_INIT_PRIORITY (decl))
3259
3260 /* Whether a DECL needs a guard to protect it against multiple
3261    initialization.  */
3262
3263 #define NEEDS_GUARD_P(decl) (TREE_PUBLIC (decl) && (DECL_COMMON (decl)      \
3264                                                     || DECL_ONE_ONLY (decl) \
3265                                                     || DECL_WEAK (decl)))
3266
3267 /* Called from one_static_initialization_or_destruction(),
3268    via walk_tree.
3269    Walks the initializer list of a global variable and looks for
3270    temporary variables (DECL_NAME() == NULL and DECL_ARTIFICIAL != 0)
3271    and that have their DECL_CONTEXT() == NULL.
3272    For each such temporary variable, set their DECL_CONTEXT() to
3273    the current function. This is necessary because otherwise
3274    some optimizers (enabled by -O2 -fprofile-arcs) might crash
3275    when trying to refer to a temporary variable that does not have
3276    it's DECL_CONTECT() properly set.  */
3277 static tree 
3278 fix_temporary_vars_context_r (tree *node,
3279                               int  * /*unused*/,
3280                               void * /*unused1*/)
3281 {
3282   gcc_assert (current_function_decl);
3283
3284   if (TREE_CODE (*node) == BIND_EXPR)
3285     {
3286       tree var;
3287
3288       for (var = BIND_EXPR_VARS (*node); var; var = DECL_CHAIN (var))
3289         if (TREE_CODE (var) == VAR_DECL
3290           && !DECL_NAME (var)
3291           && DECL_ARTIFICIAL (var)
3292           && !DECL_CONTEXT (var))
3293           DECL_CONTEXT (var) = current_function_decl;
3294     }
3295
3296   return NULL_TREE;
3297 }
3298
3299 /* Set up to handle the initialization or destruction of DECL.  If
3300    INITP is nonzero, we are initializing the variable.  Otherwise, we
3301    are destroying it.  */
3302
3303 static void
3304 one_static_initialization_or_destruction (tree decl, tree init, bool initp)
3305 {
3306   tree guard_if_stmt = NULL_TREE;
3307   tree guard;
3308
3309   /* If we are supposed to destruct and there's a trivial destructor,
3310      nothing has to be done.  */
3311   if (!initp
3312       && TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
3313     return;
3314
3315   /* Trick the compiler into thinking we are at the file and line
3316      where DECL was declared so that error-messages make sense, and so
3317      that the debugger will show somewhat sensible file and line
3318      information.  */
3319   input_location = DECL_SOURCE_LOCATION (decl);
3320
3321   /* Make sure temporary variables in the initialiser all have
3322      their DECL_CONTEXT() set to a value different from NULL_TREE.
3323      This can happen when global variables initialisers are built.
3324      In that case, the DECL_CONTEXT() of the global variables _AND_ of all 
3325      the temporary variables that might have been generated in the
3326      accompagning initialisers is NULL_TREE, meaning the variables have been
3327      declared in the global namespace.
3328      What we want to do here is to fix that and make sure the DECL_CONTEXT()
3329      of the temporaries are set to the current function decl.  */
3330   cp_walk_tree_without_duplicates (&init,
3331                                    fix_temporary_vars_context_r,
3332                                    NULL);
3333
3334   /* Because of:
3335
3336        [class.access.spec]
3337
3338        Access control for implicit calls to the constructors,
3339        the conversion functions, or the destructor called to
3340        create and destroy a static data member is performed as
3341        if these calls appeared in the scope of the member's
3342        class.
3343
3344      we pretend we are in a static member function of the class of
3345      which the DECL is a member.  */
3346   if (member_p (decl))
3347     {
3348       DECL_CONTEXT (current_function_decl) = DECL_CONTEXT (decl);
3349       DECL_STATIC_FUNCTION_P (current_function_decl) = 1;
3350     }
3351
3352   /* Assume we don't need a guard.  */
3353   guard = NULL_TREE;
3354   /* We need a guard if this is an object with external linkage that
3355      might be initialized in more than one place.  (For example, a
3356      static data member of a template, when the data member requires
3357      construction.)  */
3358   if (NEEDS_GUARD_P (decl))
3359     {
3360       tree guard_cond;
3361
3362       guard = get_guard (decl);
3363
3364       /* When using __cxa_atexit, we just check the GUARD as we would
3365          for a local static.  */
3366       if (flag_use_cxa_atexit)
3367         {
3368           /* When using __cxa_atexit, we never try to destroy
3369              anything from a static destructor.  */
3370           gcc_assert (initp);
3371           guard_cond = get_guard_cond (guard);
3372         }
3373       /* If we don't have __cxa_atexit, then we will be running
3374          destructors from .fini sections, or their equivalents.  So,
3375          we need to know how many times we've tried to initialize this
3376          object.  We do initializations only if the GUARD is zero,
3377          i.e., if we are the first to initialize the variable.  We do
3378          destructions only if the GUARD is one, i.e., if we are the
3379          last to destroy the variable.  */
3380       else if (initp)
3381         guard_cond
3382           = cp_build_binary_op (input_location,
3383                                 EQ_EXPR,
3384                                 cp_build_unary_op (PREINCREMENT_EXPR,
3385                                                    guard,
3386                                                    /*noconvert=*/1,
3387                                                    tf_warning_or_error),
3388                                 integer_one_node,
3389                                 tf_warning_or_error);
3390       else
3391         guard_cond
3392           = cp_build_binary_op (input_location,
3393                                 EQ_EXPR,
3394                                 cp_build_unary_op (PREDECREMENT_EXPR,
3395                                                    guard,
3396                                                    /*noconvert=*/1,
3397                                                    tf_warning_or_error),
3398                                 integer_zero_node,
3399                                 tf_warning_or_error);
3400
3401       guard_if_stmt = begin_if_stmt ();
3402       finish_if_stmt_cond (guard_cond, guard_if_stmt);
3403     }
3404
3405
3406   /* If we're using __cxa_atexit, we have not already set the GUARD,
3407      so we must do so now.  */
3408   if (guard && initp && flag_use_cxa_atexit)
3409     finish_expr_stmt (set_guard (guard));
3410
3411   /* Perform the initialization or destruction.  */
3412   if (initp)
3413     {
3414       if (init)
3415         finish_expr_stmt (init);
3416
3417       /* If we're using __cxa_atexit, register a function that calls the
3418          destructor for the object.  */
3419       if (flag_use_cxa_atexit)
3420         finish_expr_stmt (register_dtor_fn (decl));
3421     }
3422   else
3423     finish_expr_stmt (build_cleanup (decl));
3424
3425   /* Finish the guard if-stmt, if necessary.  */
3426   if (guard)
3427     {
3428       finish_then_clause (guard_if_stmt);
3429       finish_if_stmt (guard_if_stmt);
3430     }
3431
3432   /* Now that we're done with DECL we don't need to pretend to be a
3433      member of its class any longer.  */
3434   DECL_CONTEXT (current_function_decl) = NULL_TREE;
3435   DECL_STATIC_FUNCTION_P (current_function_decl) = 0;
3436 }
3437
3438 /* Generate code to do the initialization or destruction of the decls in VARS,
3439    a TREE_LIST of VAR_DECL with static storage duration.
3440    Whether initialization or destruction is performed is specified by INITP.  */
3441
3442 static void
3443 do_static_initialization_or_destruction (tree vars, bool initp)
3444 {
3445   tree node, init_if_stmt, cond;
3446
3447   /* Build the outer if-stmt to check for initialization or destruction.  */
3448   init_if_stmt = begin_if_stmt ();
3449   cond = initp ? integer_one_node : integer_zero_node;
3450   cond = cp_build_binary_op (input_location,
3451                              EQ_EXPR,
3452                              initialize_p_decl,
3453                              cond,
3454                              tf_warning_or_error);
3455   finish_if_stmt_cond (cond, init_if_stmt);
3456
3457   node = vars;
3458   do {
3459     tree decl = TREE_VALUE (node);
3460     tree priority_if_stmt;
3461     int priority;
3462     priority_info pi;
3463
3464     /* If we don't need a destructor, there's nothing to do.  Avoid
3465        creating a possibly empty if-stmt.  */
3466     if (!initp && TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
3467       {
3468         node = TREE_CHAIN (node);
3469         continue;
3470       }
3471
3472     /* Remember that we had an initialization or finalization at this
3473        priority.  */
3474     priority = DECL_EFFECTIVE_INIT_PRIORITY (decl);
3475     pi = get_priority_info (priority);
3476     if (initp)
3477       pi->initializations_p = 1;
3478     else
3479       pi->destructions_p = 1;
3480
3481     /* Conditionalize this initialization on being in the right priority
3482        and being initializing/finalizing appropriately.  */
3483     priority_if_stmt = begin_if_stmt ();
3484     cond = cp_build_binary_op (input_location,
3485                                EQ_EXPR,
3486                                priority_decl,
3487                                build_int_cst (NULL_TREE, priority),
3488                                tf_warning_or_error);
3489     finish_if_stmt_cond (cond, priority_if_stmt);
3490
3491     /* Process initializers with same priority.  */
3492     for (; node
3493            && DECL_EFFECTIVE_INIT_PRIORITY (TREE_VALUE (node)) == priority;
3494          node = TREE_CHAIN (node))
3495       /* Do one initialization or destruction.  */
3496       one_static_initialization_or_destruction (TREE_VALUE (node),
3497                                                 TREE_PURPOSE (node), initp);
3498
3499     /* Finish up the priority if-stmt body.  */
3500     finish_then_clause (priority_if_stmt);
3501     finish_if_stmt (priority_if_stmt);
3502
3503   } while (node);
3504
3505   /* Finish up the init/destruct if-stmt body.  */
3506   finish_then_clause (init_if_stmt);
3507   finish_if_stmt (init_if_stmt);
3508 }
3509
3510 /* VARS is a list of variables with static storage duration which may
3511    need initialization and/or finalization.  Remove those variables
3512    that don't really need to be initialized or finalized, and return
3513    the resulting list.  The order in which the variables appear in
3514    VARS is in reverse order of the order in which they should actually
3515    be initialized.  The list we return is in the unreversed order;
3516    i.e., the first variable should be initialized first.  */
3517
3518 static tree
3519 prune_vars_needing_no_initialization (tree *vars)
3520 {
3521   tree *var = vars;
3522   tree result = NULL_TREE;
3523
3524   while (*var)
3525     {
3526       tree t = *var;
3527       tree decl = TREE_VALUE (t);
3528       tree init = TREE_PURPOSE (t);
3529
3530       /* Deal gracefully with error.  */
3531       if (decl == error_mark_node)
3532         {
3533           var = &TREE_CHAIN (t);
3534           continue;
3535         }
3536
3537       /* The only things that can be initialized are variables.  */
3538       gcc_assert (TREE_CODE (decl) == VAR_DECL);
3539
3540       /* If this object is not defined, we don't need to do anything
3541          here.  */
3542       if (DECL_EXTERNAL (decl))
3543         {
3544           var = &TREE_CHAIN (t);
3545           continue;
3546         }
3547
3548       /* Also, if the initializer already contains errors, we can bail
3549          out now.  */
3550       if (init && TREE_CODE (init) == TREE_LIST
3551           && value_member (error_mark_node, init))
3552         {
3553           var = &TREE_CHAIN (t);
3554           continue;
3555         }
3556
3557       /* This variable is going to need initialization and/or
3558          finalization, so we add it to the list.  */
3559       *var = TREE_CHAIN (t);
3560       TREE_CHAIN (t) = result;
3561       result = t;
3562     }
3563
3564   return result;
3565 }
3566
3567 /* Make sure we have told the back end about all the variables in
3568    VARS.  */
3569
3570 static void
3571 write_out_vars (tree vars)
3572 {
3573   tree v;
3574
3575   for (v = vars; v; v = TREE_CHAIN (v))
3576     {
3577       tree var = TREE_VALUE (v);
3578       if (!var_finalized_p (var))
3579         {
3580           import_export_decl (var);
3581           rest_of_decl_compilation (var, 1, 1);
3582         }
3583     }
3584 }
3585
3586 /* Generate a static constructor (if CONSTRUCTOR_P) or destructor
3587    (otherwise) that will initialize all global objects with static
3588    storage duration having the indicated PRIORITY.  */
3589
3590 static void
3591 generate_ctor_or_dtor_function (bool constructor_p, int priority,
3592                                 location_t *locus)
3593 {
3594   char function_key;
3595   tree fndecl;
3596   tree body;
3597   size_t i;
3598
3599   input_location = *locus;
3600   /* ??? */
3601   /* Was: locus->line++; */
3602
3603   /* We use `I' to indicate initialization and `D' to indicate
3604      destruction.  */
3605   function_key = constructor_p ? 'I' : 'D';
3606
3607   /* We emit the function lazily, to avoid generating empty
3608      global constructors and destructors.  */
3609   body = NULL_TREE;
3610
3611   /* For Objective-C++, we may need to initialize metadata found in this module.
3612      This must be done _before_ any other static initializations.  */
3613   if (c_dialect_objc () && (priority == DEFAULT_INIT_PRIORITY)
3614       && constructor_p && objc_static_init_needed_p ())
3615     {
3616       body = start_objects (function_key, priority);
3617       objc_generate_static_init_call (NULL_TREE);
3618     }
3619
3620   /* Call the static storage duration function with appropriate
3621      arguments.  */
3622   FOR_EACH_VEC_SAFE_ELT (ssdf_decls, i, fndecl)
3623     {
3624       /* Calls to pure or const functions will expand to nothing.  */
3625       if (! (flags_from_decl_or_type (fndecl) & (ECF_CONST | ECF_PURE)))
3626         {
3627           tree call;
3628
3629           if (! body)
3630             body = start_objects (function_key, priority);
3631
3632           call = cp_build_function_call_nary (fndecl, tf_warning_or_error,
3633                                               build_int_cst (NULL_TREE,
3634                                                              constructor_p),
3635                                               build_int_cst (NULL_TREE,
3636                                                              priority),
3637                                               NULL_TREE);
3638           finish_expr_stmt (call);
3639         }
3640     }
3641
3642   /* Close out the function.  */
3643   if (body)
3644     finish_objects (function_key, priority, body);
3645 }
3646
3647 /* Generate constructor and destructor functions for the priority
3648    indicated by N.  */
3649
3650 static int
3651 generate_ctor_and_dtor_functions_for_priority (splay_tree_node n, void * data)
3652 {
3653   location_t *locus = (location_t *) data;
3654   int priority = (int) n->key;
3655   priority_info pi = (priority_info) n->value;
3656
3657   /* Generate the functions themselves, but only if they are really
3658      needed.  */
3659   if (pi->initializations_p)
3660     generate_ctor_or_dtor_function (/*constructor_p=*/true, priority, locus);
3661   if (pi->destructions_p)
3662     generate_ctor_or_dtor_function (/*constructor_p=*/false, priority, locus);
3663
3664   /* Keep iterating.  */
3665   return 0;
3666 }
3667
3668 /* Java requires that we be able to reference a local address for a
3669    method, and not be confused by PLT entries.  If hidden aliases are
3670    supported, collect and return all the functions for which we should
3671    emit a hidden alias.  */
3672
3673 static struct pointer_set_t *
3674 collect_candidates_for_java_method_aliases (void)
3675 {
3676   struct cgraph_node *node;
3677   struct pointer_set_t *candidates = NULL;
3678
3679 #ifndef HAVE_GAS_HIDDEN
3680   return candidates;
3681 #endif
3682
3683   FOR_EACH_FUNCTION (node)
3684     {
3685       tree fndecl = node->symbol.decl;
3686
3687       if (DECL_CONTEXT (fndecl)
3688           && TYPE_P (DECL_CONTEXT (fndecl))
3689           && TYPE_FOR_JAVA (DECL_CONTEXT (fndecl))
3690           && TARGET_USE_LOCAL_THUNK_ALIAS_P (fndecl))
3691         {
3692           if (candidates == NULL)
3693             candidates = pointer_set_create ();
3694           pointer_set_insert (candidates, fndecl);
3695         }
3696     }
3697
3698   return candidates;
3699 }
3700
3701
3702 /* Java requires that we be able to reference a local address for a
3703    method, and not be confused by PLT entries.  If hidden aliases are
3704    supported, emit one for each java function that we've emitted.
3705    CANDIDATES is the set of FUNCTION_DECLs that were gathered
3706    by collect_candidates_for_java_method_aliases.  */
3707
3708 static void
3709 build_java_method_aliases (struct pointer_set_t *candidates)
3710 {
3711   struct cgraph_node *node;
3712
3713 #ifndef HAVE_GAS_HIDDEN
3714   return;
3715 #endif
3716
3717   FOR_EACH_FUNCTION (node)
3718     {
3719       tree fndecl = node->symbol.decl;
3720
3721       if (TREE_ASM_WRITTEN (fndecl)
3722           && pointer_set_contains (candidates, fndecl))
3723         {
3724           /* Mangle the name in a predictable way; we need to reference
3725              this from a java compiled object file.  */
3726           tree oid, nid, alias;
3727           const char *oname;
3728           char *nname;
3729
3730           oid = DECL_ASSEMBLER_NAME (fndecl);
3731           oname = IDENTIFIER_POINTER (oid);
3732           gcc_assert (oname[0] == '_' && oname[1] == 'Z');
3733           nname = ACONCAT (("_ZGA", oname+2, NULL));
3734           nid = get_identifier (nname);
3735
3736           alias = make_alias_for (fndecl, nid);
3737           TREE_PUBLIC (alias) = 1;
3738           DECL_VISIBILITY (alias) = VISIBILITY_HIDDEN;
3739
3740           assemble_alias (alias, oid);
3741         }
3742     }
3743 }
3744
3745 /* Return C++ property of T, based on given operation OP.  */
3746
3747 static int
3748 cpp_check (tree t, cpp_operation op)
3749 {
3750   switch (op)
3751     {
3752       case IS_ABSTRACT:
3753         return DECL_PURE_VIRTUAL_P (t);
3754       case IS_CONSTRUCTOR:
3755         return DECL_CONSTRUCTOR_P (t);
3756       case IS_DESTRUCTOR:
3757         return DECL_DESTRUCTOR_P (t);
3758       case IS_COPY_CONSTRUCTOR:
3759         return DECL_COPY_CONSTRUCTOR_P (t);
3760       case IS_TEMPLATE:
3761         return TREE_CODE (t) == TEMPLATE_DECL;
3762       default:
3763         return 0;
3764     }
3765 }
3766
3767 /* Collect source file references recursively, starting from NAMESPC.  */
3768
3769 static void 
3770 collect_source_refs (tree namespc) 
3771 {
3772   tree t;
3773
3774   if (!namespc) 
3775     return;
3776
3777   /* Iterate over names in this name space.  */
3778   for (t = NAMESPACE_LEVEL (namespc)->names; t; t = TREE_CHAIN (t))
3779     if (!DECL_IS_BUILTIN (t) )
3780       collect_source_ref (DECL_SOURCE_FILE (t));
3781   
3782   /* Dump siblings, if any */
3783   collect_source_refs (TREE_CHAIN (namespc));
3784
3785   /* Dump children, if any */
3786   collect_source_refs (NAMESPACE_LEVEL (namespc)->namespaces);
3787 }
3788
3789 /* Collect decls relevant to SOURCE_FILE from all namespaces recursively,
3790    starting from NAMESPC.  */
3791
3792 static void
3793 collect_ada_namespace (tree namespc, const char *source_file)
3794 {
3795   if (!namespc)
3796     return;
3797
3798   /* Collect decls from this namespace */
3799   collect_ada_nodes (NAMESPACE_LEVEL (namespc)->names, source_file);
3800
3801   /* Collect siblings, if any */
3802   collect_ada_namespace (TREE_CHAIN (namespc), source_file);
3803
3804   /* Collect children, if any */
3805   collect_ada_namespace (NAMESPACE_LEVEL (namespc)->namespaces, source_file);
3806 }
3807
3808 /* Returns true iff there is a definition available for variable or
3809    function DECL.  */
3810
3811 static bool
3812 decl_defined_p (tree decl)
3813 {
3814   if (TREE_CODE (decl) == FUNCTION_DECL)
3815     return (DECL_INITIAL (decl) != NULL_TREE);
3816   else
3817     {
3818       gcc_assert (TREE_CODE (decl) == VAR_DECL);
3819       return !DECL_EXTERNAL (decl);
3820     }
3821 }
3822
3823 /* Nonzero for a VAR_DECL whose value can be used in a constant expression.
3824
3825       [expr.const]
3826
3827       An integral constant-expression can only involve ... const
3828       variables of integral or enumeration types initialized with
3829       constant expressions ...
3830
3831       C++0x also allows constexpr variables and temporaries initialized
3832       with constant expressions.  We handle the former here, but the latter
3833       are just folded away in cxx_eval_constant_expression.
3834
3835    The standard does not require that the expression be non-volatile.
3836    G++ implements the proposed correction in DR 457.  */
3837
3838 bool
3839 decl_constant_var_p (tree decl)
3840 {
3841   if (!decl_maybe_constant_var_p (decl))
3842     return false;
3843
3844   /* We don't know if a template static data member is initialized with
3845      a constant expression until we instantiate its initializer.  Even
3846      in the case of a constexpr variable, we can't treat it as a
3847      constant until its initializer is complete in case it's used in
3848      its own initializer.  */
3849   mark_used (decl);
3850   return DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl);
3851 }
3852
3853 /* Returns true if DECL could be a symbolic constant variable, depending on
3854    its initializer.  */
3855
3856 bool
3857 decl_maybe_constant_var_p (tree decl)
3858 {
3859   tree type = TREE_TYPE (decl);
3860   if (TREE_CODE (decl) != VAR_DECL)
3861     return false;
3862   if (DECL_DECLARED_CONSTEXPR_P (decl))
3863     return true;
3864   return (CP_TYPE_CONST_NON_VOLATILE_P (type)
3865           && INTEGRAL_OR_ENUMERATION_TYPE_P (type));
3866 }
3867
3868 /* Complain that DECL uses a type with no linkage but is never defined.  */
3869
3870 static void
3871 no_linkage_error (tree decl)
3872 {
3873   tree t = no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false);
3874   if (TYPE_ANONYMOUS_P (t))
3875     {
3876       permerror (0, "%q+#D, declared using anonymous type, "
3877                  "is used but never defined", decl);
3878       if (is_typedef_decl (TYPE_NAME (t)))
3879         permerror (0, "%q+#D does not refer to the unqualified type, "
3880                    "so it is not used for linkage", TYPE_NAME (t));
3881     }
3882   else
3883     permerror (0, "%q+#D, declared using local type %qT, "
3884                "is used but never defined", decl, t);
3885 }
3886
3887 /* Collect declarations from all namespaces relevant to SOURCE_FILE.  */
3888
3889 static void
3890 collect_all_refs (const char *source_file)
3891 {
3892   collect_ada_namespace (global_namespace, source_file);
3893 }
3894
3895 /* Clear DECL_EXTERNAL for NODE.  */
3896
3897 static bool
3898 clear_decl_external (struct cgraph_node *node, void * /*data*/)
3899 {
3900   DECL_EXTERNAL (node->symbol.decl) = 0;
3901   return false;
3902 }
3903
3904 /* Build up the function to run dynamic initializers for thread_local
3905    variables in this translation unit and alias the init functions for the
3906    individual variables to it.  */
3907
3908 static void
3909 handle_tls_init (void)
3910 {
3911   tree vars = prune_vars_needing_no_initialization (&tls_aggregates);
3912   if (vars == NULL_TREE)
3913     return;
3914
3915   location_t loc = DECL_SOURCE_LOCATION (TREE_VALUE (vars));
3916
3917   write_out_vars (vars);
3918
3919   tree guard = build_decl (loc, VAR_DECL, get_identifier ("__tls_guard"),
3920                            boolean_type_node);
3921   TREE_PUBLIC (guard) = false;
3922   TREE_STATIC (guard) = true;
3923   DECL_ARTIFICIAL (guard) = true;
3924   DECL_IGNORED_P (guard) = true;
3925   TREE_USED (guard) = true;
3926   DECL_TLS_MODEL (guard) = decl_default_tls_model (guard);
3927   pushdecl_top_level_and_finish (guard, NULL_TREE);
3928
3929   tree fn = get_local_tls_init_fn ();
3930   start_preparsed_function (fn, NULL_TREE, SF_PRE_PARSED);
3931   tree body = begin_function_body ();
3932   tree if_stmt = begin_if_stmt ();
3933   tree cond = cp_build_unary_op (TRUTH_NOT_EXPR, guard, false,
3934                                  tf_warning_or_error);
3935   finish_if_stmt_cond (cond, if_stmt);
3936   finish_expr_stmt (cp_build_modify_expr (guard, NOP_EXPR, boolean_true_node,
3937                                           tf_warning_or_error));
3938   for (; vars; vars = TREE_CHAIN (vars))
3939     {
3940       tree var = TREE_VALUE (vars);
3941       tree init = TREE_PURPOSE (vars);
3942       one_static_initialization_or_destruction (var, init, true);
3943
3944 #ifdef ASM_OUTPUT_DEF
3945       /* Output init aliases even with -fno-extern-tls-init.  */
3946       if (TREE_PUBLIC (var))
3947         {
3948           tree single_init_fn = get_tls_init_fn (var);
3949           cgraph_node *alias
3950             = cgraph_same_body_alias (cgraph_get_create_node (fn),
3951                                       single_init_fn, fn);
3952           gcc_assert (alias != NULL);
3953         }
3954 #endif
3955     }
3956
3957   finish_then_clause (if_stmt);
3958   finish_if_stmt (if_stmt);
3959   finish_function_body (body);
3960   expand_or_defer_fn (finish_function (0));
3961 }
3962
3963 /* This routine is called at the end of compilation.
3964    Its job is to create all the code needed to initialize and
3965    destroy the global aggregates.  We do the destruction
3966    first, since that way we only need to reverse the decls once.  */
3967
3968 void
3969 cp_write_global_declarations (void)
3970 {
3971   tree vars;
3972   bool reconsider;
3973   size_t i;
3974   location_t locus;
3975   unsigned ssdf_count = 0;
3976   int retries = 0;
3977   tree decl;
3978   struct pointer_set_t *candidates;
3979
3980   locus = input_location;
3981   at_eof = 1;
3982
3983   /* Bad parse errors.  Just forget about it.  */
3984   if (! global_bindings_p () || current_class_type
3985       || !vec_safe_is_empty (decl_namespace_list))
3986     return;
3987
3988   /* This is the point to write out a PCH if we're doing that.
3989      In that case we do not want to do anything else.  */
3990   if (pch_file)
3991     {
3992       c_common_write_pch ();
3993       return;
3994     }
3995
3996   cgraph_process_same_body_aliases ();
3997
3998   /* Handle -fdump-ada-spec[-slim] */
3999   if (flag_dump_ada_spec || flag_dump_ada_spec_slim)
4000     {
4001       if (flag_dump_ada_spec_slim)
4002         collect_source_ref (main_input_filename);
4003       else
4004         collect_source_refs (global_namespace);
4005
4006       dump_ada_specs (collect_all_refs, cpp_check);
4007     }
4008
4009   /* FIXME - huh?  was  input_line -= 1;*/
4010
4011   timevar_start (TV_PHASE_DEFERRED);
4012
4013   /* We now have to write out all the stuff we put off writing out.
4014      These include:
4015
4016        o Template specializations that we have not yet instantiated,
4017          but which are needed.
4018        o Initialization and destruction for non-local objects with
4019          static storage duration.  (Local objects with static storage
4020          duration are initialized when their scope is first entered,
4021          and are cleaned up via atexit.)
4022        o Virtual function tables.
4023
4024      All of these may cause others to be needed.  For example,
4025      instantiating one function may cause another to be needed, and
4026      generating the initializer for an object may cause templates to be
4027      instantiated, etc., etc.  */
4028
4029   emit_support_tinfos ();
4030
4031   do
4032     {
4033       tree t;
4034       tree decl;
4035
4036       reconsider = false;
4037
4038       /* If there are templates that we've put off instantiating, do
4039          them now.  */
4040       instantiate_pending_templates (retries);
4041       ggc_collect ();
4042
4043       /* Write out virtual tables as required.  Note that writing out
4044          the virtual table for a template class may cause the
4045          instantiation of members of that class.  If we write out
4046          vtables then we remove the class from our list so we don't
4047          have to look at it again.  */
4048
4049       while (keyed_classes != NULL_TREE
4050              && maybe_emit_vtables (TREE_VALUE (keyed_classes)))
4051         {
4052           reconsider = true;
4053           keyed_classes = TREE_CHAIN (keyed_classes);
4054         }
4055
4056       t = keyed_classes;
4057       if (t != NULL_TREE)
4058         {
4059           tree next = TREE_CHAIN (t);
4060
4061           while (next)
4062             {
4063               if (maybe_emit_vtables (TREE_VALUE (next)))
4064                 {
4065                   reconsider = true;
4066                   TREE_CHAIN (t) = TREE_CHAIN (next);
4067                 }
4068               else
4069                 t = next;
4070
4071               next = TREE_CHAIN (t);
4072             }
4073         }
4074
4075       /* Write out needed type info variables.  We have to be careful
4076          looping through unemitted decls, because emit_tinfo_decl may
4077          cause other variables to be needed. New elements will be
4078          appended, and we remove from the vector those that actually
4079          get emitted.  */
4080       for (i = unemitted_tinfo_decls->length ();
4081            unemitted_tinfo_decls->iterate (--i, &t);)
4082         if (emit_tinfo_decl (t))
4083           {
4084             reconsider = true;
4085             unemitted_tinfo_decls->unordered_remove (i);
4086           }
4087
4088       /* The list of objects with static storage duration is built up
4089          in reverse order.  We clear STATIC_AGGREGATES so that any new
4090          aggregates added during the initialization of these will be
4091          initialized in the correct order when we next come around the
4092          loop.  */
4093       vars = prune_vars_needing_no_initialization (&static_aggregates);
4094
4095       if (vars)
4096         {
4097           /* We need to start a new initialization function each time
4098              through the loop.  That's because we need to know which
4099              vtables have been referenced, and TREE_SYMBOL_REFERENCED
4100              isn't computed until a function is finished, and written
4101              out.  That's a deficiency in the back end.  When this is
4102              fixed, these initialization functions could all become
4103              inline, with resulting performance improvements.  */
4104           tree ssdf_body;
4105
4106           /* Set the line and file, so that it is obviously not from
4107              the source file.  */
4108           input_location = locus;
4109           ssdf_body = start_static_storage_duration_function (ssdf_count);
4110
4111           /* Make sure the back end knows about all the variables.  */
4112           write_out_vars (vars);
4113
4114           /* First generate code to do all the initializations.  */
4115           if (vars)
4116             do_static_initialization_or_destruction (vars, /*initp=*/true);
4117
4118           /* Then, generate code to do all the destructions.  Do these
4119              in reverse order so that the most recently constructed
4120              variable is the first destroyed.  If we're using
4121              __cxa_atexit, then we don't need to do this; functions
4122              were registered at initialization time to destroy the
4123              local statics.  */
4124           if (!flag_use_cxa_atexit && vars)
4125             {
4126               vars = nreverse (vars);
4127               do_static_initialization_or_destruction (vars, /*initp=*/false);
4128             }
4129           else
4130             vars = NULL_TREE;
4131
4132           /* Finish up the static storage duration function for this
4133              round.  */
4134           input_location = locus;
4135           finish_static_storage_duration_function (ssdf_body);
4136
4137           /* All those initializations and finalizations might cause
4138              us to need more inline functions, more template
4139              instantiations, etc.  */
4140           reconsider = true;
4141           ssdf_count++;
4142           /* ??? was:  locus.line++; */
4143         }
4144
4145       /* Now do the same for thread_local variables.  */
4146       handle_tls_init ();
4147
4148       /* Go through the set of inline functions whose bodies have not
4149          been emitted yet.  If out-of-line copies of these functions
4150          are required, emit them.  */
4151       FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl)
4152         {
4153           /* Does it need synthesizing?  */
4154           if (DECL_DEFAULTED_FN (decl) && ! DECL_INITIAL (decl)
4155               && (! DECL_REALLY_EXTERN (decl) || possibly_inlined_p (decl)))
4156             {
4157               /* Even though we're already at the top-level, we push
4158                  there again.  That way, when we pop back a few lines
4159                  hence, all of our state is restored.  Otherwise,
4160                  finish_function doesn't clean things up, and we end
4161                  up with CURRENT_FUNCTION_DECL set.  */
4162               push_to_top_level ();
4163               /* The decl's location will mark where it was first
4164                  needed.  Save that so synthesize method can indicate
4165                  where it was needed from, in case of error  */
4166               input_location = DECL_SOURCE_LOCATION (decl);
4167               synthesize_method (decl);
4168               pop_from_top_level ();
4169               reconsider = true;
4170             }
4171
4172           if (!DECL_INITIAL (decl) && decl_tls_wrapper_p (decl))
4173             generate_tls_wrapper (decl);
4174
4175           if (!DECL_SAVED_TREE (decl))
4176             continue;
4177
4178           /* We lie to the back end, pretending that some functions
4179              are not defined when they really are.  This keeps these
4180              functions from being put out unnecessarily.  But, we must
4181              stop lying when the functions are referenced, or if they
4182              are not comdat since they need to be put out now.  If
4183              DECL_INTERFACE_KNOWN, then we have already set
4184              DECL_EXTERNAL appropriately, so there's no need to check
4185              again, and we do not want to clear DECL_EXTERNAL if a
4186              previous call to import_export_decl set it.
4187
4188              This is done in a separate for cycle, because if some
4189              deferred function is contained in another deferred
4190              function later in deferred_fns varray,
4191              rest_of_compilation would skip this function and we
4192              really cannot expand the same function twice.  */
4193           import_export_decl (decl);
4194           if (DECL_NOT_REALLY_EXTERN (decl)
4195               && DECL_INITIAL (decl)
4196               && decl_needed_p (decl))
4197             {
4198               struct cgraph_node *node, *next;
4199
4200               node = cgraph_get_node (decl);
4201               if (node->same_body_alias)
4202                 node = cgraph_alias_aliased_node (node);
4203
4204               cgraph_for_node_and_aliases (node, clear_decl_external,
4205                                            NULL, true);
4206               /* If we mark !DECL_EXTERNAL one of the symbols in some comdat
4207                  group, we need to mark all symbols in the same comdat group
4208                  that way.  */
4209               if (node->symbol.same_comdat_group)
4210                 for (next = cgraph (node->symbol.same_comdat_group);
4211                      next != node;
4212                      next = cgraph (next->symbol.same_comdat_group))
4213                   cgraph_for_node_and_aliases (next, clear_decl_external,
4214                                                NULL, true);
4215             }
4216
4217           /* If we're going to need to write this function out, and
4218              there's already a body for it, create RTL for it now.
4219              (There might be no body if this is a method we haven't
4220              gotten around to synthesizing yet.)  */
4221           if (!DECL_EXTERNAL (decl)
4222               && decl_needed_p (decl)
4223               && !TREE_ASM_WRITTEN (decl)
4224               && !cgraph_get_node (decl)->local.finalized)
4225             {
4226               /* We will output the function; no longer consider it in this
4227                  loop.  */
4228               DECL_DEFER_OUTPUT (decl) = 0;
4229               /* Generate RTL for this function now that we know we
4230                  need it.  */
4231               expand_or_defer_fn (decl);
4232               /* If we're compiling -fsyntax-only pretend that this
4233                  function has been written out so that we don't try to
4234                  expand it again.  */
4235               if (flag_syntax_only)
4236                 TREE_ASM_WRITTEN (decl) = 1;
4237               reconsider = true;
4238             }
4239         }
4240
4241       if (walk_namespaces (wrapup_globals_for_namespace, /*data=*/0))
4242         reconsider = true;
4243
4244       /* Static data members are just like namespace-scope globals.  */
4245       FOR_EACH_VEC_SAFE_ELT (pending_statics, i, decl)
4246         {
4247           if (var_finalized_p (decl) || DECL_REALLY_EXTERN (decl)
4248               /* Don't write it out if we haven't seen a definition.  */
4249               || DECL_IN_AGGR_P (decl))
4250             continue;
4251           import_export_decl (decl);
4252           /* If this static data member is needed, provide it to the
4253              back end.  */
4254           if (DECL_NOT_REALLY_EXTERN (decl) && decl_needed_p (decl))
4255             DECL_EXTERNAL (decl) = 0;
4256         }
4257       if (vec_safe_length (pending_statics) != 0
4258           && wrapup_global_declarations (pending_statics->address (),
4259                                          pending_statics->length ()))
4260         reconsider = true;
4261
4262       retries++;
4263     }
4264   while (reconsider);
4265
4266   /* All used inline functions must have a definition at this point.  */
4267   FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl)
4268     {
4269       if (/* Check online inline functions that were actually used.  */
4270           DECL_ODR_USED (decl) && DECL_DECLARED_INLINE_P (decl)
4271           /* If the definition actually was available here, then the
4272              fact that the function was not defined merely represents
4273              that for some reason (use of a template repository,
4274              #pragma interface, etc.) we decided not to emit the
4275              definition here.  */
4276           && !DECL_INITIAL (decl)
4277           /* Don't complain if the template was defined.  */
4278           && !(DECL_TEMPLATE_INSTANTIATION (decl)
4279                && DECL_INITIAL (DECL_TEMPLATE_RESULT
4280                                 (template_for_substitution (decl)))))
4281         {
4282           warning (0, "inline function %q+D used but never defined", decl);
4283           /* Avoid a duplicate warning from check_global_declaration_1.  */
4284           TREE_NO_WARNING (decl) = 1;
4285         }
4286     }
4287
4288   /* So must decls that use a type with no linkage.  */
4289   FOR_EACH_VEC_SAFE_ELT (no_linkage_decls, i, decl)
4290     if (!decl_defined_p (decl))
4291       no_linkage_error (decl);
4292
4293   /* Then, do the Objective-C stuff.  This is where all the
4294      Objective-C module stuff gets generated (symtab,
4295      class/protocol/selector lists etc).  This must be done after C++
4296      templates, destructors etc. so that selectors used in C++
4297      templates are properly allocated.  */
4298   if (c_dialect_objc ())
4299     objc_write_global_declarations ();
4300
4301   /* We give C linkage to static constructors and destructors.  */
4302   push_lang_context (lang_name_c);
4303
4304   /* Generate initialization and destruction functions for all
4305      priorities for which they are required.  */
4306   if (priority_info_map)
4307     splay_tree_foreach (priority_info_map,
4308                         generate_ctor_and_dtor_functions_for_priority,
4309                         /*data=*/&locus);
4310   else if (c_dialect_objc () && objc_static_init_needed_p ())
4311     /* If this is obj-c++ and we need a static init, call
4312        generate_ctor_or_dtor_function.  */
4313     generate_ctor_or_dtor_function (/*constructor_p=*/true,
4314                                     DEFAULT_INIT_PRIORITY, &locus);
4315
4316   /* We're done with the splay-tree now.  */
4317   if (priority_info_map)
4318     splay_tree_delete (priority_info_map);
4319
4320   /* Generate any missing aliases.  */
4321   maybe_apply_pending_pragma_weaks ();
4322
4323   /* We're done with static constructors, so we can go back to "C++"
4324      linkage now.  */
4325   pop_lang_context ();
4326
4327   /* Collect candidates for Java hidden aliases.  */
4328   candidates = collect_candidates_for_java_method_aliases ();
4329
4330   timevar_stop (TV_PHASE_DEFERRED);
4331   timevar_start (TV_PHASE_OPT_GEN);
4332
4333   finalize_compilation_unit ();
4334
4335   timevar_stop (TV_PHASE_OPT_GEN);
4336   timevar_start (TV_PHASE_CHECK_DBGINFO);
4337
4338   /* Now, issue warnings about static, but not defined, functions,
4339      etc., and emit debugging information.  */
4340   walk_namespaces (wrapup_globals_for_namespace, /*data=*/&reconsider);
4341   if (vec_safe_length (pending_statics) != 0)
4342     {
4343       check_global_declarations (pending_statics->address (),
4344                                  pending_statics->length ());
4345       emit_debug_global_declarations (pending_statics->address (),
4346                                       pending_statics->length ());
4347     }
4348
4349   perform_deferred_noexcept_checks ();
4350
4351   /* Generate hidden aliases for Java.  */
4352   if (candidates)
4353     {
4354       build_java_method_aliases (candidates);
4355       pointer_set_destroy (candidates);
4356     }
4357
4358   finish_repo ();
4359
4360   /* The entire file is now complete.  If requested, dump everything
4361      to a file.  */
4362   {
4363     int flags;
4364     FILE *stream = dump_begin (TDI_tu, &flags);
4365
4366     if (stream)
4367       {
4368         dump_node (global_namespace, flags & ~TDF_SLIM, stream);
4369         dump_end (TDI_tu, stream);
4370       }
4371   }
4372
4373   if (flag_detailed_statistics)
4374     {
4375       dump_tree_statistics ();
4376       dump_time_statistics ();
4377     }
4378   input_location = locus;
4379
4380 #ifdef ENABLE_CHECKING
4381   validate_conversion_obstack ();
4382 #endif /* ENABLE_CHECKING */
4383
4384   timevar_stop (TV_PHASE_CHECK_DBGINFO);
4385 }
4386
4387 /* FN is an OFFSET_REF, DOTSTAR_EXPR or MEMBER_REF indicating the
4388    function to call in parse-tree form; it has not yet been
4389    semantically analyzed.  ARGS are the arguments to the function.
4390    They have already been semantically analyzed.  This may change
4391    ARGS.  */
4392
4393 tree
4394 build_offset_ref_call_from_tree (tree fn, vec<tree, va_gc> **args,
4395                                  tsubst_flags_t complain)
4396 {
4397   tree orig_fn;
4398   vec<tree, va_gc> *orig_args = NULL;
4399   tree expr;
4400   tree object;
4401
4402   orig_fn = fn;
4403   object = TREE_OPERAND (fn, 0);
4404
4405   if (processing_template_decl)
4406     {
4407       gcc_assert (TREE_CODE (fn) == DOTSTAR_EXPR
4408                   || TREE_CODE (fn) == MEMBER_REF);
4409       if (type_dependent_expression_p (fn)
4410           || any_type_dependent_arguments_p (*args))
4411         return build_nt_call_vec (fn, *args);
4412
4413       orig_args = make_tree_vector_copy (*args);
4414
4415       /* Transform the arguments and add the implicit "this"
4416          parameter.  That must be done before the FN is transformed
4417          because we depend on the form of FN.  */
4418       make_args_non_dependent (*args);
4419       object = build_non_dependent_expr (object);
4420       if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
4421         {
4422           if (TREE_CODE (fn) == DOTSTAR_EXPR)
4423             object = cp_build_addr_expr (object, complain);
4424           vec_safe_insert (*args, 0, object);
4425         }
4426       /* Now that the arguments are done, transform FN.  */
4427       fn = build_non_dependent_expr (fn);
4428     }
4429
4430   /* A qualified name corresponding to a bound pointer-to-member is
4431      represented as an OFFSET_REF:
4432
4433         struct B { void g(); };
4434         void (B::*p)();
4435         void B::g() { (this->*p)(); }  */
4436   if (TREE_CODE (fn) == OFFSET_REF)
4437     {
4438       tree object_addr = cp_build_addr_expr (object, complain);
4439       fn = TREE_OPERAND (fn, 1);
4440       fn = get_member_function_from_ptrfunc (&object_addr, fn,
4441                                              complain);
4442       vec_safe_insert (*args, 0, object_addr);
4443     }
4444
4445   if (CLASS_TYPE_P (TREE_TYPE (fn)))
4446     expr = build_op_call (fn, args, complain);
4447   else
4448     expr = cp_build_function_call_vec (fn, args, complain);
4449   if (processing_template_decl && expr != error_mark_node)
4450     expr = build_min_non_dep_call_vec (expr, orig_fn, orig_args);
4451
4452   if (orig_args != NULL)
4453     release_tree_vector (orig_args);
4454
4455   return expr;
4456 }
4457
4458
4459 void
4460 check_default_args (tree x)
4461 {
4462   tree arg = TYPE_ARG_TYPES (TREE_TYPE (x));
4463   bool saw_def = false;
4464   int i = 0 - (TREE_CODE (TREE_TYPE (x)) == METHOD_TYPE);
4465   for (; arg && arg != void_list_node; arg = TREE_CHAIN (arg), ++i)
4466     {
4467       if (TREE_PURPOSE (arg))
4468         saw_def = true;
4469       else if (saw_def)
4470         {
4471           error ("default argument missing for parameter %P of %q+#D", i, x);
4472           TREE_PURPOSE (arg) = error_mark_node;
4473         }
4474     }
4475 }
4476
4477 /* Return true if function DECL can be inlined.  This is used to force
4478    instantiation of methods that might be interesting for inlining.  */
4479 bool
4480 possibly_inlined_p (tree decl)
4481 {
4482   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL);
4483   if (DECL_UNINLINABLE (decl))
4484     return false;
4485   if (!optimize || pragma_java_exceptions)
4486     return DECL_DECLARED_INLINE_P (decl);
4487   /* When optimizing, we might inline everything when flatten
4488      attribute or heuristics inlining for size or autoinlining
4489      is used.  */
4490   return true;
4491 }
4492
4493 /* Mark DECL (either a _DECL or a BASELINK) as "used" in the program.
4494    If DECL is a specialization or implicitly declared class member,
4495    generate the actual definition.  Return false if something goes
4496    wrong, true otherwise.  */
4497
4498 bool
4499 mark_used (tree decl)
4500 {
4501   /* If DECL is a BASELINK for a single function, then treat it just
4502      like the DECL for the function.  Otherwise, if the BASELINK is
4503      for an overloaded function, we don't know which function was
4504      actually used until after overload resolution.  */
4505   if (BASELINK_P (decl))
4506     {
4507       decl = BASELINK_FUNCTIONS (decl);
4508       if (really_overloaded_fn (decl))
4509         return true;
4510       decl = OVL_CURRENT (decl);
4511     }
4512
4513   /* Set TREE_USED for the benefit of -Wunused.  */
4514   TREE_USED (decl) = 1;
4515   if (DECL_CLONED_FUNCTION_P (decl))
4516     TREE_USED (DECL_CLONED_FUNCTION (decl)) = 1;
4517
4518   /* Mark enumeration types as used.  */
4519   if (TREE_CODE (decl) == CONST_DECL)
4520     used_types_insert (DECL_CONTEXT (decl));
4521
4522   if (TREE_CODE (decl) == FUNCTION_DECL
4523       && DECL_DELETED_FN (decl))
4524     {
4525       if (DECL_ARTIFICIAL (decl))
4526         {
4527           if (DECL_OVERLOADED_OPERATOR_P (decl) == TYPE_EXPR
4528               && LAMBDA_TYPE_P (DECL_CONTEXT (decl)))
4529             {
4530               /* We mark a lambda conversion op as deleted if we can't
4531                  generate it properly; see maybe_add_lambda_conv_op.  */
4532               sorry ("converting lambda which uses %<...%> to "
4533                      "function pointer");
4534               return false;
4535             }
4536         }
4537       error ("use of deleted function %qD", decl);
4538       if (!maybe_explain_implicit_delete (decl))
4539         error_at (DECL_SOURCE_LOCATION (decl), "declared here");
4540       return false;
4541     }
4542
4543   /* We can only check DECL_ODR_USED on variables or functions with
4544      DECL_LANG_SPECIFIC set, and these are also the only decls that we
4545      might need special handling for.  */
4546   if ((TREE_CODE (decl) != VAR_DECL && TREE_CODE (decl) != FUNCTION_DECL)
4547       || DECL_LANG_SPECIFIC (decl) == NULL
4548       || DECL_THUNK_P (decl))
4549     {
4550       if (!processing_template_decl && type_uses_auto (TREE_TYPE (decl)))
4551         {
4552           error ("use of %qD before deduction of %<auto%>", decl);
4553           return false;
4554         }
4555       return true;
4556     }
4557
4558   /* We only want to do this processing once.  We don't need to keep trying
4559      to instantiate inline templates, because unit-at-a-time will make sure
4560      we get them compiled before functions that want to inline them.  */
4561   if (DECL_ODR_USED (decl))
4562     return true;
4563
4564   /* If within finish_function, defer the rest until that function
4565      finishes, otherwise it might recurse.  */
4566   if (defer_mark_used_calls)
4567     {
4568       vec_safe_push (deferred_mark_used_calls, decl);
4569       return true;
4570     }
4571
4572   if (TREE_CODE (decl) == FUNCTION_DECL)
4573     maybe_instantiate_noexcept (decl);
4574
4575   /* Normally, we can wait until instantiation-time to synthesize DECL.
4576      However, if DECL is a static data member initialized with a constant
4577      or a constexpr function, we need it right now because a reference to
4578      such a data member or a call to such function is not value-dependent.
4579      For a function that uses auto in the return type, we need to instantiate
4580      it to find out its type.  */
4581   if ((decl_maybe_constant_var_p (decl)
4582        || (TREE_CODE (decl) == FUNCTION_DECL
4583            && DECL_DECLARED_CONSTEXPR_P (decl))
4584        || type_uses_auto (TREE_TYPE (decl)))
4585       && DECL_LANG_SPECIFIC (decl)
4586       && DECL_TEMPLATE_INFO (decl)
4587       && !uses_template_parms (DECL_TI_ARGS (decl)))
4588     {
4589       /* Instantiating a function will result in garbage collection.  We
4590          must treat this situation as if we were within the body of a
4591          function so as to avoid collecting live data only referenced from
4592          the stack (such as overload resolution candidates).  */
4593       ++function_depth;
4594       instantiate_decl (decl, /*defer_ok=*/false,
4595                         /*expl_inst_class_mem_p=*/false);
4596       --function_depth;
4597     }
4598
4599   if (processing_template_decl)
4600     return true;
4601
4602   /* Check this too in case we're within fold_non_dependent_expr.  */
4603   if (DECL_TEMPLATE_INFO (decl)
4604       && uses_template_parms (DECL_TI_ARGS (decl)))
4605     return true;
4606
4607   if (type_uses_auto (TREE_TYPE (decl)))
4608     {
4609       error ("use of %qD before deduction of %<auto%>", decl);
4610       return false;
4611     }
4612
4613   /* If we don't need a value, then we don't need to synthesize DECL.  */
4614   if (cp_unevaluated_operand != 0)
4615     return true;
4616
4617   DECL_ODR_USED (decl) = 1;
4618   if (DECL_CLONED_FUNCTION_P (decl))
4619     DECL_ODR_USED (DECL_CLONED_FUNCTION (decl)) = 1;
4620
4621   /* DR 757: A type without linkage shall not be used as the type of a
4622      variable or function with linkage, unless
4623    o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
4624    o the variable or function is not used (3.2 [basic.def.odr]) or is
4625    defined in the same translation unit.  */
4626   if (cxx_dialect > cxx98
4627       && decl_linkage (decl) != lk_none
4628       && !DECL_EXTERN_C_P (decl)
4629       && !DECL_ARTIFICIAL (decl)
4630       && !decl_defined_p (decl)
4631       && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
4632     {
4633       if (is_local_extern (decl))
4634         /* There's no way to define a local extern, and adding it to
4635            the vector interferes with GC, so give an error now.  */
4636         no_linkage_error (decl);
4637       else
4638         vec_safe_push (no_linkage_decls, decl);
4639     }
4640
4641   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_DECLARED_INLINE_P (decl)
4642       && !DECL_INITIAL (decl) && !DECL_ARTIFICIAL (decl))
4643     /* Remember it, so we can check it was defined.  */
4644     note_vague_linkage_fn (decl);
4645
4646   /* Is it a synthesized method that needs to be synthesized?  */
4647   if (TREE_CODE (decl) == FUNCTION_DECL
4648       && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
4649       && DECL_DEFAULTED_FN (decl)
4650       /* A function defaulted outside the class is synthesized either by
4651          cp_finish_decl or instantiate_decl.  */
4652       && !DECL_DEFAULTED_OUTSIDE_CLASS_P (decl)
4653       && ! DECL_INITIAL (decl))
4654     {
4655       /* Defer virtual destructors so that thunks get the right
4656          linkage.  */
4657       if (DECL_VIRTUAL_P (decl) && !at_eof)
4658         {
4659           note_vague_linkage_fn (decl);
4660           return true;
4661         }
4662
4663       /* Remember the current location for a function we will end up
4664          synthesizing.  Then we can inform the user where it was
4665          required in the case of error.  */
4666       DECL_SOURCE_LOCATION (decl) = input_location;
4667
4668       /* Synthesizing an implicitly defined member function will result in
4669          garbage collection.  We must treat this situation as if we were
4670          within the body of a function so as to avoid collecting live data
4671          on the stack (such as overload resolution candidates).
4672
4673          We could just let cp_write_global_declarations handle synthesizing
4674          this function by adding it to deferred_fns, but doing
4675          it at the use site produces better error messages.  */
4676       ++function_depth;
4677       synthesize_method (decl);
4678       --function_depth;
4679       /* If this is a synthesized method we don't need to
4680          do the instantiation test below.  */
4681     }
4682   else if ((TREE_CODE (decl) == FUNCTION_DECL || TREE_CODE (decl) == VAR_DECL)
4683            && DECL_TEMPLATE_INFO (decl)
4684            && (!DECL_EXPLICIT_INSTANTIATION (decl)
4685                || always_instantiate_p (decl)))
4686     /* If this is a function or variable that is an instance of some
4687        template, we now know that we will need to actually do the
4688        instantiation. We check that DECL is not an explicit
4689        instantiation because that is not checked in instantiate_decl.
4690
4691        We put off instantiating functions in order to improve compile
4692        times.  Maintaining a stack of active functions is expensive,
4693        and the inliner knows to instantiate any functions it might
4694        need.  Therefore, we always try to defer instantiation.  */
4695     {
4696       ++function_depth;
4697       instantiate_decl (decl, /*defer_ok=*/true,
4698                         /*expl_inst_class_mem_p=*/false);
4699       --function_depth;
4700     }
4701
4702   return true;
4703 }
4704
4705 #include "gt-cp-decl2.h"