OSDN Git Service

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