OSDN Git Service

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