OSDN Git Service

* decl2.c (mark_member_pointers): Verify that member pointer points to
[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 Free Software Foundation, Inc.
4    Hacked by Michael Tiemann (tiemann@cygnus.com)
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
11 any later version.
12
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING.  If not, write to
20 the Free Software Foundation, 59 Temple Place - Suite 330,
21 Boston, MA 02111-1307, USA.  */
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 "lex.h"
42 #include "output.h"
43 #include "except.h"
44 #include "toplev.h"
45 #include "timevar.h"
46 #include "cpplib.h"
47 #include "target.h"
48 #include "c-common.h"
49 #include "cgraph.h"
50 #include "tree-inline.h"
51 extern cpp_reader *parse_in;
52
53 /* This structure contains information about the initializations
54    and/or destructions required for a particular priority level.  */
55 typedef struct priority_info_s {
56   /* Nonzero if there have been any initializations at this priority
57      throughout the translation unit.  */
58   int initializations_p;
59   /* Nonzero if there have been any destructions at this priority
60      throughout the translation unit.  */
61   int destructions_p;
62 } *priority_info;
63
64 static void mark_vtable_entries (tree);
65 static void grok_function_init (tree, tree);
66 static bool maybe_emit_vtables (tree);
67 static void add_using_namespace (tree, tree, bool);
68 static cxx_binding *ambiguous_decl (tree, cxx_binding *, cxx_binding *, int);
69 static tree build_anon_union_vars (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 merge_functions (tree, tree);
74 static tree decl_namespace (tree);
75 static tree validate_nonmember_using_decl (tree, tree *, tree *);
76 static void do_nonmember_using_decl (tree, tree, tree, tree, tree *, tree *);
77 static tree start_static_storage_duration_function (unsigned);
78 static void finish_static_storage_duration_function (tree);
79 static priority_info get_priority_info (int);
80 static void do_static_initialization (tree, tree);
81 static void do_static_destruction (tree);
82 static tree start_static_initialization_or_destruction (tree, int);
83 static void finish_static_initialization_or_destruction (tree);
84 static void generate_ctor_or_dtor_function (bool, int, location_t *);
85 static int generate_ctor_and_dtor_functions_for_priority (splay_tree_node,
86                                                           void *);
87 static tree prune_vars_needing_no_initialization (tree *);
88 static void write_out_vars (tree);
89 static void import_export_class (tree);
90 static tree get_guard_bits (tree);
91
92 /* A list of static class variables.  This is needed, because a
93    static class variable can be declared inside the class without
94    an initializer, and then initialized, statically, outside the class.  */
95 static GTY(()) varray_type pending_statics;
96 #define pending_statics_used \
97   (pending_statics ? pending_statics->elements_used : 0)
98
99 /* A list of functions which were declared inline, but which we
100    may need to emit outline anyway.  */
101 static GTY(()) varray_type deferred_fns;
102 #define deferred_fns_used \
103   (deferred_fns ? deferred_fns->elements_used : 0)
104
105 /* Flag used when debugging spew.c */
106
107 extern int spew_debug;
108
109 /* Nonzero if we're done parsing and into end-of-file activities.  */
110
111 int at_eof;
112
113 /* Functions called along with real static constructors and destructors.  */
114
115 tree static_ctors;
116 tree static_dtors;
117
118 /* The :: namespace.  */
119
120 tree global_namespace;
121 \f
122 /* Incorporate `const' and `volatile' qualifiers for member functions.
123    FUNCTION is a TYPE_DECL or a FUNCTION_DECL.
124    QUALS is a list of qualifiers.  Returns any explicit
125    top-level qualifiers of the method's this pointer, anything other than
126    TYPE_UNQUALIFIED will be an extension.  */
127
128 int
129 grok_method_quals (tree ctype, tree function, tree quals)
130 {
131   tree fntype = TREE_TYPE (function);
132   tree raises = TYPE_RAISES_EXCEPTIONS (fntype);
133   int type_quals = TYPE_UNQUALIFIED;
134   int dup_quals = TYPE_UNQUALIFIED;
135   int this_quals = TYPE_UNQUALIFIED;
136
137   do
138     {
139       int tq = cp_type_qual_from_rid (TREE_VALUE (quals));
140       
141       if ((type_quals | this_quals) & tq)
142         dup_quals |= tq;
143       else if (tq & TYPE_QUAL_RESTRICT)
144         this_quals |= tq;
145       else
146         type_quals |= tq;
147       quals = TREE_CHAIN (quals);
148     } 
149   while (quals);
150
151   if (dup_quals != TYPE_UNQUALIFIED)
152     error ("duplicate type qualifiers in %s declaration",
153               TREE_CODE (function) == FUNCTION_DECL 
154               ? "member function" : "type");
155
156   ctype = cp_build_qualified_type (ctype, type_quals);
157   fntype = build_cplus_method_type (ctype, TREE_TYPE (fntype),
158                                     (TREE_CODE (fntype) == METHOD_TYPE
159                                      ? TREE_CHAIN (TYPE_ARG_TYPES (fntype))
160                                      : TYPE_ARG_TYPES (fntype)));
161   if (raises)
162     fntype = build_exception_variant (fntype, raises);
163
164   TREE_TYPE (function) = fntype;
165   return this_quals;
166 }
167
168 /* Warn when -fexternal-templates is used and #pragma
169    interface/implementation is not used all the times it should be,
170    inform the user.  */
171
172 void
173 warn_if_unknown_interface (tree decl)
174 {
175   static int already_warned = 0;
176   if (already_warned++)
177     return;
178
179   if (flag_alt_external_templates)
180     {
181       tree til = tinst_for_decl ();
182       location_t saved_loc = input_location;
183
184       if (til)
185         {
186           input_line = TINST_LINE (til);
187           input_filename = TINST_FILE (til);
188         }
189       warning ("template `%#D' instantiated in file without #pragma interface",
190                   decl);
191       input_location = saved_loc;
192     }
193   else
194     cp_warning_at ("template `%#D' defined in file without #pragma interface",
195                    decl);
196 }
197
198 /* A subroutine of the parser, to handle a component list.  */
199
200 void
201 grok_x_components (tree specs)
202 {
203   tree t;
204
205   specs = strip_attrs (specs);
206
207   check_tag_decl (specs);
208   t = groktypename (build_tree_list (specs, NULL_TREE)); 
209
210   /* The only case where we need to do anything additional here is an
211      anonymous union field, e.g.: `struct S { union { int i; }; };'.  */
212   if (t == NULL_TREE || !ANON_AGGR_TYPE_P (t))
213     return;
214
215   fixup_anonymous_aggr (t);
216   finish_member_declaration (build_decl (FIELD_DECL, NULL_TREE, t)); 
217 }
218
219 /* Build a PARM_DECL with NAME and TYPE, and set DECL_ARG_TYPE
220    appropriately.  */
221
222 tree
223 cp_build_parm_decl (tree name, tree type)
224 {
225   tree parm = build_decl (PARM_DECL, name, type);
226   DECL_ARG_TYPE (parm) = type_passed_as (type);
227   return parm;
228 }
229
230 /* Returns a PARM_DECL for a parameter of the indicated TYPE, with the
231    indicated NAME.  */
232
233 tree
234 build_artificial_parm (tree name, tree type)
235 {
236   tree parm = cp_build_parm_decl (name, type);
237   DECL_ARTIFICIAL (parm) = 1;
238   /* All our artificial parms are implicitly `const'; they cannot be
239      assigned to.  */
240   TREE_READONLY (parm) = 1;
241   return parm;
242 }
243
244 /* Constructors for types with virtual baseclasses need an "in-charge" flag
245    saying whether this constructor is responsible for initialization of
246    virtual baseclasses or not.  All destructors also need this "in-charge"
247    flag, which additionally determines whether or not the destructor should
248    free the memory for the object.
249
250    This function adds the "in-charge" flag to member function FN if
251    appropriate.  It is called from grokclassfn and tsubst.
252    FN must be either a constructor or destructor.
253
254    The in-charge flag follows the 'this' parameter, and is followed by the
255    VTT parm (if any), then the user-written parms.  */
256
257 void
258 maybe_retrofit_in_chrg (tree fn)
259 {
260   tree basetype, arg_types, parms, parm, fntype;
261
262   /* If we've already add the in-charge parameter don't do it again.  */
263   if (DECL_HAS_IN_CHARGE_PARM_P (fn))
264     return;
265
266   /* When processing templates we can't know, in general, whether or
267      not we're going to have virtual baseclasses.  */
268   if (uses_template_parms (fn))
269     return;
270
271   /* We don't need an in-charge parameter for constructors that don't
272      have virtual bases.  */
273   if (DECL_CONSTRUCTOR_P (fn)
274       && !TYPE_USES_VIRTUAL_BASECLASSES (DECL_CONTEXT (fn)))
275     return;
276
277   arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
278   basetype = TREE_TYPE (TREE_VALUE (arg_types));
279   arg_types = TREE_CHAIN (arg_types);
280
281   parms = TREE_CHAIN (DECL_ARGUMENTS (fn));
282
283   /* If this is a subobject constructor or destructor, our caller will
284      pass us a pointer to our VTT.  */
285   if (TYPE_USES_VIRTUAL_BASECLASSES (DECL_CONTEXT (fn)))
286     {
287       parm = build_artificial_parm (vtt_parm_identifier, vtt_parm_type);
288
289       /* First add it to DECL_ARGUMENTS between 'this' and the real args...  */
290       TREE_CHAIN (parm) = parms;
291       parms = parm;
292
293       /* ...and then to TYPE_ARG_TYPES.  */
294       arg_types = hash_tree_chain (vtt_parm_type, arg_types);
295
296       DECL_HAS_VTT_PARM_P (fn) = 1;
297     }
298
299   /* Then add the in-charge parm (before the VTT parm).  */
300   parm = build_artificial_parm (in_charge_identifier, integer_type_node);
301   TREE_CHAIN (parm) = parms;
302   parms = parm;
303   arg_types = hash_tree_chain (integer_type_node, arg_types);
304
305   /* Insert our new parameter(s) into the list.  */
306   TREE_CHAIN (DECL_ARGUMENTS (fn)) = parms;
307
308   /* And rebuild the function type.  */
309   fntype = build_cplus_method_type (basetype, TREE_TYPE (TREE_TYPE (fn)),
310                                     arg_types);
311   if (TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn)))
312     fntype = build_exception_variant (fntype,
313                                       TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn)));
314   TREE_TYPE (fn) = fntype;
315
316   /* Now we've got the in-charge parameter.  */
317   DECL_HAS_IN_CHARGE_PARM_P (fn) = 1;
318 }
319
320 /* Classes overload their constituent function names automatically.
321    When a function name is declared in a record structure,
322    its name is changed to it overloaded name.  Since names for
323    constructors and destructors can conflict, we place a leading
324    '$' for destructors.
325
326    CNAME is the name of the class we are grokking for.
327
328    FUNCTION is a FUNCTION_DECL.  It was created by `grokdeclarator'.
329
330    FLAGS contains bits saying what's special about today's
331    arguments.  1 == DESTRUCTOR.  2 == OPERATOR.
332
333    If FUNCTION is a destructor, then we must add the `auto-delete' field
334    as a second parameter.  There is some hair associated with the fact
335    that we must "declare" this variable in the manner consistent with the
336    way the rest of the arguments were declared.
337
338    QUALS are the qualifiers for the this pointer.  */
339
340 void
341 grokclassfn (tree ctype, tree function, enum overload_flags flags, tree quals)
342 {
343   tree fn_name = DECL_NAME (function);
344   int this_quals = TYPE_UNQUALIFIED;
345
346   /* Even within an `extern "C"' block, members get C++ linkage.  See
347      [dcl.link] for details.  */
348   SET_DECL_LANGUAGE (function, lang_cplusplus);
349
350   if (fn_name == NULL_TREE)
351     {
352       error ("name missing for member function");
353       fn_name = get_identifier ("<anonymous>");
354       DECL_NAME (function) = fn_name;
355     }
356
357   if (quals)
358     this_quals = grok_method_quals (ctype, function, quals);
359
360   if (TREE_CODE (TREE_TYPE (function)) == METHOD_TYPE)
361     {
362       /* Must add the class instance variable up front.  */
363       /* Right now we just make this a pointer.  But later
364          we may wish to make it special.  */
365       tree type = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (function)));
366       tree qual_type;
367       tree parm;
368
369       /* The `this' parameter is implicitly `const'; it cannot be
370          assigned to.  */
371       this_quals |= TYPE_QUAL_CONST;
372       qual_type = cp_build_qualified_type (type, this_quals);
373       parm = build_artificial_parm (this_identifier, qual_type);
374       c_apply_type_quals_to_decl (this_quals, parm);
375       TREE_CHAIN (parm) = last_function_parms;
376       last_function_parms = parm;
377     }
378
379   DECL_ARGUMENTS (function) = last_function_parms;
380   DECL_CONTEXT (function) = ctype;
381
382   if (flags == DTOR_FLAG)
383     DECL_DESTRUCTOR_P (function) = 1;
384
385   if (flags == DTOR_FLAG || DECL_CONSTRUCTOR_P (function))
386     maybe_retrofit_in_chrg (function);
387
388   if (flags == DTOR_FLAG)
389     {
390       DECL_DESTRUCTOR_P (function) = 1;
391       TYPE_HAS_DESTRUCTOR (ctype) = 1;
392     }
393 }
394
395 /* Create an ARRAY_REF, checking for the user doing things backwards
396    along the way.  */
397
398 tree
399 grok_array_decl (tree array_expr, tree index_exp)
400 {
401   tree type;
402   tree expr;
403   tree orig_array_expr = array_expr;
404   tree orig_index_exp = index_exp;
405
406   if (error_operand_p (array_expr) || error_operand_p (index_exp))
407     return error_mark_node;
408
409   if (processing_template_decl)
410     {
411       if (type_dependent_expression_p (array_expr)
412           || type_dependent_expression_p (index_exp))
413         return build_min_nt (ARRAY_REF, array_expr, index_exp);
414       array_expr = build_non_dependent_expr (array_expr);
415       index_exp = build_non_dependent_expr (index_exp);
416     }
417
418   type = TREE_TYPE (array_expr);
419   my_friendly_assert (type, 20030626);
420   type = non_reference (type);
421
422   /* If they have an `operator[]', use that.  */
423   if (IS_AGGR_TYPE (type) || IS_AGGR_TYPE (TREE_TYPE (index_exp)))
424     expr = build_new_op (ARRAY_REF, LOOKUP_NORMAL,
425                          array_expr, index_exp, NULL_TREE);
426   else
427     {
428       tree p1, p2, i1, i2;
429
430       /* Otherwise, create an ARRAY_REF for a pointer or array type.
431          It is a little-known fact that, if `a' is an array and `i' is
432          an int, you can write `i[a]', which means the same thing as
433          `a[i]'.  */
434       if (TREE_CODE (type) == ARRAY_TYPE)
435         p1 = array_expr;
436       else
437         p1 = build_expr_type_conversion (WANT_POINTER, array_expr, false);
438
439       if (TREE_CODE (TREE_TYPE (index_exp)) == ARRAY_TYPE)
440         p2 = index_exp;
441       else
442         p2 = build_expr_type_conversion (WANT_POINTER, index_exp, false);
443
444       i1 = build_expr_type_conversion (WANT_INT | WANT_ENUM, array_expr, 
445                                        false);
446       i2 = build_expr_type_conversion (WANT_INT | WANT_ENUM, index_exp, 
447                                        false);
448
449       if ((p1 && i2) && (i1 && p2))
450         error ("ambiguous conversion for array subscript");
451
452       if (p1 && i2)
453         array_expr = p1, index_exp = i2;
454       else if (i1 && p2)
455         array_expr = p2, index_exp = i1;
456       else
457         {
458           error ("invalid types `%T[%T]' for array subscript",
459                     type, TREE_TYPE (index_exp));
460           return error_mark_node;
461         }
462
463       if (array_expr == error_mark_node || index_exp == error_mark_node)
464         error ("ambiguous conversion for array subscript");
465
466       expr = build_array_ref (array_expr, index_exp);
467     }
468   if (processing_template_decl && expr != error_mark_node)
469     return build_min (ARRAY_REF, TREE_TYPE (expr), orig_array_expr, 
470                       orig_index_exp);
471   return expr;
472 }
473
474 /* Given the cast expression EXP, checking out its validity.   Either return
475    an error_mark_node if there was an unavoidable error, return a cast to
476    void for trying to delete a pointer w/ the value 0, or return the
477    call to delete.  If DOING_VEC is 1, we handle things differently
478    for doing an array delete.  If DOING_VEC is 2, they gave us the
479    array size as an argument to delete.
480    Implements ARM $5.3.4.  This is called from the parser.  */
481
482 tree
483 delete_sanity (tree exp, tree size, int doing_vec, int use_global_delete)
484 {
485   tree t, type;
486   /* For a regular vector delete (aka, no size argument) we will pass
487      this down as a NULL_TREE into build_vec_delete.  */
488   tree maxindex = NULL_TREE;
489
490   if (exp == error_mark_node)
491     return exp;
492
493   if (processing_template_decl)
494     {
495       t = build_min (DELETE_EXPR, void_type_node, exp, size);
496       DELETE_EXPR_USE_GLOBAL (t) = use_global_delete;
497       DELETE_EXPR_USE_VEC (t) = doing_vec;
498       return t;
499     }
500
501   exp = convert_from_reference (exp);
502   t = build_expr_type_conversion (WANT_POINTER, exp, true);
503
504   if (t == NULL_TREE || t == error_mark_node)
505     {
506       error ("type `%#T' argument given to `delete', expected pointer",
507                 TREE_TYPE (exp));
508       return error_mark_node;
509     }
510
511   if (doing_vec == 2)
512     {
513       maxindex = cp_build_binary_op (MINUS_EXPR, size, integer_one_node);
514       pedwarn ("anachronistic use of array size in vector delete");
515     }
516
517   type = TREE_TYPE (t);
518
519   /* As of Valley Forge, you can delete a pointer to const.  */
520
521   /* You can't delete functions.  */
522   if (TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE)
523     {
524       error ("cannot delete a function.  Only pointer-to-objects are valid arguments to `delete'");
525       return error_mark_node;
526     }
527
528   /* Deleting ptr to void is undefined behavior [expr.delete/3].  */
529   if (TREE_CODE (TREE_TYPE (type)) == VOID_TYPE)
530     {
531       warning ("deleting `%T' is undefined", type);
532       doing_vec = 0;
533     }
534
535   /* An array can't have been allocated by new, so complain.  */
536   if (TREE_CODE (t) == ADDR_EXPR
537       && TREE_CODE (TREE_OPERAND (t, 0)) == VAR_DECL
538       && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == ARRAY_TYPE)
539     warning ("deleting array `%#D'", TREE_OPERAND (t, 0));
540
541   /* Deleting a pointer with the value zero is valid and has no effect.  */
542   if (integer_zerop (t))
543     return build1 (NOP_EXPR, void_type_node, t);
544
545   if (doing_vec)
546     return build_vec_delete (t, maxindex, sfk_deleting_destructor,
547                              use_global_delete);
548   else
549     return build_delete (type, t, sfk_deleting_destructor,
550                          LOOKUP_NORMAL, use_global_delete);
551 }
552
553 /* Report an error if the indicated template declaration is not the
554    sort of thing that should be a member template.  */
555
556 void
557 check_member_template (tree tmpl)
558 {
559   tree decl;
560
561   my_friendly_assert (TREE_CODE (tmpl) == TEMPLATE_DECL, 0);
562   decl = DECL_TEMPLATE_RESULT (tmpl);
563
564   if (TREE_CODE (decl) == FUNCTION_DECL
565       || (TREE_CODE (decl) == TYPE_DECL
566           && IS_AGGR_TYPE (TREE_TYPE (decl))))
567     {
568       if (current_function_decl)
569         /* 14.5.2.2 [temp.mem]
570            
571            A local class shall not have member templates.  */
572         error ("invalid declaration of member template `%#D' in local class",
573                   decl);
574       
575       if (TREE_CODE (decl) == FUNCTION_DECL && DECL_VIRTUAL_P (decl))
576         {
577           /* 14.5.2.3 [temp.mem]
578
579              A member function template shall not be virtual.  */
580           error 
581             ("invalid use of `virtual' in template declaration of `%#D'",
582              decl);
583           DECL_VIRTUAL_P (decl) = 0;
584         }
585
586       /* The debug-information generating code doesn't know what to do
587          with member templates.  */ 
588       DECL_IGNORED_P (tmpl) = 1;
589     } 
590   else
591     error ("template declaration of `%#D'", decl);
592 }
593
594 /* Return true iff TYPE is a valid Java parameter or return type.  */
595
596 static bool
597 acceptable_java_type (tree type)
598 {
599   if (TREE_CODE (type) == VOID_TYPE || TYPE_FOR_JAVA (type))
600     return 1;
601   if (TREE_CODE (type) == POINTER_TYPE || TREE_CODE (type) == REFERENCE_TYPE)
602     {
603       type = TREE_TYPE (type);
604       if (TREE_CODE (type) == RECORD_TYPE)
605         {
606           tree args;  int i;
607           if (! TYPE_FOR_JAVA (type))
608             return false;
609           if (! CLASSTYPE_TEMPLATE_INFO (type))
610             return true;
611           args = CLASSTYPE_TI_ARGS (type);
612           i = TREE_VEC_LENGTH (args);
613           while (--i >= 0)
614             {
615               type = TREE_VEC_ELT (args, i);
616               if (TREE_CODE (type) == POINTER_TYPE)
617                 type = TREE_TYPE (type);
618               if (! TYPE_FOR_JAVA (type))
619                 return false;
620             }
621           return true;
622         }
623     }
624   return false;
625 }
626
627 /* For a METHOD in a Java class CTYPE, return true if
628    the parameter and return types are valid Java types.
629    Otherwise, print appropriate error messages, and return false.  */
630
631 bool
632 check_java_method (tree method)
633 {
634   bool jerr = false;
635   tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (method));
636   tree ret_type = TREE_TYPE (TREE_TYPE (method));
637   if (!acceptable_java_type (ret_type))
638     {
639       error ("Java method '%D' has non-Java return type `%T'",
640                 method, ret_type);
641       jerr = true;
642     }
643   for (; arg_types != NULL_TREE; arg_types = TREE_CHAIN (arg_types))
644     {
645       tree type = TREE_VALUE (arg_types);
646       if (!acceptable_java_type (type))
647         {
648           error ("Java method '%D' has non-Java parameter type `%T'",
649                     method, type);
650           jerr = true;
651         }
652     }
653   return !jerr;
654 }
655
656 /* Sanity check: report error if this function FUNCTION is not
657    really a member of the class (CTYPE) it is supposed to belong to.
658    CNAME is the same here as it is for grokclassfn above.  */
659
660 tree
661 check_classfn (tree ctype, tree function)
662 {
663   int ix;
664   int is_template;
665   
666   if (DECL_USE_TEMPLATE (function)
667       && !(TREE_CODE (function) == TEMPLATE_DECL
668            && DECL_TEMPLATE_SPECIALIZATION (function))
669       && is_member_template (DECL_TI_TEMPLATE (function)))
670     /* Since this is a specialization of a member template,
671        we're not going to find the declaration in the class.
672        For example, in:
673        
674          struct S { template <typename T> void f(T); };
675          template <> void S::f(int);
676        
677        we're not going to find `S::f(int)', but there's no
678        reason we should, either.  We let our callers know we didn't
679        find the method, but we don't complain.  */
680     return NULL_TREE;
681
682   /* OK, is this a definition of a member template?  */
683   is_template = (TREE_CODE (function) == TEMPLATE_DECL
684                  || (processing_template_decl - template_class_depth (ctype)));
685
686   ix = lookup_fnfields_1 (complete_type (ctype),
687                           DECL_CONSTRUCTOR_P (function) ? ctor_identifier :
688                           DECL_DESTRUCTOR_P (function) ? dtor_identifier :
689                           DECL_NAME (function));
690
691   if (ix >= 0)
692     {
693       tree methods = CLASSTYPE_METHOD_VEC (ctype);
694       tree fndecls, fndecl = 0;
695       bool is_conv_op;
696       const char *format = NULL;
697       
698       push_scope (ctype);
699       for (fndecls = TREE_VEC_ELT (methods, ix);
700            fndecls; fndecls = OVL_NEXT (fndecls))
701         {
702           tree p1, p2;
703           
704           fndecl = OVL_CURRENT (fndecls);
705           p1 = TYPE_ARG_TYPES (TREE_TYPE (function));
706           p2 = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
707
708           /* We cannot simply call decls_match because this doesn't
709              work for static member functions that are pretending to
710              be methods, and because the name may have been changed by
711              asm("new_name").  */ 
712               
713            /* Get rid of the this parameter on functions that become
714               static.  */
715           if (DECL_STATIC_FUNCTION_P (fndecl)
716               && TREE_CODE (TREE_TYPE (function)) == METHOD_TYPE)
717             p1 = TREE_CHAIN (p1);
718
719           /* A member template definition only matches a member template
720              declaration.  */
721           if (is_template != (TREE_CODE (fndecl) == TEMPLATE_DECL))
722             continue;
723               
724           if (same_type_p (TREE_TYPE (TREE_TYPE (function)),
725                            TREE_TYPE (TREE_TYPE (fndecl)))
726               && compparms (p1, p2)
727               && (DECL_TEMPLATE_SPECIALIZATION (function)
728                   == DECL_TEMPLATE_SPECIALIZATION (fndecl))
729               && (!DECL_TEMPLATE_SPECIALIZATION (function)
730                   || (DECL_TI_TEMPLATE (function) 
731                       == DECL_TI_TEMPLATE (fndecl))))
732             break;
733         }
734       pop_scope (ctype);
735       if (fndecls)
736         return OVL_CURRENT (fndecls);
737       error ("prototype for `%#D' does not match any in class `%T'",
738              function, ctype);
739       is_conv_op = DECL_CONV_FN_P (fndecl);
740
741       if (is_conv_op)
742         ix = CLASSTYPE_FIRST_CONVERSION_SLOT;
743       fndecls = TREE_VEC_ELT (methods, ix);
744       while (fndecls)
745         {
746           fndecl = OVL_CURRENT (fndecls);
747           fndecls = OVL_NEXT (fndecls);
748
749           if (!fndecls && is_conv_op)
750             {
751               if (TREE_VEC_LENGTH (methods) > ix)
752                 {
753                   ix++;
754                   fndecls = TREE_VEC_ELT (methods, ix);
755                   if (!DECL_CONV_FN_P (OVL_CURRENT (fndecls)))
756                     {
757                       fndecls = NULL_TREE;
758                       is_conv_op = false;
759                     }
760                 }
761               else
762                 is_conv_op = false;
763             }
764           if (format)
765             format = "                %#D";
766           else if (fndecls)
767             format = "candidates are: %#D";
768           else
769             format = "candidate is: %#D";
770           cp_error_at (format, fndecl);
771         }
772     }
773   else if (!COMPLETE_TYPE_P (ctype))
774     cxx_incomplete_type_error (function, ctype);
775   else
776     error ("no `%#D' member function declared in class `%T'",
777            function, ctype);
778
779   /* If we did not find the method in the class, add it to avoid
780      spurious errors (unless the CTYPE is not yet defined, in which
781      case we'll only confuse ourselves when the function is declared
782      properly within the class.  */
783   if (COMPLETE_TYPE_P (ctype))
784     add_method (ctype, function, /*error_p=*/1);
785   return NULL_TREE;
786 }
787
788 /* We have just processed the DECL, which is a static data member.
789    Its initializer, if present, is INIT.  The ASMSPEC_TREE, if
790    present, is the assembly-language name for the data member.
791    FLAGS is as for cp_finish_decl.  */
792
793 void
794 finish_static_data_member_decl (tree decl, tree init, tree asmspec_tree,
795                                 int flags)
796 {
797   my_friendly_assert (TREE_PUBLIC (decl), 0);
798
799   DECL_CONTEXT (decl) = current_class_type;
800
801   /* We cannot call pushdecl here, because that would fill in the
802      TREE_CHAIN of our decl.  Instead, we modify cp_finish_decl to do
803      the right thing, namely, to put this decl out straight away.  */
804   /* current_class_type can be NULL_TREE in case of error.  */
805   if (!asmspec_tree && current_class_type)
806     DECL_INITIAL (decl) = error_mark_node;
807
808   if (! processing_template_decl)
809     {
810       if (!pending_statics)
811         VARRAY_TREE_INIT (pending_statics, 32, "pending_statics");
812       VARRAY_PUSH_TREE (pending_statics, decl);
813     }
814
815   if (LOCAL_CLASS_P (current_class_type))
816     pedwarn ("local class `%#T' shall not have static data member `%#D'",
817              current_class_type, decl);
818
819   /* Static consts need not be initialized in the class definition.  */
820   if (init != NULL_TREE && TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (decl)))
821     {
822       static int explained = 0;
823           
824       error ("initializer invalid for static member with constructor");
825       if (!explained)
826         {
827           error ("(an out of class initialization is required)");
828           explained = 1;
829         }
830       init = NULL_TREE;
831     }
832   /* Force the compiler to know when an uninitialized static const
833      member is being used.  */
834   if (CP_TYPE_CONST_P (TREE_TYPE (decl)) && init == 0)
835     TREE_USED (decl) = 1;
836   DECL_INITIAL (decl) = init;
837   DECL_IN_AGGR_P (decl) = 1;
838
839   cp_finish_decl (decl, init, asmspec_tree, flags);
840 }
841
842 /* Process the specs, declarator (NULL if omitted) and width (NULL if omitted)
843    of a structure component, returning a _DECL node.
844    QUALS is a list of type qualifiers for this decl (such as for declaring
845    const member functions).
846
847    This is done during the parsing of the struct declaration.
848    The _DECL nodes are chained together and the lot of them
849    are ultimately passed to `build_struct' to make the RECORD_TYPE node.
850
851    If class A defines that certain functions in class B are friends, then
852    the way I have set things up, it is B who is interested in permission
853    granted by A.  However, it is in A's context that these declarations
854    are parsed.  By returning a void_type_node, class A does not attempt
855    to incorporate the declarations of the friends within its structure.
856
857    DO NOT MAKE ANY CHANGES TO THIS CODE WITHOUT MAKING CORRESPONDING
858    CHANGES TO CODE IN `start_method'.  */
859
860 tree
861 grokfield (tree declarator, tree declspecs, tree init, tree asmspec_tree,
862            tree attrlist)
863 {
864   tree value;
865   const char *asmspec = 0;
866   int flags = LOOKUP_ONLYCONVERTING;
867
868   if (declspecs == NULL_TREE
869       && TREE_CODE (declarator) == SCOPE_REF
870       && TREE_CODE (TREE_OPERAND (declarator, 1)) == IDENTIFIER_NODE)
871     {
872       /* Access declaration */
873       if (! IS_AGGR_TYPE_CODE (TREE_CODE (TREE_OPERAND (declarator, 0))))
874         ;
875       else if (TREE_COMPLEXITY (declarator) == current_class_depth)
876         pop_nested_class ();
877       return do_class_using_decl (declarator);
878     }
879
880   if (init
881       && TREE_CODE (init) == TREE_LIST
882       && TREE_VALUE (init) == error_mark_node
883       && TREE_CHAIN (init) == NULL_TREE)
884     init = NULL_TREE;
885
886   value = grokdeclarator (declarator, declspecs, FIELD, init != 0, &attrlist);
887   if (! value || value == error_mark_node)
888     /* friend or constructor went bad.  */
889     return value;
890   if (TREE_TYPE (value) == error_mark_node)
891     return error_mark_node;
892
893   if (TREE_CODE (value) == TYPE_DECL && init)
894     {
895       error ("typedef `%D' is initialized (use __typeof__ instead)", value);
896       init = NULL_TREE;
897     }
898
899   /* Pass friendly classes back.  */
900   if (value == void_type_node)
901     return value;
902
903   /* Pass friend decls back.  */
904   if ((TREE_CODE (value) == FUNCTION_DECL
905        || TREE_CODE (value) == TEMPLATE_DECL)
906       && DECL_CONTEXT (value) != current_class_type)
907     return value;
908
909   if (DECL_NAME (value) != NULL_TREE
910       && IDENTIFIER_POINTER (DECL_NAME (value))[0] == '_'
911       && ! strcmp (IDENTIFIER_POINTER (DECL_NAME (value)), "_vptr"))
912     error ("member `%D' conflicts with virtual function table field name",
913               value);
914
915   /* Stash away type declarations.  */
916   if (TREE_CODE (value) == TYPE_DECL)
917     {
918       DECL_NONLOCAL (value) = 1;
919       DECL_CONTEXT (value) = current_class_type;
920
921       if (CLASS_TYPE_P (TREE_TYPE (value)))
922         CLASSTYPE_GOT_SEMICOLON (TREE_TYPE (value)) = 1;
923       
924       if (processing_template_decl)
925         value = push_template_decl (value);
926
927       return value;
928     }
929
930   if (DECL_IN_AGGR_P (value))
931     {
932       error ("`%D' is already defined in `%T'", value,
933                 DECL_CONTEXT (value));
934       return void_type_node;
935     }
936
937   if (asmspec_tree)
938     asmspec = TREE_STRING_POINTER (asmspec_tree);
939
940   if (init)
941     {
942       if (TREE_CODE (value) == FUNCTION_DECL)
943         {
944           grok_function_init (value, init);
945           init = NULL_TREE;
946         }
947       else if (pedantic && TREE_CODE (value) != VAR_DECL)
948         /* Already complained in grokdeclarator.  */
949         init = NULL_TREE;
950       else
951         {
952           /* We allow initializers to become parameters to base
953              initializers.  */
954           if (TREE_CODE (init) == TREE_LIST)
955             {
956               if (TREE_CHAIN (init) == NULL_TREE)
957                 init = TREE_VALUE (init);
958               else
959                 init = digest_init (TREE_TYPE (value), init, (tree *)0);
960             }
961
962           if (!processing_template_decl)
963             {
964               if (TREE_CODE (init) == CONST_DECL)
965                 init = DECL_INITIAL (init);
966               else if (TREE_READONLY_DECL_P (init))
967                 init = decl_constant_value (init);
968               else if (TREE_CODE (init) == CONSTRUCTOR)
969                 init = digest_init (TREE_TYPE (value), init, (tree *)0);
970               if (init != error_mark_node && ! TREE_CONSTANT (init))
971                 {
972                   /* We can allow references to things that are effectively
973                      static, since references are initialized with the
974                      address.  */
975                   if (TREE_CODE (TREE_TYPE (value)) != REFERENCE_TYPE
976                       || (TREE_STATIC (init) == 0
977                           && (!DECL_P (init) || DECL_EXTERNAL (init) == 0)))
978                     {
979                       error ("field initializer is not constant");
980                       init = error_mark_node;
981                     }
982                 }
983             }
984         }
985     }
986
987   if (processing_template_decl
988       && (TREE_CODE (value) == VAR_DECL || TREE_CODE (value) == FUNCTION_DECL))
989     value = push_template_decl (value);
990
991   if (attrlist)
992     cplus_decl_attributes (&value, attrlist, 0);
993
994   if (TREE_CODE (value) == VAR_DECL)
995     {
996       finish_static_data_member_decl (value, init, asmspec_tree, 
997                                       flags);
998       return value;
999     }
1000   if (TREE_CODE (value) == FIELD_DECL)
1001     {
1002       if (asmspec)
1003         error ("`asm' specifiers are not permitted on non-static data members");
1004       if (DECL_INITIAL (value) == error_mark_node)
1005         init = error_mark_node;
1006       cp_finish_decl (value, init, NULL_TREE, flags);
1007       DECL_INITIAL (value) = init;
1008       DECL_IN_AGGR_P (value) = 1;
1009       return value;
1010     }
1011   if (TREE_CODE (value) == FUNCTION_DECL)
1012     {
1013       if (asmspec)
1014         {
1015           /* This must override the asm specifier which was placed
1016              by grokclassfn.  Lay this out fresh.  */
1017           SET_DECL_RTL (value, NULL_RTX);
1018           SET_DECL_ASSEMBLER_NAME (value, get_identifier (asmspec));
1019         }
1020       if (!DECL_FRIEND_P (value))
1021         grok_special_member_properties (value);
1022       
1023       cp_finish_decl (value, init, asmspec_tree, flags);
1024
1025       /* Pass friends back this way.  */
1026       if (DECL_FRIEND_P (value))
1027         return void_type_node;
1028
1029       DECL_IN_AGGR_P (value) = 1;
1030       return value;
1031     }
1032   abort ();
1033   /* NOTREACHED */
1034   return NULL_TREE;
1035 }
1036
1037 /* Like `grokfield', but for bitfields.
1038    WIDTH is non-NULL for bit fields only, and is an INTEGER_CST node.  */
1039
1040 tree
1041 grokbitfield (tree declarator, tree declspecs, tree width)
1042 {
1043   register tree value = grokdeclarator (declarator, declspecs, BITFIELD,
1044                                         0, NULL);
1045
1046   if (! value) return NULL_TREE; /* friends went bad.  */
1047
1048   /* Pass friendly classes back.  */
1049   if (TREE_CODE (value) == VOID_TYPE)
1050     return void_type_node;
1051
1052   if (TREE_CODE (value) == TYPE_DECL)
1053     {
1054       error ("cannot declare `%D' to be a bit-field type", value);
1055       return NULL_TREE;
1056     }
1057
1058   /* Usually, finish_struct_1 catches bitfields with invalid types.
1059      But, in the case of bitfields with function type, we confuse
1060      ourselves into thinking they are member functions, so we must
1061      check here.  */
1062   if (TREE_CODE (value) == FUNCTION_DECL)
1063     {
1064       error ("cannot declare bit-field `%D' with function type",
1065              DECL_NAME (value));
1066       return NULL_TREE;
1067     }
1068
1069   if (DECL_IN_AGGR_P (value))
1070     {
1071       error ("`%D' is already defined in the class %T", value,
1072                   DECL_CONTEXT (value));
1073       return void_type_node;
1074     }
1075
1076   if (TREE_STATIC (value))
1077     {
1078       error ("static member `%D' cannot be a bit-field", value);
1079       return NULL_TREE;
1080     }
1081   cp_finish_decl (value, NULL_TREE, NULL_TREE, 0);
1082
1083   if (width != error_mark_node)
1084     {
1085       constant_expression_warning (width);
1086       DECL_INITIAL (value) = width;
1087       SET_DECL_C_BIT_FIELD (value);
1088     }
1089
1090   DECL_IN_AGGR_P (value) = 1;
1091   return value;
1092 }
1093
1094 /* When a function is declared with an initializer,
1095    do the right thing.  Currently, there are two possibilities:
1096
1097    class B
1098    {
1099     public:
1100      // initialization possibility #1.
1101      virtual void f () = 0;
1102      int g ();
1103    };
1104    
1105    class D1 : B
1106    {
1107     public:
1108      int d1;
1109      // error, no f ();
1110    };
1111    
1112    class D2 : B
1113    {
1114     public:
1115      int d2;
1116      void f ();
1117    };
1118    
1119    class D3 : B
1120    {
1121     public:
1122      int d3;
1123      // initialization possibility #2
1124      void f () = B::f;
1125    };
1126
1127 */
1128
1129 static void
1130 grok_function_init (tree decl, tree init)
1131 {
1132   /* An initializer for a function tells how this function should
1133      be inherited.  */
1134   tree type = TREE_TYPE (decl);
1135
1136   if (TREE_CODE (type) == FUNCTION_TYPE)
1137     error ("initializer specified for non-member function `%D'", decl);
1138   else if (integer_zerop (init))
1139     DECL_PURE_VIRTUAL_P (decl) = 1;
1140   else
1141     error ("invalid initializer for virtual method `%D'", decl);
1142 }
1143 \f
1144 void
1145 cplus_decl_attributes (tree *decl, tree attributes, int flags)
1146 {
1147   if (*decl == NULL_TREE || *decl == void_type_node)
1148     return;
1149
1150   if (TREE_CODE (*decl) == TEMPLATE_DECL)
1151     decl = &DECL_TEMPLATE_RESULT (*decl);
1152
1153   decl_attributes (decl, attributes, flags);
1154
1155   if (TREE_CODE (*decl) == TYPE_DECL)
1156     SET_IDENTIFIER_TYPE_VALUE (DECL_NAME (*decl), TREE_TYPE (*decl));
1157 }
1158 \f
1159 /* Return the name for the constructor (or destructor) for the
1160    specified class TYPE.  When given a template, this routine doesn't
1161    lose the specialization.  */
1162
1163 tree
1164 constructor_name_full (tree type)
1165 {
1166   type = TYPE_MAIN_VARIANT (type);
1167   if (CLASS_TYPE_P (type) && TYPE_WAS_ANONYMOUS (type) 
1168       && TYPE_HAS_CONSTRUCTOR (type))
1169     return DECL_NAME (OVL_CURRENT (CLASSTYPE_CONSTRUCTORS (type)));
1170   else
1171     return TYPE_IDENTIFIER (type);
1172 }
1173
1174 /* Return the name for the constructor (or destructor) for the
1175    specified class.  When given a template, return the plain
1176    unspecialized name.  */
1177
1178 tree
1179 constructor_name (tree type)
1180 {
1181   tree name;
1182   name = constructor_name_full (type);
1183   if (IDENTIFIER_TEMPLATE (name))
1184     name = IDENTIFIER_TEMPLATE (name);
1185   return name;
1186 }
1187
1188 /* Returns TRUE if NAME is the name for the constructor for TYPE.  */
1189
1190 bool
1191 constructor_name_p (tree name, tree type)
1192 {
1193   tree ctor_name;
1194
1195   if (!name)
1196     return false;
1197   
1198   if (TREE_CODE (name) != IDENTIFIER_NODE)
1199     return false;
1200   
1201   ctor_name = constructor_name_full (type);
1202   if (name == ctor_name)
1203     return true;
1204   if (IDENTIFIER_TEMPLATE (ctor_name)
1205       && name == IDENTIFIER_TEMPLATE (ctor_name))
1206     return true;
1207   return false;
1208 }
1209
1210 \f
1211 /* Defer the compilation of the FN until the end of compilation.  */
1212
1213 void
1214 defer_fn (tree fn)
1215 {
1216   if (DECL_DEFERRED_FN (fn))
1217     return;
1218   DECL_DEFERRED_FN (fn) = 1;
1219   DECL_DEFER_OUTPUT (fn) = 1;
1220   if (!deferred_fns)
1221     VARRAY_TREE_INIT (deferred_fns, 32, "deferred_fns");
1222
1223   VARRAY_PUSH_TREE (deferred_fns, fn);
1224 }
1225
1226 /* Walks through the namespace- or function-scope anonymous union OBJECT,
1227    building appropriate ALIAS_DECLs.  Returns one of the fields for use in
1228    the mangled name.  */
1229
1230 static tree
1231 build_anon_union_vars (tree object)
1232 {
1233   tree type = TREE_TYPE (object);
1234   tree main_decl = NULL_TREE;
1235   tree field;
1236
1237   /* Rather than write the code to handle the non-union case,
1238      just give an error.  */
1239   if (TREE_CODE (type) != UNION_TYPE)
1240     error ("anonymous struct not inside named type");
1241
1242   for (field = TYPE_FIELDS (type); 
1243        field != NULL_TREE; 
1244        field = TREE_CHAIN (field))
1245     {
1246       tree decl;
1247       tree ref;
1248
1249       if (DECL_ARTIFICIAL (field))
1250         continue;
1251       if (TREE_CODE (field) != FIELD_DECL)
1252         {
1253           cp_pedwarn_at ("\
1254 `%#D' invalid; an anonymous union can only have non-static data members",
1255                          field);
1256           continue;
1257         }
1258
1259       if (TREE_PRIVATE (field))
1260         cp_pedwarn_at ("private member `%#D' in anonymous union", field);
1261       else if (TREE_PROTECTED (field))
1262         cp_pedwarn_at ("protected member `%#D' in anonymous union", field);
1263
1264       if (processing_template_decl)
1265         ref = build_min_nt (COMPONENT_REF, object, DECL_NAME (field));
1266       else
1267         ref = build_class_member_access_expr (object, field, NULL_TREE,
1268                                               false);
1269
1270       if (DECL_NAME (field))
1271         {
1272           decl = build_decl (ALIAS_DECL, DECL_NAME (field), TREE_TYPE (field));
1273           DECL_INITIAL (decl) = ref;        
1274           TREE_PUBLIC (decl) = 0;
1275           TREE_STATIC (decl) = 0;
1276           DECL_EXTERNAL (decl) = 1;
1277           decl = pushdecl (decl);
1278         }
1279       else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1280         decl = build_anon_union_vars (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 = TREE_TYPE (anon_union_decl);
1299   tree main_decl;
1300   bool public_p = TREE_PUBLIC (anon_union_decl);
1301
1302   /* The VAR_DECL's context is the same as the TYPE's context.  */
1303   DECL_CONTEXT (anon_union_decl) = DECL_CONTEXT (TYPE_NAME (type));
1304   
1305   if (TYPE_FIELDS (type) == NULL_TREE)
1306     return;
1307
1308   if (public_p)
1309     {
1310       error ("namespace-scope anonymous aggregates must be static");
1311       return;
1312     }
1313
1314   main_decl = build_anon_union_vars (anon_union_decl);
1315   if (main_decl == NULL_TREE)
1316     {
1317       warning ("anonymous union with no members");
1318       return;
1319     }
1320
1321   if (!processing_template_decl)
1322     {
1323       /* Use main_decl to set the mangled name.  */
1324       DECL_NAME (anon_union_decl) = DECL_NAME (main_decl);
1325       mangle_decl (anon_union_decl);
1326       DECL_NAME (anon_union_decl) = NULL_TREE;
1327     }
1328
1329   pushdecl (anon_union_decl);
1330   if (building_stmt_tree ()
1331       && at_function_scope_p ())
1332     add_decl_stmt (anon_union_decl);
1333   else if (!processing_template_decl)
1334     rest_of_decl_compilation (anon_union_decl, NULL,
1335                               toplevel_bindings_p (), at_eof);
1336 }
1337 \f
1338 /* Auxiliary functions to make type signatures for
1339    `operator new' and `operator delete' correspond to
1340    what compiler will be expecting.  */
1341
1342 tree
1343 coerce_new_type (tree type)
1344 {
1345   int e = 0;
1346   tree args = TYPE_ARG_TYPES (type);
1347
1348   my_friendly_assert (TREE_CODE (type) == FUNCTION_TYPE, 20001107);
1349   
1350   if (!same_type_p (TREE_TYPE (type), ptr_type_node))
1351     e = 1, error ("`operator new' must return type `%T'", ptr_type_node);
1352
1353   if (!args || args == void_list_node
1354       || !same_type_p (TREE_VALUE (args), size_type_node))
1355     {
1356       e = 2;
1357       if (args && args != void_list_node)
1358         args = TREE_CHAIN (args);
1359       pedwarn ("`operator new' takes type `size_t' (`%T') as first parameter", size_type_node);
1360     }
1361   switch (e)
1362   {
1363     case 2:
1364       args = tree_cons (NULL_TREE, size_type_node, args);
1365       /* FALLTHROUGH */
1366     case 1:
1367       type = build_exception_variant
1368               (build_function_type (ptr_type_node, args),
1369                TYPE_RAISES_EXCEPTIONS (type));
1370       /* FALLTHROUGH */
1371     default:;
1372   }
1373   return type;
1374 }
1375
1376 tree
1377 coerce_delete_type (tree type)
1378 {
1379   int e = 0;
1380   tree args = TYPE_ARG_TYPES (type);
1381   
1382   my_friendly_assert (TREE_CODE (type) == FUNCTION_TYPE, 20001107);
1383
1384   if (!same_type_p (TREE_TYPE (type), void_type_node))
1385     e = 1, error ("`operator delete' must return type `%T'", void_type_node);
1386
1387   if (!args || args == void_list_node
1388       || !same_type_p (TREE_VALUE (args), ptr_type_node))
1389     {
1390       e = 2;
1391       if (args && args != void_list_node)
1392         args = TREE_CHAIN (args);
1393       error ("`operator delete' takes type `%T' as first parameter", ptr_type_node);
1394     }
1395   switch (e)
1396   {
1397     case 2:
1398       args = tree_cons (NULL_TREE, ptr_type_node, args);
1399       /* FALLTHROUGH */
1400     case 1:
1401       type = build_exception_variant
1402               (build_function_type (void_type_node, args),
1403                TYPE_RAISES_EXCEPTIONS (type));
1404       /* FALLTHROUGH */
1405     default:;
1406   }
1407
1408   return type;
1409 }
1410 \f
1411 static void
1412 mark_vtable_entries (tree decl)
1413 {
1414   tree entries = CONSTRUCTOR_ELTS (DECL_INITIAL (decl));
1415
1416   for (; entries; entries = TREE_CHAIN (entries))
1417     {
1418       tree fnaddr = TREE_VALUE (entries);
1419       tree fn;
1420
1421       STRIP_NOPS (fnaddr);
1422
1423       if (TREE_CODE (fnaddr) != ADDR_EXPR
1424           && TREE_CODE (fnaddr) != FDESC_EXPR)
1425         /* This entry is an offset: a virtual base class offset, a
1426            virtual call offset, an RTTI offset, etc.  */
1427         continue;
1428
1429       fn = TREE_OPERAND (fnaddr, 0);
1430       TREE_ADDRESSABLE (fn) = 1;
1431       /* When we don't have vcall offsets, we output thunks whenever
1432          we output the vtables that contain them.  With vcall offsets,
1433          we know all the thunks we'll need when we emit a virtual
1434          function, so we emit the thunks there instead.  */
1435       if (DECL_THUNK_P (fn)) 
1436         use_thunk (fn, /*emit_p=*/0);
1437       mark_used (fn);
1438     }
1439 }
1440
1441 /* Set DECL up to have the closest approximation of "initialized common"
1442    linkage available.  */
1443
1444 void
1445 comdat_linkage (tree decl)
1446 {
1447   if (flag_weak)
1448     make_decl_one_only (decl);
1449   else if (TREE_CODE (decl) == FUNCTION_DECL 
1450            || (TREE_CODE (decl) == VAR_DECL && DECL_ARTIFICIAL (decl)))
1451     /* We can just emit function and compiler-generated variables
1452        statically; having multiple copies is (for the most part) only
1453        a waste of space.  
1454
1455        There are two correctness issues, however: the address of a
1456        template instantiation with external linkage should be the
1457        same, independent of what translation unit asks for the
1458        address, and this will not hold when we emit multiple copies of
1459        the function.  However, there's little else we can do.  
1460
1461        Also, by default, the typeinfo implementation assumes that
1462        there will be only one copy of the string used as the name for
1463        each type.  Therefore, if weak symbols are unavailable, the
1464        run-time library should perform a more conservative check; it
1465        should perform a string comparison, rather than an address
1466        comparison.  */
1467     TREE_PUBLIC (decl) = 0;
1468   else
1469     {
1470       /* Static data member template instantiations, however, cannot
1471          have multiple copies.  */
1472       if (DECL_INITIAL (decl) == 0
1473           || DECL_INITIAL (decl) == error_mark_node)
1474         DECL_COMMON (decl) = 1;
1475       else if (EMPTY_CONSTRUCTOR_P (DECL_INITIAL (decl)))
1476         {
1477           DECL_COMMON (decl) = 1;
1478           DECL_INITIAL (decl) = error_mark_node;
1479         }
1480       else if (!DECL_EXPLICIT_INSTANTIATION (decl))
1481         {
1482           /* We can't do anything useful; leave vars for explicit
1483              instantiation.  */
1484           DECL_EXTERNAL (decl) = 1;
1485           DECL_NOT_REALLY_EXTERN (decl) = 0;
1486         }
1487     }
1488
1489   if (DECL_LANG_SPECIFIC (decl))
1490     DECL_COMDAT (decl) = 1;
1491 }
1492
1493 /* For win32 we also want to put explicit instantiations in
1494    linkonce sections, so that they will be merged with implicit
1495    instantiations; otherwise we get duplicate symbol errors.  */
1496
1497 void
1498 maybe_make_one_only (tree decl)
1499 {
1500   /* We used to say that this was not necessary on targets that support weak
1501      symbols, because the implicit instantiations will defer to the explicit
1502      one.  However, that's not actually the case in SVR4; a strong definition
1503      after a weak one is an error.  Also, not making explicit
1504      instantiations one_only means that we can end up with two copies of
1505      some template instantiations.  */
1506   if (! flag_weak)
1507     return;
1508
1509   /* We can't set DECL_COMDAT on functions, or finish_file will think
1510      we can get away with not emitting them if they aren't used.  We need
1511      to for variables so that cp_finish_decl will update their linkage,
1512      because their DECL_INITIAL may not have been set properly yet.  */
1513
1514   make_decl_one_only (decl);
1515
1516   if (TREE_CODE (decl) == VAR_DECL)
1517     {
1518       DECL_COMDAT (decl) = 1;
1519       /* Mark it needed so we don't forget to emit it.  */
1520       TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)) = 1;
1521     }
1522 }
1523
1524 /* Set TREE_PUBLIC and/or DECL_EXTERN on the vtable DECL,
1525    based on TYPE and other static flags.
1526
1527    Note that anything public is tagged TREE_PUBLIC, whether
1528    it's public in this file or in another one.  */
1529
1530 void
1531 import_export_vtable (tree decl, tree type, int final)
1532 {
1533   if (DECL_INTERFACE_KNOWN (decl))
1534     return;
1535
1536   if (TYPE_FOR_JAVA (type))
1537     {
1538       TREE_PUBLIC (decl) = 1;
1539       DECL_EXTERNAL (decl) = 1;
1540       DECL_INTERFACE_KNOWN (decl) = 1;
1541     }
1542   else if (CLASSTYPE_INTERFACE_KNOWN (type))
1543     {
1544       TREE_PUBLIC (decl) = 1;
1545       DECL_EXTERNAL (decl) = CLASSTYPE_INTERFACE_ONLY (type);
1546       DECL_INTERFACE_KNOWN (decl) = 1;
1547     }
1548   else
1549     {
1550       /* We can only wait to decide if we have real non-inline virtual
1551          functions in our class, or if we come from a template.  */
1552
1553       int found = (CLASSTYPE_TEMPLATE_INSTANTIATION (type)
1554                    || CLASSTYPE_KEY_METHOD (type) != NULL_TREE);
1555
1556       if (final || ! found)
1557         {
1558           comdat_linkage (decl);
1559           DECL_EXTERNAL (decl) = 0;
1560         }
1561       else
1562         {
1563           TREE_PUBLIC (decl) = 1;
1564           DECL_EXTERNAL (decl) = 1;
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   my_friendly_assert (at_eof, 20000226);
1584
1585   if (CLASSTYPE_INTERFACE_KNOWN (ctype))
1586     return;
1587
1588   /* If MULTIPLE_SYMBOL_SPACES is defined 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
1601   /* If we got -fno-implicit-templates, we import template classes that
1602      weren't explicitly instantiated.  */
1603   if (import_export == 0
1604       && CLASSTYPE_IMPLICIT_INSTANTIATION (ctype)
1605       && ! flag_implicit_templates)
1606     import_export = -1;
1607
1608   /* Base our import/export status on that of the first non-inline,
1609      non-pure virtual function, if any.  */
1610   if (import_export == 0
1611       && TYPE_POLYMORPHIC_P (ctype))
1612     {
1613       tree method = CLASSTYPE_KEY_METHOD (ctype);
1614       if (method)
1615         import_export = (DECL_REALLY_EXTERN (method) ? -1 : 1);
1616     }
1617
1618 #ifdef MULTIPLE_SYMBOL_SPACES
1619   if (import_export == -1)
1620     import_export = 0;
1621 #endif
1622
1623   if (import_export)
1624     {
1625       SET_CLASSTYPE_INTERFACE_KNOWN (ctype);
1626       CLASSTYPE_INTERFACE_ONLY (ctype) = (import_export < 0);
1627     }
1628 }
1629     
1630 /* We need to describe to the assembler the relationship between
1631    a vtable and the vtable of the parent class.  */
1632
1633 void
1634 prepare_assemble_variable (tree vars)
1635 {
1636   tree parent;
1637   rtx child_rtx, parent_rtx;
1638
1639   if (!flag_vtable_gc || TREE_CODE (vars) != VAR_DECL
1640       || !DECL_VTABLE_OR_VTT_P (vars))
1641     return;
1642
1643   child_rtx = XEXP (DECL_RTL (vars), 0);          /* strip the mem ref  */
1644
1645   parent = binfo_for_vtable (vars);
1646
1647   if (parent == TYPE_BINFO (DECL_CONTEXT (vars)))
1648     parent_rtx = const0_rtx;
1649   else if (parent)
1650     {
1651       parent = get_vtbl_decl_for_binfo (TYPE_BINFO (BINFO_TYPE (parent)));
1652       parent_rtx = XEXP (DECL_RTL (parent), 0);  /* strip the mem ref  */
1653     }
1654   else
1655     abort ();
1656
1657   assemble_vtable_inherit (child_rtx, parent_rtx);
1658 }
1659
1660 /* If necessary, write out the vtables for the dynamic class CTYPE.
1661    Returns true if any vtables were emitted.  */
1662
1663 static bool
1664 maybe_emit_vtables (tree ctype)
1665 {
1666   tree vtbl;
1667   tree primary_vtbl;
1668   bool needed = false;
1669
1670   /* If the vtables for this class have already been emitted there is
1671      nothing more to do.  */
1672   primary_vtbl = CLASSTYPE_VTABLES (ctype);
1673   if (TREE_ASM_WRITTEN (primary_vtbl))
1674     return false;
1675   /* Ignore dummy vtables made by get_vtable_decl.  */
1676   if (TREE_TYPE (primary_vtbl) == void_type_node)
1677     return false;
1678
1679   import_export_class (ctype);
1680   import_export_vtable (primary_vtbl, ctype, 1);
1681
1682   /* See if any of the vtables are needed.  */
1683   for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = TREE_CHAIN (vtbl))
1684     if (!DECL_EXTERNAL (vtbl) && DECL_NEEDED_P (vtbl))
1685       break;
1686   if (!vtbl)
1687     {
1688       /* If the references to this class' vtables are optimized away,
1689          still emit the appropriate debugging information.  See
1690          dfs_debug_mark.  */
1691       if (DECL_COMDAT (primary_vtbl) 
1692           && CLASSTYPE_DEBUG_REQUESTED (ctype))
1693         note_debug_info_needed (ctype);
1694       return false;
1695     }
1696   else if (TREE_PUBLIC (vtbl) && !DECL_COMDAT (vtbl))
1697     needed = true;
1698   
1699
1700   /* The ABI requires that we emit all of the vtables if we emit any
1701      of them.  */
1702   for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = TREE_CHAIN (vtbl))
1703     {
1704       /* Write it out.  */
1705       import_export_vtable (vtbl, ctype, 1);
1706       mark_vtable_entries (vtbl);
1707
1708       /* If we know that DECL is needed, mark it as such for the varpool.  */
1709       if (needed)
1710         cgraph_varpool_mark_needed_node (cgraph_varpool_node (vtbl));
1711
1712       if (TREE_TYPE (DECL_INITIAL (vtbl)) == 0)
1713         store_init_value (vtbl, DECL_INITIAL (vtbl));
1714
1715       if (write_symbols == DWARF_DEBUG || write_symbols == DWARF2_DEBUG)
1716         {
1717           /* Mark the VAR_DECL node representing the vtable itself as a
1718              "gratuitous" one, thereby forcing dwarfout.c to ignore it.
1719              It is rather important that such things be ignored because
1720              any effort to actually generate DWARF for them will run
1721              into trouble when/if we encounter code like:
1722
1723                 #pragma interface
1724                 struct S { virtual void member (); };
1725
1726               because the artificial declaration of the vtable itself (as
1727               manufactured by the g++ front end) will say that the vtable
1728               is a static member of `S' but only *after* the debug output
1729               for the definition of `S' has already been output.  This causes
1730               grief because the DWARF entry for the definition of the vtable
1731               will try to refer back to an earlier *declaration* of the
1732               vtable as a static member of `S' and there won't be one.
1733               We might be able to arrange to have the "vtable static member"
1734               attached to the member list for `S' before the debug info for
1735               `S' get written (which would solve the problem) but that would
1736               require more intrusive changes to the g++ front end.  */
1737
1738           DECL_IGNORED_P (vtbl) = 1;
1739         }
1740
1741       /* Always make vtables weak.  */
1742       if (flag_weak)
1743         comdat_linkage (vtbl);
1744
1745       rest_of_decl_compilation (vtbl, NULL, 1, 1);
1746
1747       /* Because we're only doing syntax-checking, we'll never end up
1748          actually marking the variable as written.  */
1749       if (flag_syntax_only)
1750         TREE_ASM_WRITTEN (vtbl) = 1;
1751     }
1752
1753   /* Since we're writing out the vtable here, also write the debug
1754      info.  */
1755   note_debug_info_needed (ctype);
1756
1757   return true;
1758 }
1759
1760 /* Determines the proper settings of TREE_PUBLIC and DECL_EXTERNAL for an
1761    inline function or template instantiation at end-of-file.  */
1762
1763 void
1764 import_export_decl (tree decl)
1765 {
1766   if (DECL_INTERFACE_KNOWN (decl))
1767     return;
1768
1769   if (DECL_TEMPLATE_INSTANTIATION (decl)
1770       || DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl))
1771     {
1772       DECL_NOT_REALLY_EXTERN (decl) = 1;
1773       if ((DECL_IMPLICIT_INSTANTIATION (decl)
1774            || DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl))
1775           && (flag_implicit_templates
1776               || (flag_implicit_inline_templates 
1777                   && DECL_DECLARED_INLINE_P (decl))))
1778         {
1779           if (!TREE_PUBLIC (decl))
1780             /* Templates are allowed to have internal linkage.  See 
1781                [basic.link].  */
1782             ;
1783           else
1784             comdat_linkage (decl);
1785         }
1786       else
1787         {
1788           DECL_EXTERNAL (decl) = 1;
1789           DECL_NOT_REALLY_EXTERN (decl) = 0;
1790         }
1791     }
1792   else if (DECL_FUNCTION_MEMBER_P (decl))
1793     {
1794       if (!DECL_DECLARED_INLINE_P (decl))
1795         {
1796           tree ctype = DECL_CONTEXT (decl);
1797           import_export_class (ctype);
1798           if (CLASSTYPE_INTERFACE_KNOWN (ctype))
1799             {
1800               DECL_NOT_REALLY_EXTERN (decl)
1801                 = ! (CLASSTYPE_INTERFACE_ONLY (ctype)
1802                      || (DECL_DECLARED_INLINE_P (decl) 
1803                          && ! flag_implement_inlines
1804                          && !DECL_VINDEX (decl)));
1805
1806               if (!DECL_NOT_REALLY_EXTERN (decl))
1807                 DECL_EXTERNAL (decl) = 1;
1808
1809               /* Always make artificials weak.  */
1810               if (DECL_ARTIFICIAL (decl) && flag_weak)
1811                 comdat_linkage (decl);
1812               else
1813                 maybe_make_one_only (decl);
1814             }
1815         }
1816       else
1817         comdat_linkage (decl);
1818     }
1819   else
1820     comdat_linkage (decl);
1821
1822   DECL_INTERFACE_KNOWN (decl) = 1;
1823 }
1824
1825 /* Here, we only decide whether or not the tinfo node should be
1826    emitted with the vtable.  IS_IN_LIBRARY is nonzero iff the
1827    typeinfo for TYPE should be in the runtime library.  */
1828
1829 void
1830 import_export_tinfo (tree decl, tree type, bool is_in_library)
1831 {
1832   if (DECL_INTERFACE_KNOWN (decl))
1833     return;
1834   
1835   if (IS_AGGR_TYPE (type))
1836     import_export_class (type);
1837       
1838   if (IS_AGGR_TYPE (type) && CLASSTYPE_INTERFACE_KNOWN (type)
1839       && TYPE_POLYMORPHIC_P (type)
1840       /* If -fno-rtti, we're not necessarily emitting this stuff with
1841          the class, so go ahead and emit it now.  This can happen when
1842          a class is used in exception handling.  */
1843       && flag_rtti)
1844     {
1845       DECL_NOT_REALLY_EXTERN (decl) = !CLASSTYPE_INTERFACE_ONLY (type);
1846       DECL_COMDAT (decl) = 0;
1847     }
1848   else
1849     {
1850       DECL_NOT_REALLY_EXTERN (decl) = 1;
1851       DECL_COMDAT (decl) = 1;
1852     }
1853
1854   /* Now override some cases.  */
1855   if (flag_weak)
1856     DECL_COMDAT (decl) = 1;
1857   else if (is_in_library)
1858     DECL_COMDAT (decl) = 0;
1859   
1860   DECL_INTERFACE_KNOWN (decl) = 1;
1861 }
1862
1863 /* Return an expression that performs the destruction of DECL, which
1864    must be a VAR_DECL whose type has a non-trivial destructor, or is
1865    an array whose (innermost) elements have a non-trivial destructor.  */
1866
1867 tree
1868 build_cleanup (tree decl)
1869 {
1870   tree temp;
1871   tree type = TREE_TYPE (decl);
1872
1873   /* This function should only be called for declarations that really
1874      require cleanups.  */
1875   my_friendly_assert (!TYPE_HAS_TRIVIAL_DESTRUCTOR (type), 20030106);
1876
1877   /* Treat all objects with destructors as used; the destructor may do
1878      something substantive.  */
1879   mark_used (decl);
1880
1881   if (TREE_CODE (type) == ARRAY_TYPE)
1882     temp = decl;
1883   else
1884     {
1885       cxx_mark_addressable (decl);
1886       temp = build1 (ADDR_EXPR, build_pointer_type (type), decl);
1887     }
1888   temp = build_delete (TREE_TYPE (temp), temp,
1889                        sfk_complete_destructor,
1890                        LOOKUP_NORMAL|LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR, 0);
1891   return temp;
1892 }
1893
1894 /* Returns the initialization guard variable for the variable DECL,
1895    which has static storage duration.  */
1896
1897 tree
1898 get_guard (tree decl)
1899 {
1900   tree sname;
1901   tree guard;
1902
1903   sname = mangle_guard_variable (decl);
1904   guard = IDENTIFIER_GLOBAL_VALUE (sname);
1905   if (! guard)
1906     {
1907       tree guard_type;
1908
1909       /* We use a type that is big enough to contain a mutex as well
1910          as an integer counter.  */
1911       guard_type = long_long_integer_type_node;
1912       guard = build_decl (VAR_DECL, sname, guard_type);
1913       
1914       /* The guard should have the same linkage as what it guards.  */
1915       TREE_PUBLIC (guard) = TREE_PUBLIC (decl);
1916       TREE_STATIC (guard) = TREE_STATIC (decl);
1917       DECL_COMMON (guard) = DECL_COMMON (decl);
1918       DECL_ONE_ONLY (guard) = DECL_ONE_ONLY (decl);
1919       if (TREE_PUBLIC (decl))
1920         DECL_WEAK (guard) = DECL_WEAK (decl);
1921       
1922       DECL_ARTIFICIAL (guard) = 1;
1923       TREE_USED (guard) = 1;
1924       pushdecl_top_level_and_finish (guard, NULL_TREE);
1925     }
1926   return guard;
1927 }
1928
1929 /* Return those bits of the GUARD variable that should be set when the
1930    guarded entity is actually initialized.  */
1931
1932 static tree
1933 get_guard_bits (tree guard)
1934 {
1935   /* We only set the first byte of the guard, in order to leave room
1936      for a mutex in the high-order bits.  */
1937   guard = build1 (ADDR_EXPR, 
1938                   build_pointer_type (TREE_TYPE (guard)),
1939                   guard);
1940   guard = build1 (NOP_EXPR, 
1941                   build_pointer_type (char_type_node), 
1942                   guard);
1943   guard = build1 (INDIRECT_REF, char_type_node, guard);
1944
1945   return guard;
1946 }
1947
1948 /* Return an expression which determines whether or not the GUARD
1949    variable has already been initialized.  */
1950
1951 tree
1952 get_guard_cond (tree guard)
1953 {
1954   tree guard_value;
1955
1956   /* Check to see if the GUARD is zero.  */
1957   guard = get_guard_bits (guard);
1958   guard_value = integer_zero_node;
1959   if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
1960     guard_value = convert (TREE_TYPE (guard), guard_value);
1961   return cp_build_binary_op (EQ_EXPR, guard, guard_value);
1962 }
1963
1964 /* Return an expression which sets the GUARD variable, indicating that
1965    the variable being guarded has been initialized.  */
1966
1967 tree
1968 set_guard (tree guard)
1969 {
1970   tree guard_init;
1971
1972   /* Set the GUARD to one.  */
1973   guard = get_guard_bits (guard);
1974   guard_init = integer_one_node;
1975   if (!same_type_p (TREE_TYPE (guard_init), TREE_TYPE (guard)))
1976     guard_init = convert (TREE_TYPE (guard), guard_init);
1977   return build_modify_expr (guard, NOP_EXPR, guard_init);
1978 }
1979
1980 /* Start the process of running a particular set of global constructors
1981    or destructors.  Subroutine of do_[cd]tors.  */
1982
1983 static tree
1984 start_objects (int method_type, int initp)
1985 {
1986   tree fnname;
1987   tree body;
1988   char type[10];
1989
1990   /* Make ctor or dtor function.  METHOD_TYPE may be 'I' or 'D'.  */
1991
1992   if (initp != DEFAULT_INIT_PRIORITY)
1993     {
1994       char joiner;
1995
1996 #ifdef JOINER
1997       joiner = JOINER;
1998 #else
1999       joiner = '_';
2000 #endif
2001
2002       sprintf (type, "%c%c%.5u", method_type, joiner, initp);
2003     }
2004   else
2005     sprintf (type, "%c", method_type);
2006
2007   fnname = get_file_function_name_long (type);
2008
2009   start_function (void_list_node,
2010                   make_call_declarator (fnname, void_list_node, NULL_TREE,
2011                                         NULL_TREE),
2012                   NULL_TREE, SF_DEFAULT);
2013
2014   /* It can be a static function as long as collect2 does not have
2015      to scan the object file to find its ctor/dtor routine.  */
2016   TREE_PUBLIC (current_function_decl) = ! targetm.have_ctors_dtors;
2017
2018   /* Mark this declaration as used to avoid spurious warnings.  */
2019   TREE_USED (current_function_decl) = 1;
2020
2021   /* Mark this function as a global constructor or destructor.  */
2022   if (method_type == 'I')
2023     DECL_GLOBAL_CTOR_P (current_function_decl) = 1;
2024   else
2025     DECL_GLOBAL_DTOR_P (current_function_decl) = 1;
2026   DECL_LANG_SPECIFIC (current_function_decl)->decl_flags.u2sel = 1;
2027
2028   body = begin_compound_stmt (/*has_no_scope=*/false);
2029
2030   /* We cannot allow these functions to be elided, even if they do not
2031      have external linkage.  And, there's no point in deferring
2032      compilation of thes functions; they're all going to have to be
2033      out anyhow.  */
2034   current_function_cannot_inline
2035     = "static constructors and destructors cannot be inlined";
2036
2037   return body;
2038 }
2039
2040 /* Finish the process of running a particular set of global constructors
2041    or destructors.  Subroutine of do_[cd]tors.  */
2042
2043 static void
2044 finish_objects (int method_type, int initp, tree body)
2045 {
2046   tree fn;
2047
2048   /* Finish up.  */
2049   finish_compound_stmt (body);
2050   fn = finish_function (0);
2051   expand_or_defer_fn (fn);
2052
2053   /* When only doing semantic analysis, and no RTL generation, we
2054      can't call functions that directly emit assembly code; there is
2055      no assembly file in which to put the code.  */
2056   if (flag_syntax_only)
2057     return;
2058
2059   if (targetm.have_ctors_dtors)
2060     {
2061       rtx fnsym = XEXP (DECL_RTL (fn), 0);
2062       if (method_type == 'I')
2063         (* targetm.asm_out.constructor) (fnsym, initp);
2064       else
2065         (* targetm.asm_out.destructor) (fnsym, initp);
2066     }
2067 }
2068
2069 /* The names of the parameters to the function created to handle
2070    initializations and destructions for objects with static storage
2071    duration.  */
2072 #define INITIALIZE_P_IDENTIFIER "__initialize_p"
2073 #define PRIORITY_IDENTIFIER "__priority"
2074
2075 /* The name of the function we create to handle initializations and
2076    destructions for objects with static storage duration.  */
2077 #define SSDF_IDENTIFIER "__static_initialization_and_destruction"
2078
2079 /* The declaration for the __INITIALIZE_P argument.  */
2080 static GTY(()) tree initialize_p_decl;
2081
2082 /* The declaration for the __PRIORITY argument.  */
2083 static GTY(()) tree priority_decl;
2084
2085 /* The declaration for the static storage duration function.  */
2086 static GTY(()) tree ssdf_decl;
2087
2088 /* All the static storage duration functions created in this
2089    translation unit.  */
2090 static GTY(()) varray_type ssdf_decls;
2091
2092 /* A map from priority levels to information about that priority
2093    level.  There may be many such levels, so efficient lookup is
2094    important.  */
2095 static splay_tree priority_info_map;
2096
2097 /* Begins the generation of the function that will handle all
2098    initialization and destruction of objects with static storage
2099    duration.  The function generated takes two parameters of type
2100    `int': __INITIALIZE_P and __PRIORITY.  If __INITIALIZE_P is
2101    nonzero, it performs initializations.  Otherwise, it performs
2102    destructions.  It only performs those initializations or
2103    destructions with the indicated __PRIORITY.  The generated function
2104    returns no value.  
2105
2106    It is assumed that this function will only be called once per
2107    translation unit.  */
2108
2109 static tree
2110 start_static_storage_duration_function (unsigned count)
2111 {
2112   tree parm_types;
2113   tree type;
2114   tree body;
2115   char id[sizeof (SSDF_IDENTIFIER) + 1 /* '\0' */ + 32];
2116
2117   /* Create the identifier for this function.  It will be of the form
2118      SSDF_IDENTIFIER_<number>.  */
2119   sprintf (id, "%s_%u", SSDF_IDENTIFIER, count);
2120
2121   /* Create the parameters.  */
2122   parm_types = void_list_node;
2123   parm_types = tree_cons (NULL_TREE, integer_type_node, parm_types);
2124   parm_types = tree_cons (NULL_TREE, integer_type_node, parm_types);
2125   type = build_function_type (void_type_node, parm_types);
2126
2127   /* Create the FUNCTION_DECL itself.  */
2128   ssdf_decl = build_lang_decl (FUNCTION_DECL, 
2129                                get_identifier (id),
2130                                type);
2131   TREE_PUBLIC (ssdf_decl) = 0;
2132   DECL_ARTIFICIAL (ssdf_decl) = 1;
2133
2134   /* Put this function in the list of functions to be called from the
2135      static constructors and destructors.  */
2136   if (!ssdf_decls)
2137     {
2138       VARRAY_TREE_INIT (ssdf_decls, 32, "ssdf_decls");
2139
2140       /* Take this opportunity to initialize the map from priority
2141          numbers to information about that priority level.  */
2142       priority_info_map = splay_tree_new (splay_tree_compare_ints,
2143                                           /*delete_key_fn=*/0,
2144                                           /*delete_value_fn=*/
2145                                           (splay_tree_delete_value_fn) &free);
2146
2147       /* We always need to generate functions for the
2148          DEFAULT_INIT_PRIORITY so enter it now.  That way when we walk
2149          priorities later, we'll be sure to find the
2150          DEFAULT_INIT_PRIORITY.  */
2151       get_priority_info (DEFAULT_INIT_PRIORITY);
2152     }
2153
2154   VARRAY_PUSH_TREE (ssdf_decls, ssdf_decl);
2155
2156   /* Create the argument list.  */
2157   initialize_p_decl = cp_build_parm_decl
2158     (get_identifier (INITIALIZE_P_IDENTIFIER), integer_type_node);
2159   DECL_CONTEXT (initialize_p_decl) = ssdf_decl;
2160   TREE_USED (initialize_p_decl) = 1;
2161   priority_decl = cp_build_parm_decl
2162     (get_identifier (PRIORITY_IDENTIFIER), integer_type_node);
2163   DECL_CONTEXT (priority_decl) = ssdf_decl;
2164   TREE_USED (priority_decl) = 1;
2165
2166   TREE_CHAIN (initialize_p_decl) = priority_decl;
2167   DECL_ARGUMENTS (ssdf_decl) = initialize_p_decl;
2168
2169   /* Put the function in the global scope.  */
2170   pushdecl (ssdf_decl);
2171
2172   /* Start the function itself.  This is equivalent to declarating the
2173      function as:
2174
2175        static void __ssdf (int __initialize_p, init __priority_p);
2176        
2177      It is static because we only need to call this function from the
2178      various constructor and destructor functions for this module.  */
2179   start_function (/*specs=*/NULL_TREE, 
2180                   ssdf_decl,
2181                   /*attrs=*/NULL_TREE,
2182                   SF_PRE_PARSED);
2183
2184   /* Set up the scope of the outermost block in the function.  */
2185   body = begin_compound_stmt (/*has_no_scope=*/false);
2186
2187   /* This function must not be deferred because we are depending on
2188      its compilation to tell us what is TREE_SYMBOL_REFERENCED.  */
2189   current_function_cannot_inline 
2190     = "static storage duration functions cannot be inlined";
2191
2192   return body;
2193 }
2194
2195 /* Finish the generation of the function which performs initialization
2196    and destruction of objects with static storage duration.  After
2197    this point, no more such objects can be created.  */
2198
2199 static void
2200 finish_static_storage_duration_function (tree body)
2201 {
2202   /* Close out the function.  */
2203   finish_compound_stmt (body);
2204   expand_or_defer_fn (finish_function (0));
2205 }
2206
2207 /* Return the information about the indicated PRIORITY level.  If no
2208    code to handle this level has yet been generated, generate the
2209    appropriate prologue.  */
2210
2211 static priority_info
2212 get_priority_info (int priority)
2213 {
2214   priority_info pi;
2215   splay_tree_node n;
2216
2217   n = splay_tree_lookup (priority_info_map, 
2218                          (splay_tree_key) priority);
2219   if (!n)
2220     {
2221       /* Create a new priority information structure, and insert it
2222          into the map.  */
2223       pi = xmalloc (sizeof (struct priority_info_s));
2224       pi->initializations_p = 0;
2225       pi->destructions_p = 0;
2226       splay_tree_insert (priority_info_map,
2227                          (splay_tree_key) priority,
2228                          (splay_tree_value) pi);
2229     }
2230   else
2231     pi = (priority_info) n->value;
2232
2233   return pi;
2234 }
2235
2236 /* Set up to handle the initialization or destruction of DECL.  If
2237    INITP is nonzero, we are initializing the variable.  Otherwise, we
2238    are destroying it.  */
2239
2240 static tree
2241 start_static_initialization_or_destruction (tree decl, int initp)
2242 {
2243   tree guard_if_stmt = NULL_TREE;
2244   int priority;
2245   tree cond;
2246   tree guard;
2247   tree init_cond;
2248   priority_info pi;
2249
2250   /* Figure out the priority for this declaration.  */
2251   priority = DECL_INIT_PRIORITY (decl);
2252   if (!priority)
2253     priority = DEFAULT_INIT_PRIORITY;
2254
2255   /* Remember that we had an initialization or finalization at this
2256      priority.  */
2257   pi = get_priority_info (priority);
2258   if (initp)
2259     pi->initializations_p = 1;
2260   else
2261     pi->destructions_p = 1;
2262
2263   /* Trick the compiler into thinking we are at the file and line
2264      where DECL was declared so that error-messages make sense, and so
2265      that the debugger will show somewhat sensible file and line
2266      information.  */
2267   input_location = DECL_SOURCE_LOCATION (decl);
2268
2269   /* Because of:
2270
2271        [class.access.spec]
2272
2273        Access control for implicit calls to the constructors,
2274        the conversion functions, or the destructor called to
2275        create and destroy a static data member is performed as
2276        if these calls appeared in the scope of the member's
2277        class.  
2278
2279      we pretend we are in a static member function of the class of
2280      which the DECL is a member.  */
2281   if (member_p (decl))
2282     {
2283       DECL_CONTEXT (current_function_decl) = DECL_CONTEXT (decl);
2284       DECL_STATIC_FUNCTION_P (current_function_decl) = 1;
2285     }
2286   
2287   /* Conditionalize this initialization on being in the right priority
2288      and being initializing/finalizing appropriately.  */
2289   guard_if_stmt = begin_if_stmt ();
2290   cond = cp_build_binary_op (EQ_EXPR,
2291                              priority_decl,
2292                              build_int_2 (priority, 0));
2293   init_cond = initp ? integer_one_node : integer_zero_node;
2294   init_cond = cp_build_binary_op (EQ_EXPR,
2295                                   initialize_p_decl,
2296                                   init_cond);
2297   cond = cp_build_binary_op (TRUTH_ANDIF_EXPR, cond, init_cond);
2298
2299   /* Assume we don't need a guard.  */
2300   guard = NULL_TREE;
2301   /* We need a guard if this is an object with external linkage that
2302      might be initialized in more than one place.  (For example, a
2303      static data member of a template, when the data member requires
2304      construction.)  */
2305   if (TREE_PUBLIC (decl) && (DECL_COMMON (decl) 
2306                              || DECL_ONE_ONLY (decl)
2307                              || DECL_WEAK (decl)))
2308     {
2309       tree guard_cond;
2310
2311       guard = get_guard (decl);
2312
2313       /* When using __cxa_atexit, we just check the GUARD as we would
2314          for a local static.  */
2315       if (flag_use_cxa_atexit)
2316         {
2317           /* When using __cxa_atexit, we never try to destroy
2318              anything from a static destructor.  */
2319           my_friendly_assert (initp, 20000629);
2320           guard_cond = get_guard_cond (guard);
2321         }
2322       /* If we don't have __cxa_atexit, then we will be running
2323          destructors from .fini sections, or their equivalents.  So,
2324          we need to know how many times we've tried to initialize this
2325          object.  We do initializations only if the GUARD is zero,
2326          i.e., if we are the first to initialize the variable.  We do
2327          destructions only if the GUARD is one, i.e., if we are the
2328          last to destroy the variable.  */
2329       else if (initp)
2330         guard_cond 
2331           = cp_build_binary_op (EQ_EXPR,
2332                                 build_unary_op (PREINCREMENT_EXPR,
2333                                                 guard,
2334                                                 /*noconvert=*/1),
2335                                 integer_one_node);
2336       else
2337         guard_cond 
2338           = cp_build_binary_op (EQ_EXPR,
2339                                 build_unary_op (PREDECREMENT_EXPR,
2340                                                 guard,
2341                                                 /*noconvert=*/1),
2342                                 integer_zero_node);
2343
2344       cond = cp_build_binary_op (TRUTH_ANDIF_EXPR, cond, guard_cond);
2345     }
2346
2347   finish_if_stmt_cond (cond, guard_if_stmt);
2348
2349   /* If we're using __cxa_atexit, we have not already set the GUARD,
2350      so we must do so now.  */
2351   if (guard && initp && flag_use_cxa_atexit)
2352     finish_expr_stmt (set_guard (guard));
2353
2354   return guard_if_stmt;
2355 }
2356
2357 /* We've just finished generating code to do an initialization or
2358    finalization.  GUARD_IF_STMT is the if-statement we used to guard
2359    the initialization.  */
2360
2361 static void
2362 finish_static_initialization_or_destruction (tree guard_if_stmt)
2363 {
2364   finish_then_clause (guard_if_stmt);
2365   finish_if_stmt ();
2366
2367   /* Now that we're done with DECL we don't need to pretend to be a
2368      member of its class any longer.  */
2369   DECL_CONTEXT (current_function_decl) = NULL_TREE;
2370   DECL_STATIC_FUNCTION_P (current_function_decl) = 0;
2371 }
2372
2373 /* Generate code to do the initialization of DECL, a VAR_DECL with
2374    static storage duration.  The initialization is INIT.  */
2375
2376 static void
2377 do_static_initialization (tree decl, tree init)
2378 {
2379   tree guard_if_stmt;
2380
2381   /* Set up for the initialization.  */
2382   guard_if_stmt
2383     = start_static_initialization_or_destruction (decl,
2384                                                   /*initp=*/1);
2385
2386   /* Perform the initialization.  */
2387   if (init)
2388     finish_expr_stmt (init);
2389
2390   /* If we're using __cxa_atexit, register a a function that calls the
2391      destructor for the object.  */
2392   if (flag_use_cxa_atexit)
2393     register_dtor_fn (decl);
2394
2395   /* Finsh up.  */
2396   finish_static_initialization_or_destruction (guard_if_stmt);
2397 }
2398
2399 /* Generate code to do the static destruction of DECL.  If DECL may be
2400    initialized more than once in different object files, GUARD is the
2401    guard variable to check.  PRIORITY is the priority for the
2402    destruction.  */
2403
2404 static void
2405 do_static_destruction (tree decl)
2406 {
2407   tree guard_if_stmt;
2408
2409   /* If we're using __cxa_atexit, then destructors are registered
2410      immediately after objects are initialized.  */
2411   my_friendly_assert (!flag_use_cxa_atexit, 20000121);
2412
2413   /* If we don't need a destructor, there's nothing to do.  */
2414   if (TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
2415     return;
2416
2417   /* Actually do the destruction.  */
2418   guard_if_stmt = start_static_initialization_or_destruction (decl,
2419                                                               /*initp=*/0);
2420   finish_expr_stmt (build_cleanup (decl));
2421   finish_static_initialization_or_destruction (guard_if_stmt);
2422 }
2423
2424 /* VARS is a list of variables with static storage duration which may
2425    need initialization and/or finalization.  Remove those variables
2426    that don't really need to be initialized or finalized, and return
2427    the resulting list.  The order in which the variables appear in
2428    VARS is in reverse order of the order in which they should actually
2429    be initialized.  The list we return is in the unreversed order;
2430    i.e., the first variable should be initialized first.  */
2431
2432 static tree
2433 prune_vars_needing_no_initialization (tree *vars)
2434 {
2435   tree *var = vars;
2436   tree result = NULL_TREE;
2437
2438   while (*var)
2439     {
2440       tree t = *var;
2441       tree decl = TREE_VALUE (t);
2442       tree init = TREE_PURPOSE (t);
2443
2444       /* Deal gracefully with error.  */
2445       if (decl == error_mark_node)
2446         {
2447           var = &TREE_CHAIN (t);
2448           continue;
2449         }
2450
2451       /* The only things that can be initialized are variables.  */
2452       my_friendly_assert (TREE_CODE (decl) == VAR_DECL, 19990420);
2453
2454       /* If this object is not defined, we don't need to do anything
2455          here.  */
2456       if (DECL_EXTERNAL (decl))
2457         {
2458           var = &TREE_CHAIN (t);
2459           continue;
2460         }
2461
2462       /* Also, if the initializer already contains errors, we can bail
2463          out now.  */
2464       if (init && TREE_CODE (init) == TREE_LIST 
2465           && value_member (error_mark_node, init))
2466         {
2467           var = &TREE_CHAIN (t);
2468           continue;
2469         }
2470
2471       /* This variable is going to need initialization and/or
2472          finalization, so we add it to the list.  */
2473       *var = TREE_CHAIN (t);
2474       TREE_CHAIN (t) = result;
2475       result = t;
2476     }
2477
2478   return result;
2479 }
2480
2481 /* Make sure we have told the back end about all the variables in
2482    VARS.  */
2483
2484 static void
2485 write_out_vars (tree vars)
2486 {
2487   tree v;
2488
2489   for (v = vars; v; v = TREE_CHAIN (v))
2490     if (! TREE_ASM_WRITTEN (TREE_VALUE (v)))
2491       rest_of_decl_compilation (TREE_VALUE (v), 0, 1, 1);
2492 }
2493
2494 /* Generate a static constructor (if CONSTRUCTOR_P) or destructor
2495    (otherwise) that will initialize all gobal objects with static
2496    storage duration having the indicated PRIORITY.  */
2497
2498 static void
2499 generate_ctor_or_dtor_function (bool constructor_p, int priority,
2500                                 location_t *locus)
2501 {
2502   char function_key;
2503   tree arguments;
2504   tree fndecl;
2505   tree body;
2506   size_t i;
2507
2508   input_location = *locus;
2509   locus->line++;
2510   
2511   /* We use `I' to indicate initialization and `D' to indicate
2512      destruction.  */
2513   function_key = constructor_p ? 'I' : 'D';
2514
2515   /* We emit the function lazily, to avoid generating empty
2516      global constructors and destructors.  */
2517   body = NULL_TREE;
2518
2519   /* Call the static storage duration function with appropriate
2520      arguments.  */
2521   if (ssdf_decls)
2522     for (i = 0; i < ssdf_decls->elements_used; ++i) 
2523       {
2524         fndecl = VARRAY_TREE (ssdf_decls, i);
2525
2526         /* Calls to pure or const functions will expand to nothing.  */
2527         if (! (flags_from_decl_or_type (fndecl) & (ECF_CONST | ECF_PURE)))
2528           {
2529             if (! body)
2530               body = start_objects (function_key, priority);
2531
2532             arguments = tree_cons (NULL_TREE, build_int_2 (priority, 0), 
2533                                    NULL_TREE);
2534             arguments = tree_cons (NULL_TREE, build_int_2 (constructor_p, 0),
2535                                    arguments);
2536             finish_expr_stmt (build_function_call (fndecl, arguments));
2537           }
2538       }
2539
2540   /* If we're generating code for the DEFAULT_INIT_PRIORITY, throw in
2541      calls to any functions marked with attributes indicating that
2542      they should be called at initialization- or destruction-time.  */
2543   if (priority == DEFAULT_INIT_PRIORITY)
2544     {
2545       tree fns;
2546
2547       for (fns = constructor_p ? static_ctors : static_dtors; 
2548            fns;
2549            fns = TREE_CHAIN (fns))
2550         {
2551           fndecl = TREE_VALUE (fns);
2552
2553           /* Calls to pure/const functions will expand to nothing.  */
2554           if (! (flags_from_decl_or_type (fndecl) & (ECF_CONST | ECF_PURE)))
2555             {
2556               if (! body)
2557                 body = start_objects (function_key, priority);
2558               finish_expr_stmt (build_function_call (fndecl, NULL_TREE));
2559             }
2560         }
2561     }
2562
2563   /* Close out the function.  */
2564   if (body)
2565     finish_objects (function_key, priority, body);
2566 }
2567
2568 /* Generate constructor and destructor functions for the priority
2569    indicated by N.  */
2570
2571 static int
2572 generate_ctor_and_dtor_functions_for_priority (splay_tree_node n, void * data)
2573 {
2574   location_t *locus = data;
2575   int priority = (int) n->key;
2576   priority_info pi = (priority_info) n->value;
2577
2578   /* Generate the functions themselves, but only if they are really
2579      needed.  */
2580   if (pi->initializations_p
2581       || (priority == DEFAULT_INIT_PRIORITY && static_ctors))
2582     generate_ctor_or_dtor_function (/*constructor_p=*/true, priority, locus);
2583   if (pi->destructions_p
2584       || (priority == DEFAULT_INIT_PRIORITY && static_dtors))
2585     generate_ctor_or_dtor_function (/*constructor_p=*/false, priority, locus);
2586
2587   /* Keep iterating.  */
2588   return 0;
2589 }
2590
2591 /* Callgraph code does not understand the member pointers.  Mark the methods
2592    referenced as used.  */
2593 static tree
2594 mark_member_pointers (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
2595                       void *data ATTRIBUTE_UNUSED)
2596 {
2597   if (TREE_CODE (*tp) == PTRMEM_CST
2598       && TYPE_PTRMEMFUNC_P (TREE_TYPE (*tp)))
2599     cgraph_mark_needed_node (cgraph_node (PTRMEM_CST_MEMBER (*tp)), 1);
2600   return 0;
2601 }
2602
2603 /* Called via LANGHOOK_CALLGRAPH_LOWER_FUNCTION.  It is supposed to lower
2604    frontend specific constructs that would otherwise confuse the middle end.  */
2605 void
2606 lower_function (tree fn)
2607 {
2608   walk_tree_without_duplicates (&DECL_SAVED_TREE (fn), mark_member_pointers,
2609                                 NULL);
2610 }
2611
2612 /* This routine is called from the last rule in yyparse ().
2613    Its job is to create all the code needed to initialize and
2614    destroy the global aggregates.  We do the destruction
2615    first, since that way we only need to reverse the decls once.  */
2616
2617 void
2618 finish_file ()
2619 {
2620   tree vars;
2621   bool reconsider;
2622   size_t i;
2623   location_t locus;
2624   unsigned ssdf_count = 0;
2625
2626   locus = input_location;
2627   at_eof = 1;
2628
2629   /* Bad parse errors.  Just forget about it.  */
2630   if (! global_bindings_p () || current_class_type || decl_namespace_list)
2631     return;
2632
2633   if (pch_file)
2634     c_common_write_pch ();
2635
2636   /* Otherwise, GDB can get confused, because in only knows
2637      about source for LINENO-1 lines.  */
2638   input_line -= 1;
2639
2640   interface_unknown = 1;
2641   interface_only = 0;
2642
2643   /* We now have to write out all the stuff we put off writing out.
2644      These include:
2645
2646        o Template specializations that we have not yet instantiated,
2647          but which are needed.
2648        o Initialization and destruction for non-local objects with
2649          static storage duration.  (Local objects with static storage
2650          duration are initialized when their scope is first entered,
2651          and are cleaned up via atexit.)
2652        o Virtual function tables.  
2653
2654      All of these may cause others to be needed.  For example,
2655      instantiating one function may cause another to be needed, and
2656      generating the initializer for an object may cause templates to be
2657      instantiated, etc., etc.  */
2658
2659   timevar_push (TV_VARCONST);
2660
2661   emit_support_tinfos ();
2662   
2663   do 
2664     {
2665       tree t;
2666       size_t n_old, n_new;
2667
2668       reconsider = false;
2669
2670       /* If there are templates that we've put off instantiating, do
2671          them now.  */
2672       instantiate_pending_templates ();
2673
2674       /* Write out virtual tables as required.  Note that writing out
2675          the virtual table for a template class may cause the
2676          instantiation of members of that class.  If we write out
2677          vtables then we remove the class from our list so we don't
2678          have to look at it again.  */
2679  
2680       while (keyed_classes != NULL_TREE
2681              && maybe_emit_vtables (TREE_VALUE (keyed_classes)))
2682         {
2683           reconsider = true;
2684           keyed_classes = TREE_CHAIN (keyed_classes);
2685         }
2686  
2687       t = keyed_classes;
2688       if (t != NULL_TREE)
2689         {
2690           tree next = TREE_CHAIN (t);
2691  
2692           while (next)
2693             {
2694               if (maybe_emit_vtables (TREE_VALUE (next)))
2695                 {
2696                   reconsider = true;
2697                   TREE_CHAIN (t) = TREE_CHAIN (next);
2698                 }
2699               else
2700                 t = next;
2701  
2702               next = TREE_CHAIN (t);
2703             }
2704         }
2705        
2706       /* Write out needed type info variables.  We have to be careful
2707          looping through unemitted decls, because emit_tinfo_decl may
2708          cause other variables to be needed.  We stick new elements
2709          (and old elements that we may need to reconsider) at the end
2710          of the array, then shift them back to the beginning once we're
2711          done.  */
2712   
2713       n_old = VARRAY_ACTIVE_SIZE (unemitted_tinfo_decls);
2714       for (i = 0; i < n_old; ++i)
2715         {
2716           tree tinfo_decl = VARRAY_TREE (unemitted_tinfo_decls, i);
2717           if (emit_tinfo_decl (tinfo_decl))
2718             reconsider = true;
2719           else
2720             VARRAY_PUSH_TREE (unemitted_tinfo_decls, tinfo_decl);
2721         }
2722   
2723       /* The only elements we want to keep are the new ones.  Copy
2724          them to the beginning of the array, then get rid of the
2725          leftovers.  */
2726       n_new = VARRAY_ACTIVE_SIZE (unemitted_tinfo_decls) - n_old;
2727       memmove (&VARRAY_TREE (unemitted_tinfo_decls, 0),
2728                &VARRAY_TREE (unemitted_tinfo_decls, n_old),
2729                n_new * sizeof (tree));
2730       memset (&VARRAY_TREE (unemitted_tinfo_decls, n_new),
2731               0,
2732               n_old * sizeof (tree));
2733       VARRAY_ACTIVE_SIZE (unemitted_tinfo_decls) = n_new;
2734
2735       /* The list of objects with static storage duration is built up
2736          in reverse order.  We clear STATIC_AGGREGATES so that any new
2737          aggregates added during the initialization of these will be
2738          initialized in the correct order when we next come around the
2739          loop.  */
2740       vars = prune_vars_needing_no_initialization (&static_aggregates);
2741
2742       if (vars)
2743         {
2744           tree v;
2745
2746           /* We need to start a new initialization function each time
2747              through the loop.  That's because we need to know which
2748              vtables have been referenced, and TREE_SYMBOL_REFERENCED
2749              isn't computed until a function is finished, and written
2750              out.  That's a deficiency in the back-end.  When this is
2751              fixed, these initialization functions could all become
2752              inline, with resulting performance improvements.  */
2753           tree ssdf_body;
2754
2755           /* Set the line and file, so that it is obviously not from
2756              the source file.  */
2757           input_location = locus;
2758           ssdf_body = start_static_storage_duration_function (ssdf_count);
2759
2760           /* Make sure the back end knows about all the variables.  */
2761           write_out_vars (vars);
2762
2763           /* First generate code to do all the initializations.  */
2764           for (v = vars; v; v = TREE_CHAIN (v))
2765             do_static_initialization (TREE_VALUE (v),
2766                                       TREE_PURPOSE (v));
2767
2768           /* Then, generate code to do all the destructions.  Do these
2769              in reverse order so that the most recently constructed
2770              variable is the first destroyed.  If we're using
2771              __cxa_atexit, then we don't need to do this; functions
2772              were registered at initialization time to destroy the
2773              local statics.  */
2774           if (!flag_use_cxa_atexit)
2775             {
2776               vars = nreverse (vars);
2777               for (v = vars; v; v = TREE_CHAIN (v))
2778                 do_static_destruction (TREE_VALUE (v));
2779             }
2780           else
2781             vars = NULL_TREE;
2782
2783           /* Finish up the static storage duration function for this
2784              round.  */
2785           input_location = locus;
2786           finish_static_storage_duration_function (ssdf_body);
2787
2788           /* All those initializations and finalizations might cause
2789              us to need more inline functions, more template
2790              instantiations, etc.  */
2791           reconsider = true;
2792           ssdf_count++;
2793           locus.line++;
2794         }
2795       
2796       for (i = 0; i < deferred_fns_used; ++i)
2797         {
2798           tree decl = VARRAY_TREE (deferred_fns, i);
2799
2800           /* Does it need synthesizing?  */
2801           if (DECL_ARTIFICIAL (decl) && ! DECL_INITIAL (decl)
2802               && TREE_USED (decl)
2803               && (! DECL_REALLY_EXTERN (decl) || DECL_INLINE (decl)))
2804             {
2805               /* Even though we're already at the top-level, we push
2806                  there again.  That way, when we pop back a few lines
2807                  hence, all of our state is restored.  Otherwise,
2808                  finish_function doesn't clean things up, and we end
2809                  up with CURRENT_FUNCTION_DECL set.  */
2810               push_to_top_level ();
2811               synthesize_method (decl);
2812               pop_from_top_level ();
2813               reconsider = true;
2814             }
2815
2816           /* If the function has no body, avoid calling
2817              import_export_decl.  On a system without weak symbols,
2818              calling import_export_decl will make an inline template
2819              instantiation "static", which will result in errors about
2820              the use of undefined functions if there is no body for
2821              the function.  */
2822           if (!DECL_SAVED_TREE (decl))
2823             continue;
2824
2825           import_export_decl (decl);
2826
2827           /* We lie to the back-end, pretending that some functions
2828              are not defined when they really are.  This keeps these
2829              functions from being put out unnecessarily.  But, we must
2830              stop lying when the functions are referenced, or if they
2831              are not comdat since they need to be put out now.  This
2832              is done in a separate for cycle, because if some deferred
2833              function is contained in another deferred function later
2834              in deferred_fns varray, rest_of_compilation would skip
2835              this function and we really cannot expand the same
2836              function twice.  */
2837           if (DECL_NOT_REALLY_EXTERN (decl)
2838               && DECL_INITIAL (decl)
2839               && DECL_NEEDED_P (decl))
2840             DECL_EXTERNAL (decl) = 0;
2841
2842           /* If we're going to need to write this function out, and
2843              there's already a body for it, create RTL for it now.
2844              (There might be no body if this is a method we haven't
2845              gotten around to synthesizing yet.)  */
2846           if (!DECL_EXTERNAL (decl)
2847               && DECL_NEEDED_P (decl)
2848               && DECL_SAVED_TREE (decl)
2849               && !TREE_ASM_WRITTEN (decl)
2850               && (!flag_unit_at_a_time 
2851                   || !cgraph_node (decl)->local.finalized))
2852             {
2853               /* We will output the function; no longer consider it in this
2854                  loop.  */
2855               DECL_DEFER_OUTPUT (decl) = 0;
2856               /* Generate RTL for this function now that we know we
2857                  need it.  */
2858               expand_or_defer_fn (decl);
2859               /* If we're compiling -fsyntax-only pretend that this
2860                  function has been written out so that we don't try to
2861                  expand it again.  */
2862               if (flag_syntax_only)
2863                 TREE_ASM_WRITTEN (decl) = 1;
2864               reconsider = true;
2865             }
2866         }
2867
2868       if (walk_namespaces (wrapup_globals_for_namespace, /*data=*/0))
2869         reconsider = true;
2870
2871       /* Static data members are just like namespace-scope globals.  */
2872       for (i = 0; i < pending_statics_used; ++i) 
2873         {
2874           tree decl = VARRAY_TREE (pending_statics, i);
2875           if (TREE_ASM_WRITTEN (decl))
2876             continue;
2877           import_export_decl (decl);
2878           if (DECL_NOT_REALLY_EXTERN (decl) && ! DECL_IN_AGGR_P (decl))
2879             DECL_EXTERNAL (decl) = 0;
2880         }
2881       if (pending_statics
2882           && wrapup_global_declarations (&VARRAY_TREE (pending_statics, 0),
2883                                          pending_statics_used))
2884         reconsider = true;
2885     } 
2886   while (reconsider);
2887
2888   /* All used inline functions must have a definition at this point.  */
2889   for (i = 0; i < deferred_fns_used; ++i)
2890     {
2891       tree decl = VARRAY_TREE (deferred_fns, i);
2892
2893       if (TREE_USED (decl) && DECL_DECLARED_INLINE_P (decl)
2894           && !(TREE_ASM_WRITTEN (decl) || DECL_SAVED_TREE (decl)
2895                /* An explicit instantiation can be used to specify
2896                   that the body is in another unit. It will have
2897                   already verified there was a definition.  */
2898                || DECL_EXPLICIT_INSTANTIATION (decl)))
2899         {
2900           cp_warning_at ("inline function `%D' used but never defined", decl);
2901           /* This symbol is effectively an "extern" declaration now.
2902              This is not strictly necessary, but removes a duplicate
2903              warning.  */
2904           TREE_PUBLIC (decl) = 1;
2905         }
2906       
2907     }
2908   
2909   /* We give C linkage to static constructors and destructors.  */
2910   push_lang_context (lang_name_c);
2911
2912   /* Generate initialization and destruction functions for all
2913      priorities for which they are required.  */
2914   if (priority_info_map)
2915     splay_tree_foreach (priority_info_map, 
2916                         generate_ctor_and_dtor_functions_for_priority,
2917                         /*data=*/&locus);
2918   else
2919     {
2920       
2921       if (static_ctors)
2922         generate_ctor_or_dtor_function (/*constructor_p=*/true,
2923                                         DEFAULT_INIT_PRIORITY, &locus);
2924       if (static_dtors)
2925         generate_ctor_or_dtor_function (/*constructor_p=*/false,
2926                                         DEFAULT_INIT_PRIORITY, &locus);
2927     }
2928
2929   /* We're done with the splay-tree now.  */
2930   if (priority_info_map)
2931     splay_tree_delete (priority_info_map);
2932
2933   /* We're done with static constructors, so we can go back to "C++"
2934      linkage now.  */
2935   pop_lang_context ();
2936
2937   if (flag_unit_at_a_time)
2938     {
2939       cgraph_finalize_compilation_unit ();
2940       cgraph_optimize ();
2941     }
2942
2943   /* Now, issue warnings about static, but not defined, functions,
2944      etc., and emit debugging information.  */
2945   walk_namespaces (wrapup_globals_for_namespace, /*data=*/&reconsider);
2946   if (pending_statics)
2947     check_global_declarations (&VARRAY_TREE (pending_statics, 0),
2948                                pending_statics_used);
2949
2950   finish_repo ();
2951
2952   /* The entire file is now complete.  If requested, dump everything
2953      to a file.  */
2954   {
2955     int flags;
2956     FILE *stream = dump_begin (TDI_all, &flags);
2957
2958     if (stream)
2959       {
2960         dump_node (global_namespace, flags & ~TDF_SLIM, stream);
2961         dump_end (TDI_all, stream);
2962       }
2963   }
2964   
2965   timevar_pop (TV_VARCONST);
2966
2967   if (flag_detailed_statistics)
2968     {
2969       dump_tree_statistics ();
2970       dump_time_statistics ();
2971     }
2972   input_location = locus;
2973 }
2974
2975 /* FN is an OFFSET_REF indicating the function to call in parse-tree
2976    form; it has not yet been semantically analyzed.  ARGS are the
2977    arguments to the function.  They have already been semantically
2978    analzyed.  */
2979
2980 tree
2981 build_offset_ref_call_from_tree (tree fn, tree args)
2982 {
2983   tree object_addr;
2984   tree orig_fn;
2985   tree orig_args;
2986   tree expr;
2987
2988   orig_fn = fn;
2989   orig_args = args;
2990
2991   if (processing_template_decl)
2992     {
2993       tree object;
2994       tree object_type;
2995
2996       my_friendly_assert (TREE_CODE (fn) == DOTSTAR_EXPR
2997                           || TREE_CODE (fn) == MEMBER_REF,
2998                           20030708);
2999       if (type_dependent_expression_p (fn)
3000           || any_type_dependent_arguments_p (args))
3001         return build_min_nt (CALL_EXPR, fn, args);
3002
3003       /* Transform the arguments and add the implicit "this"
3004          parameter.  That must be done before the FN is transformed
3005          because we depend on the form of FN.  */
3006       args = build_non_dependent_args (args);
3007       object_type = TREE_TYPE (TREE_OPERAND (fn, 0));
3008       if (TREE_CODE (fn) == DOTSTAR_EXPR)
3009         object_type = build_pointer_type (non_reference (object_type));
3010       object = build (NON_DEPENDENT_EXPR, object_type);
3011       args = tree_cons (NULL_TREE, object, args);
3012       /* Now that the arguments are done, transform FN.  */
3013       fn = build_non_dependent_expr (fn);
3014     }
3015
3016   /* A qualified name corresponding to a bound pointer-to-member is
3017      represented as an OFFSET_REF:
3018
3019         struct B { void g(); };
3020         void (B::*p)();
3021         void B::g() { (this->*p)(); }  */
3022   if (TREE_CODE (fn) == OFFSET_REF)
3023     {
3024       object_addr = build_unary_op (ADDR_EXPR, TREE_OPERAND (fn, 0), 0);
3025       fn = TREE_OPERAND (fn, 1);
3026       fn = get_member_function_from_ptrfunc (&object_addr, fn);
3027       args = tree_cons (NULL_TREE, object_addr, args);
3028     }
3029
3030   expr = build_function_call (fn, args);
3031   if (processing_template_decl && expr != error_mark_node)
3032     return build_min (CALL_EXPR, TREE_TYPE (expr), orig_fn, orig_args);
3033   return expr;
3034 }
3035
3036 /* Returns true if ROOT (a namespace, class, or function) encloses
3037    CHILD.  CHILD may be either a class type or a namespace.  */
3038
3039 bool
3040 is_ancestor (tree root, tree child)
3041 {
3042   my_friendly_assert ((TREE_CODE (root) == NAMESPACE_DECL
3043                        || TREE_CODE (root) == FUNCTION_DECL
3044                        || CLASS_TYPE_P (root)), 20030307);
3045   my_friendly_assert ((TREE_CODE (child) == NAMESPACE_DECL
3046                        || CLASS_TYPE_P (child)),
3047                       20030307);
3048   
3049   /* The global namespace encloses everything.  */
3050   if (root == global_namespace)
3051     return true;
3052
3053   while (true)
3054     {
3055       /* If we've run out of scopes, stop.  */
3056       if (!child)
3057         return false;
3058       /* If we've reached the ROOT, it encloses CHILD.  */
3059       if (root == child)
3060         return true;
3061       /* Go out one level.  */
3062       if (TYPE_P (child))
3063         child = TYPE_NAME (child);
3064       child = DECL_CONTEXT (child);
3065     }
3066 }
3067   
3068
3069 /* Return the namespace that is the common ancestor 
3070    of two given namespaces.  */
3071
3072 tree
3073 namespace_ancestor (tree ns1, tree ns2)
3074 {
3075   timevar_push (TV_NAME_LOOKUP);
3076   if (is_ancestor (ns1, ns2))
3077     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, ns1);
3078   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP,
3079                           namespace_ancestor (CP_DECL_CONTEXT (ns1), ns2));
3080 }
3081
3082 /* Insert USED into the using list of USER. Set INDIRECT_flag if this
3083    directive is not directly from the source. Also find the common
3084    ancestor and let our users know about the new namespace */
3085 static void 
3086 add_using_namespace (tree user, tree used, bool indirect)
3087 {
3088   tree t;
3089   timevar_push (TV_NAME_LOOKUP);
3090   /* Using oneself is a no-op.  */
3091   if (user == used)
3092     {
3093       timevar_pop (TV_NAME_LOOKUP);
3094       return;
3095     }
3096   my_friendly_assert (TREE_CODE (user) == NAMESPACE_DECL, 380);
3097   my_friendly_assert (TREE_CODE (used) == NAMESPACE_DECL, 380);
3098   /* Check if we already have this.  */
3099   t = purpose_member (used, DECL_NAMESPACE_USING (user));
3100   if (t != NULL_TREE)
3101     {
3102       if (!indirect)
3103         /* Promote to direct usage.  */
3104         TREE_INDIRECT_USING (t) = 0;
3105       timevar_pop (TV_NAME_LOOKUP);
3106       return;
3107     }
3108
3109   /* Add used to the user's using list.  */
3110   DECL_NAMESPACE_USING (user) 
3111     = tree_cons (used, namespace_ancestor (user, used), 
3112                  DECL_NAMESPACE_USING (user));
3113
3114   TREE_INDIRECT_USING (DECL_NAMESPACE_USING (user)) = indirect;
3115
3116   /* Add user to the used's users list.  */
3117   DECL_NAMESPACE_USERS (used)
3118     = tree_cons (user, 0, DECL_NAMESPACE_USERS (used));
3119
3120   /* Recursively add all namespaces used.  */
3121   for (t = DECL_NAMESPACE_USING (used); t; t = TREE_CHAIN (t))
3122     /* indirect usage */
3123     add_using_namespace (user, TREE_PURPOSE (t), 1);
3124
3125   /* Tell everyone using us about the new used namespaces.  */
3126   for (t = DECL_NAMESPACE_USERS (user); t; t = TREE_CHAIN (t))
3127     add_using_namespace (TREE_PURPOSE (t), used, 1);
3128   timevar_pop (TV_NAME_LOOKUP);
3129 }
3130
3131 /* Combines two sets of overloaded functions into an OVERLOAD chain, removing
3132    duplicates.  The first list becomes the tail of the result.
3133
3134    The algorithm is O(n^2).  We could get this down to O(n log n) by
3135    doing a sort on the addresses of the functions, if that becomes
3136    necessary.  */
3137
3138 static tree
3139 merge_functions (tree s1, tree s2)
3140 {
3141   for (; s2; s2 = OVL_NEXT (s2))
3142     {
3143       tree fn2 = OVL_CURRENT (s2);
3144       tree fns1;
3145
3146       for (fns1 = s1; fns1; fns1 = OVL_NEXT (fns1))
3147         {
3148           tree fn1 = OVL_CURRENT (fns1);
3149
3150           /* If the function from S2 is already in S1, there is no
3151              need to add it again.  For `extern "C"' functions, we
3152              might have two FUNCTION_DECLs for the same function, in
3153              different namespaces; again, we only need one of them.  */
3154           if (fn1 == fn2 
3155               || (DECL_EXTERN_C_P (fn1) && DECL_EXTERN_C_P (fn2)
3156                   && DECL_NAME (fn1) == DECL_NAME (fn2)))
3157             break;
3158         }
3159       
3160       /* If we exhausted all of the functions in S1, FN2 is new.  */
3161       if (!fns1)
3162         s1 = build_overload (fn2, s1);
3163     }
3164   return s1;
3165 }
3166
3167 /* This should return an error not all definitions define functions.
3168    It is not an error if we find two functions with exactly the
3169    same signature, only if these are selected in overload resolution.
3170    old is the current set of bindings, new the freshly-found binding.
3171    XXX Do we want to give *all* candidates in case of ambiguity?
3172    XXX In what way should I treat extern declarations?
3173    XXX I don't want to repeat the entire duplicate_decls here */
3174
3175 static cxx_binding *
3176 ambiguous_decl (tree name, cxx_binding *old, cxx_binding *new, int flags)
3177 {
3178   tree val, type;
3179   my_friendly_assert (old != NULL, 393);
3180   /* Copy the value.  */
3181   val = BINDING_VALUE (new);
3182   if (val)
3183     switch (TREE_CODE (val))
3184       {
3185       case TEMPLATE_DECL:
3186         /* If we expect types or namespaces, and not templates,
3187            or this is not a template class.  */
3188         if (LOOKUP_QUALIFIERS_ONLY (flags)
3189             && !DECL_CLASS_TEMPLATE_P (val))
3190           val = NULL_TREE;
3191         break;
3192       case TYPE_DECL:
3193         if (LOOKUP_NAMESPACES_ONLY (flags))
3194           val = NULL_TREE;
3195         break;
3196       case NAMESPACE_DECL:
3197         if (LOOKUP_TYPES_ONLY (flags))
3198           val = NULL_TREE;
3199         break;
3200       case FUNCTION_DECL:
3201         /* Ignore built-in functions that are still anticipated.  */
3202         if (LOOKUP_QUALIFIERS_ONLY (flags) || DECL_ANTICIPATED (val))
3203           val = NULL_TREE;
3204         break;
3205       default:
3206         if (LOOKUP_QUALIFIERS_ONLY (flags))
3207           val = NULL_TREE;
3208       }
3209         
3210   if (!BINDING_VALUE (old))
3211     BINDING_VALUE (old) = val;
3212   else if (val && val != BINDING_VALUE (old))
3213     {
3214       if (is_overloaded_fn (BINDING_VALUE (old)) && is_overloaded_fn (val))
3215         BINDING_VALUE (old) = merge_functions (BINDING_VALUE (old), val);
3216       else
3217         {
3218           /* Some declarations are functions, some are not.  */
3219           if (flags & LOOKUP_COMPLAIN)
3220             {
3221               /* If we've already given this error for this lookup,
3222                  BINDING_VALUE (old) is error_mark_node, so let's not
3223                  repeat ourselves.  */
3224               if (BINDING_VALUE (old) != error_mark_node)
3225                 {
3226                   error ("use of `%D' is ambiguous", name);
3227                   cp_error_at ("  first declared as `%#D' here",
3228                                BINDING_VALUE (old));
3229                 }
3230               cp_error_at ("  also declared as `%#D' here", val);
3231             }
3232           BINDING_VALUE (old) = error_mark_node;
3233         }
3234     }
3235   /* ... and copy the type.  */
3236   type = BINDING_TYPE (new);
3237   if (LOOKUP_NAMESPACES_ONLY (flags))
3238     type = NULL_TREE;
3239   if (!BINDING_TYPE (old))
3240     BINDING_TYPE (old) = type;
3241   else if (type && BINDING_TYPE (old) != type)
3242     {
3243       if (flags & LOOKUP_COMPLAIN)
3244         {
3245           error ("`%D' denotes an ambiguous type",name);
3246           error ("%H  first type here",
3247                  &DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (BINDING_TYPE (old))));
3248           error ("%H  other type here",
3249                  &DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)));
3250         }
3251     }
3252   return old;
3253 }
3254
3255 /* Subroutine of unualified_namespace_lookup:
3256    Add the bindings of NAME in used namespaces to VAL.
3257    We are currently looking for names in namespace SCOPE, so we
3258    look through USINGS for using-directives of namespaces
3259    which have SCOPE as a common ancestor with the current scope.
3260    Returns false on errors.  */
3261
3262 bool
3263 lookup_using_namespace (tree name, cxx_binding *val, tree usings, tree scope,
3264                         int flags, tree *spacesp)
3265 {
3266   tree iter;
3267   timevar_push (TV_NAME_LOOKUP);
3268   /* Iterate over all used namespaces in current, searching for using
3269      directives of scope.  */
3270   for (iter = usings; iter; iter = TREE_CHAIN (iter))
3271     if (TREE_VALUE (iter) == scope)
3272       {
3273         tree used = ORIGINAL_NAMESPACE (TREE_PURPOSE (iter));
3274         cxx_binding *val1 =
3275           cxx_scope_find_binding_for_name (NAMESPACE_LEVEL (used), name);
3276         if (spacesp)
3277           *spacesp = tree_cons (used, NULL_TREE, *spacesp);
3278         /* Resolve ambiguities.  */
3279         if (val1)
3280           val = ambiguous_decl (name, val, val1, flags);
3281       }
3282   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP,
3283                           BINDING_VALUE (val) != error_mark_node);
3284 }
3285
3286 /* [namespace.qual]
3287    Accepts the NAME to lookup and its qualifying SCOPE.
3288    Returns the name/type pair found into the cxx_binding *RESULT,
3289    or false on error.  */
3290
3291 bool
3292 qualified_lookup_using_namespace (tree name, tree scope, cxx_binding *result,
3293                                   int flags)
3294 {
3295   /* Maintain a list of namespaces visited...  */
3296   tree seen = NULL_TREE;
3297   /* ... and a list of namespace yet to see.  */
3298   tree todo = NULL_TREE;
3299   tree usings;
3300   timevar_push (TV_NAME_LOOKUP);
3301   /* Look through namespace aliases.  */
3302   scope = ORIGINAL_NAMESPACE (scope);
3303   while (scope && result->value != error_mark_node)
3304     {
3305       cxx_binding *binding =
3306         cxx_scope_find_binding_for_name (NAMESPACE_LEVEL (scope), name);
3307       seen = tree_cons (scope, NULL_TREE, seen);
3308       if (binding)
3309         result = ambiguous_decl (name, result, binding, flags);
3310       if (!BINDING_VALUE (result) && !BINDING_TYPE (result))
3311         /* Consider using directives.  */
3312         for (usings = DECL_NAMESPACE_USING (scope); usings;
3313              usings = TREE_CHAIN (usings))
3314           /* If this was a real directive, and we have not seen it.  */
3315           if (!TREE_INDIRECT_USING (usings)
3316               && !purpose_member (TREE_PURPOSE (usings), seen))
3317             todo = tree_cons (TREE_PURPOSE (usings), NULL_TREE, todo);
3318       if (todo)
3319         {
3320           scope = TREE_PURPOSE (todo);
3321           todo = TREE_CHAIN (todo);
3322         }
3323       else
3324         scope = NULL_TREE; /* If there never was a todo list.  */
3325     }
3326   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, result->value != error_mark_node);
3327 }
3328
3329 /* [namespace.memdef]/2 */
3330
3331 /* Set the context of a declaration to scope. Complain if we are not
3332    outside scope.  */
3333
3334 void
3335 set_decl_namespace (tree decl, tree scope, bool friendp)
3336 {
3337   tree old;
3338   
3339   /* Get rid of namespace aliases.  */
3340   scope = ORIGINAL_NAMESPACE (scope);
3341   
3342   /* It is ok for friends to be qualified in parallel space.  */
3343   if (!friendp && !is_ancestor (current_namespace, scope))
3344     error ("declaration of `%D' not in a namespace surrounding `%D'",
3345               decl, scope);
3346   DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
3347   if (scope != current_namespace)
3348     {
3349       /* See whether this has been declared in the namespace.  */
3350       old = namespace_binding (DECL_NAME (decl), scope);
3351       if (!old)
3352         /* No old declaration at all.  */
3353         goto complain;
3354       /* A template can be explicitly specialized in any namespace.  */
3355       if (processing_explicit_instantiation)
3356         return;
3357       if (!is_overloaded_fn (decl))
3358         /* Don't compare non-function decls with decls_match here,
3359            since it can't check for the correct constness at this
3360            point. pushdecl will find those errors later.  */
3361         return;
3362       /* Since decl is a function, old should contain a function decl.  */
3363       if (!is_overloaded_fn (old))
3364         goto complain;
3365       if (processing_template_decl || processing_specialization)
3366         /* We have not yet called push_template_decl to turn a
3367            FUNCTION_DECL into a TEMPLATE_DECL, so the declarations
3368            won't match.  But, we'll check later, when we construct the
3369            template.  */
3370         return;
3371       if (is_overloaded_fn (old))
3372         {
3373           for (; old; old = OVL_NEXT (old))
3374             if (decls_match (decl, OVL_CURRENT (old)))
3375               return;
3376         }
3377       else
3378         if (decls_match (decl, old))
3379           return;
3380     }
3381   else
3382     return;
3383  complain:
3384   error ("`%D' should have been declared inside `%D'",
3385             decl, scope);
3386
3387
3388 /* Compute the namespace where a declaration is defined.  */
3389
3390 static tree
3391 decl_namespace (tree decl)
3392 {
3393   timevar_push (TV_NAME_LOOKUP);
3394   if (TYPE_P (decl))
3395     decl = TYPE_STUB_DECL (decl);
3396   while (DECL_CONTEXT (decl))
3397     {
3398       decl = DECL_CONTEXT (decl);
3399       if (TREE_CODE (decl) == NAMESPACE_DECL)
3400         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, decl);
3401       if (TYPE_P (decl))
3402         decl = TYPE_STUB_DECL (decl);
3403       my_friendly_assert (DECL_P (decl), 390);
3404     }
3405
3406   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, global_namespace);
3407 }
3408
3409 /* Return the namespace where the current declaration is declared.  */
3410
3411 tree
3412 current_decl_namespace (void)
3413 {
3414   tree result;
3415   /* If we have been pushed into a different namespace, use it.  */
3416   if (decl_namespace_list)
3417     return TREE_PURPOSE (decl_namespace_list);
3418
3419   if (current_class_type)
3420     result = decl_namespace (TYPE_STUB_DECL (current_class_type));
3421   else if (current_function_decl)
3422     result = decl_namespace (current_function_decl);
3423   else 
3424     result = current_namespace;
3425   return result;
3426 }
3427
3428 /* Temporarily set the namespace for the current declaration.  */
3429
3430 void
3431 push_decl_namespace (tree decl)
3432 {
3433   if (TREE_CODE (decl) != NAMESPACE_DECL)
3434     decl = decl_namespace (decl);
3435   decl_namespace_list = tree_cons (ORIGINAL_NAMESPACE (decl),
3436                                    NULL_TREE, decl_namespace_list);
3437 }
3438
3439 void
3440 pop_decl_namespace (void)
3441 {
3442   decl_namespace_list = TREE_CHAIN (decl_namespace_list);
3443 }
3444
3445 /* Enter a class or namespace scope.  */
3446
3447 void
3448 push_scope (tree t)
3449 {
3450   if (TREE_CODE (t) == NAMESPACE_DECL)
3451     push_decl_namespace (t);
3452   else if CLASS_TYPE_P (t)
3453     push_nested_class (t);
3454 }
3455
3456 /* Leave scope pushed by push_scope.  */
3457
3458 void
3459 pop_scope (tree t)
3460 {
3461   if (TREE_CODE (t) == NAMESPACE_DECL)
3462     pop_decl_namespace ();
3463   else if CLASS_TYPE_P (t)
3464     pop_nested_class ();
3465 }
3466
3467 /* [basic.lookup.koenig] */
3468 /* A nonzero return value in the functions below indicates an error.  */
3469
3470 struct arg_lookup
3471 {
3472   tree name;
3473   tree namespaces;
3474   tree classes;
3475   tree functions;
3476 };
3477
3478 static bool arg_assoc (struct arg_lookup*, tree);
3479 static bool arg_assoc_args (struct arg_lookup*, tree);
3480 static bool arg_assoc_type (struct arg_lookup*, tree);
3481 static bool add_function (struct arg_lookup *, tree);
3482 static bool arg_assoc_namespace (struct arg_lookup *, tree);
3483 static bool arg_assoc_class (struct arg_lookup *, tree);
3484 static bool arg_assoc_template_arg (struct arg_lookup*, tree);
3485
3486 /* Add a function to the lookup structure.
3487    Returns true on error.  */
3488
3489 static bool
3490 add_function (struct arg_lookup *k, tree fn)
3491 {
3492   /* We used to check here to see if the function was already in the list,
3493      but that's O(n^2), which is just too expensive for function lookup.
3494      Now we deal with the occasional duplicate in joust.  In doing this, we
3495      assume that the number of duplicates will be small compared to the
3496      total number of functions being compared, which should usually be the
3497      case.  */
3498
3499   /* We must find only functions, or exactly one non-function.  */
3500   if (!k->functions) 
3501     k->functions = fn;
3502   else if (is_overloaded_fn (k->functions) && is_overloaded_fn (fn))
3503     k->functions = build_overload (fn, k->functions);
3504   else
3505     {
3506       tree f1 = OVL_CURRENT (k->functions);
3507       tree f2 = fn;
3508       if (is_overloaded_fn (f1))
3509         {
3510           fn = f1; f1 = f2; f2 = fn;
3511         }
3512       cp_error_at ("`%D' is not a function,", f1);
3513       cp_error_at ("  conflict with `%D'", f2);
3514       error ("  in call to `%D'", k->name);
3515       return true;
3516     }
3517
3518   return false;
3519 }
3520
3521 /* Add functions of a namespace to the lookup structure.
3522    Returns true on error.  */
3523
3524 static bool
3525 arg_assoc_namespace (struct arg_lookup *k, tree scope)
3526 {
3527   tree value;
3528
3529   if (purpose_member (scope, k->namespaces))
3530     return 0;
3531   k->namespaces = tree_cons (scope, NULL_TREE, k->namespaces);
3532   
3533   value = namespace_binding (k->name, scope);
3534   if (!value)
3535     return false;
3536
3537   for (; value; value = OVL_NEXT (value))
3538     if (add_function (k, OVL_CURRENT (value)))
3539       return true;
3540   
3541   return false;
3542 }
3543
3544 /* Adds everything associated with a template argument to the lookup
3545    structure.  Returns true on error.  */
3546
3547 static bool
3548 arg_assoc_template_arg (struct arg_lookup *k, tree arg)
3549 {
3550   /* [basic.lookup.koenig]
3551
3552      If T is a template-id, its associated namespaces and classes are
3553      ... the namespaces and classes associated with the types of the
3554      template arguments provided for template type parameters
3555      (excluding template template parameters); the namespaces in which
3556      any template template arguments are defined; and the classes in
3557      which any member templates used as template template arguments
3558      are defined.  [Note: non-type template arguments do not
3559      contribute to the set of associated namespaces.  ]  */
3560
3561   /* Consider first template template arguments.  */
3562   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
3563       || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
3564     return false;
3565   else if (TREE_CODE (arg) == TEMPLATE_DECL)
3566     {
3567       tree ctx = CP_DECL_CONTEXT (arg);
3568
3569       /* It's not a member template.  */
3570       if (TREE_CODE (ctx) == NAMESPACE_DECL)
3571         return arg_assoc_namespace (k, ctx);
3572       /* Otherwise, it must be member template.  */
3573       else 
3574         return arg_assoc_class (k, ctx);
3575     }
3576   /* It's not a template template argument, but it is a type template
3577      argument.  */
3578   else if (TYPE_P (arg))
3579     return arg_assoc_type (k, arg);
3580   /* It's a non-type template argument.  */
3581   else
3582     return false;
3583 }
3584
3585 /* Adds everything associated with class to the lookup structure.
3586    Returns true on error.  */
3587
3588 static bool
3589 arg_assoc_class (struct arg_lookup *k, tree type)
3590 {
3591   tree list, friends, context;
3592   int i;
3593   
3594   /* Backend build structures, such as __builtin_va_list, aren't
3595      affected by all this.  */
3596   if (!CLASS_TYPE_P (type))
3597     return false;
3598
3599   if (purpose_member (type, k->classes))
3600     return false;
3601   k->classes = tree_cons (type, NULL_TREE, k->classes);
3602   
3603   context = decl_namespace (TYPE_MAIN_DECL (type));
3604   if (arg_assoc_namespace (k, context))
3605     return true;
3606   
3607   /* Process baseclasses.  */
3608   for (i = 0; i < CLASSTYPE_N_BASECLASSES (type); i++)
3609     if (arg_assoc_class (k, TYPE_BINFO_BASETYPE (type, i)))
3610       return true;
3611   
3612   /* Process friends.  */
3613   for (list = DECL_FRIENDLIST (TYPE_MAIN_DECL (type)); list; 
3614        list = TREE_CHAIN (list))
3615     if (k->name == FRIEND_NAME (list))
3616       for (friends = FRIEND_DECLS (list); friends; 
3617            friends = TREE_CHAIN (friends))
3618         /* Only interested in global functions with potentially hidden
3619            (i.e. unqualified) declarations.  */
3620         if (CP_DECL_CONTEXT (TREE_VALUE (friends)) == context)
3621           if (add_function (k, TREE_VALUE (friends)))
3622             return true;
3623
3624   /* Process template arguments.  */
3625   if (CLASSTYPE_TEMPLATE_INFO (type))
3626     {
3627       list = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
3628       for (i = 0; i < TREE_VEC_LENGTH (list); ++i) 
3629         arg_assoc_template_arg (k, TREE_VEC_ELT (list, i));
3630     }
3631
3632   return false;
3633 }
3634
3635 /* Adds everything associated with a given type.
3636    Returns 1 on error.  */
3637
3638 static bool
3639 arg_assoc_type (struct arg_lookup *k, tree type)
3640 {
3641   /* As we do not get the type of non-type dependent expressions
3642      right, we can end up with such things without a type.  */
3643   if (!type)
3644     return false;
3645
3646   if (TYPE_PTRMEM_P (type))
3647     {
3648       /* Pointer to member: associate class type and value type.  */
3649       if (arg_assoc_type (k, TYPE_PTRMEM_CLASS_TYPE (type)))
3650         return true;
3651       return arg_assoc_type (k, TYPE_PTRMEM_POINTED_TO_TYPE (type));
3652     }
3653   else switch (TREE_CODE (type))
3654     {
3655     case ERROR_MARK:
3656       return false;
3657     case VOID_TYPE:
3658     case INTEGER_TYPE:
3659     case REAL_TYPE:
3660     case COMPLEX_TYPE:
3661     case VECTOR_TYPE:
3662     case CHAR_TYPE:
3663     case BOOLEAN_TYPE:
3664       return false;
3665     case RECORD_TYPE:
3666       if (TYPE_PTRMEMFUNC_P (type))
3667         return arg_assoc_type (k, TYPE_PTRMEMFUNC_FN_TYPE (type));
3668       return arg_assoc_class (k, type);
3669     case POINTER_TYPE:
3670     case REFERENCE_TYPE:
3671     case ARRAY_TYPE:
3672       return arg_assoc_type (k, TREE_TYPE (type));
3673     case UNION_TYPE:
3674     case ENUMERAL_TYPE:
3675       return arg_assoc_namespace (k, decl_namespace (TYPE_MAIN_DECL (type)));
3676     case METHOD_TYPE:
3677       /* The basetype is referenced in the first arg type, so just
3678          fall through.  */
3679     case FUNCTION_TYPE:
3680       /* Associate the parameter types.  */
3681       if (arg_assoc_args (k, TYPE_ARG_TYPES (type)))
3682         return true;
3683       /* Associate the return type.  */
3684       return arg_assoc_type (k, TREE_TYPE (type));
3685     case TEMPLATE_TYPE_PARM:
3686     case BOUND_TEMPLATE_TEMPLATE_PARM:
3687       return false;
3688     case TYPENAME_TYPE:
3689       return false;
3690     case LANG_TYPE:
3691       if (type == unknown_type_node)
3692         return false;
3693       /* else fall through */
3694     default:
3695       abort ();
3696     }
3697   return false;
3698 }
3699
3700 /* Adds everything associated with arguments.  Returns true on error.  */
3701
3702 static bool
3703 arg_assoc_args (struct arg_lookup *k, tree args)
3704 {
3705   for (; args; args = TREE_CHAIN (args))
3706     if (arg_assoc (k, TREE_VALUE (args)))
3707       return true;
3708   return false;
3709 }
3710
3711 /* Adds everything associated with a given tree_node.  Returns 1 on error.  */
3712
3713 static bool
3714 arg_assoc (struct arg_lookup *k, tree n)
3715 {
3716   if (n == error_mark_node)
3717     return false;
3718
3719   if (TYPE_P (n))
3720     return arg_assoc_type (k, n);
3721
3722   if (! type_unknown_p (n))
3723     return arg_assoc_type (k, TREE_TYPE (n));
3724
3725   if (TREE_CODE (n) == ADDR_EXPR)
3726     n = TREE_OPERAND (n, 0);
3727   if (TREE_CODE (n) == COMPONENT_REF)
3728     n = TREE_OPERAND (n, 1);
3729   if (TREE_CODE (n) == OFFSET_REF)
3730     n = TREE_OPERAND (n, 1);
3731   while (TREE_CODE (n) == TREE_LIST)
3732     n = TREE_VALUE (n);
3733   if (TREE_CODE (n) == BASELINK)
3734     n = BASELINK_FUNCTIONS (n);
3735
3736   if (TREE_CODE (n) == FUNCTION_DECL)
3737     return arg_assoc_type (k, TREE_TYPE (n));
3738   if (TREE_CODE (n) == TEMPLATE_ID_EXPR)
3739     {
3740       /* [basic.lookup.koenig]
3741
3742          If T is a template-id, its associated namespaces and classes
3743          are the namespace in which the template is defined; for
3744          member templates, the member template's class...  */
3745       tree template = TREE_OPERAND (n, 0);
3746       tree args = TREE_OPERAND (n, 1);
3747       tree ctx;
3748       tree arg;
3749
3750       if (TREE_CODE (template) == COMPONENT_REF)
3751         template = TREE_OPERAND (template, 1);
3752       
3753       /* First, the template.  There may actually be more than one if
3754          this is an overloaded function template.  But, in that case,
3755          we only need the first; all the functions will be in the same
3756          namespace.  */
3757       template = OVL_CURRENT (template);
3758
3759       ctx = CP_DECL_CONTEXT (template);
3760        
3761       if (TREE_CODE (ctx) == NAMESPACE_DECL)
3762         {
3763           if (arg_assoc_namespace (k, ctx) == 1)
3764             return true;
3765         }
3766       /* It must be a member template.  */
3767       else if (arg_assoc_class (k, ctx) == 1)
3768         return true;
3769
3770       /* Now the arguments.  */
3771       for (arg = args; arg != NULL_TREE; arg = TREE_CHAIN (arg))
3772         if (arg_assoc_template_arg (k, TREE_VALUE (arg)) == 1)
3773           return true;
3774     }
3775   else
3776     {
3777       my_friendly_assert (TREE_CODE (n) == OVERLOAD, 980715);
3778       
3779       for (; n; n = OVL_CHAIN (n))
3780         if (arg_assoc_type (k, TREE_TYPE (OVL_FUNCTION (n))))
3781           return true;
3782     }
3783
3784   return false;
3785 }
3786
3787 /* Performs Koenig lookup depending on arguments, where fns
3788    are the functions found in normal lookup.  */
3789
3790 tree
3791 lookup_arg_dependent (tree name, tree fns, tree args)
3792 {
3793   struct arg_lookup k;
3794   tree fn = NULL_TREE;
3795
3796   timevar_push (TV_NAME_LOOKUP);
3797   k.name = name;
3798   k.functions = fns;
3799   k.classes = NULL_TREE;
3800
3801   /* Note that we've already looked at some namespaces during normal
3802      unqualified lookup, unless we found a decl in function scope.  */
3803   if (fns)
3804     fn = OVL_CURRENT (fns);
3805   if (fn && TREE_CODE (fn) == FUNCTION_DECL && DECL_LOCAL_FUNCTION_P (fn))
3806     k.namespaces = NULL_TREE;
3807   else
3808     unqualified_namespace_lookup (name, 0, &k.namespaces);
3809
3810   arg_assoc_args (&k, args);
3811   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, k.functions);
3812 }
3813
3814 /* Process a namespace-alias declaration.  */
3815
3816 void
3817 do_namespace_alias (tree alias, tree namespace)
3818 {
3819   if (TREE_CODE (namespace) != NAMESPACE_DECL)
3820     {
3821       /* The parser did not find it, so it's not there.  */
3822       error ("unknown namespace `%D'", namespace);
3823       return;
3824     }
3825
3826   namespace = ORIGINAL_NAMESPACE (namespace);
3827
3828   /* Build the alias.  */
3829   alias = build_lang_decl (NAMESPACE_DECL, alias, void_type_node);     
3830   DECL_NAMESPACE_ALIAS (alias) = namespace;
3831   DECL_EXTERNAL (alias) = 1;
3832   pushdecl (alias);
3833 }
3834
3835 /* Check a non-member using-declaration. Return the name and scope
3836    being used, and the USING_DECL, or NULL_TREE on failure.  */
3837
3838 static tree
3839 validate_nonmember_using_decl (tree decl, tree *scope, tree *name)
3840 {
3841   *scope = global_namespace;
3842   *name = NULL_TREE;
3843
3844   if (TREE_CODE (decl) == TEMPLATE_ID_EXPR)
3845     {
3846       *name = TREE_OPERAND (decl, 0);
3847       /* 7.3.3/5
3848            A using-declaration shall not name a template-id.  */
3849       error ("a using-declaration cannot specify a template-id.  Try `using %D'", *name);
3850       return NULL_TREE;
3851     }
3852
3853   if (TREE_CODE (decl) == NAMESPACE_DECL)
3854     {
3855       error ("namespace `%D' not allowed in using-declaration", decl);
3856       return NULL_TREE;
3857     }
3858
3859   if (TREE_CODE (decl) == SCOPE_REF)
3860     {
3861       /* It's a nested name with template parameter dependent scope.
3862          This can only be using-declaration for class member.  */
3863       error ("`%T' is not a namespace", TREE_OPERAND (decl, 0));
3864       return NULL_TREE;
3865     }
3866
3867   if (is_overloaded_fn (decl))
3868     decl = get_first_fn (decl);
3869
3870   my_friendly_assert (DECL_P (decl), 20020908);
3871
3872   if (TREE_CODE (decl) == CONST_DECL)
3873     /* Enumeration constants to not have DECL_CONTEXT set.  */
3874     *scope = TYPE_CONTEXT (TREE_TYPE (decl));
3875   else
3876     *scope = DECL_CONTEXT (decl);
3877   if (!*scope)
3878     *scope = global_namespace;
3879
3880   /* [namespace.udecl]
3881        A using-declaration for a class member shall be a
3882        member-declaration.  */
3883   if (TYPE_P (*scope))
3884     {
3885       error ("`%T' is not a namespace", *scope);
3886       return NULL_TREE;
3887     }
3888   *name = DECL_NAME (decl);
3889   /* Make a USING_DECL.  */
3890   return push_using_decl (*scope, *name);
3891 }
3892
3893 /* Process local and global using-declarations.  */
3894
3895 static void
3896 do_nonmember_using_decl (tree scope, tree name, tree oldval, tree oldtype,
3897                          tree *newval, tree *newtype)
3898 {
3899   cxx_binding decls;
3900
3901   *newval = *newtype = NULL_TREE;
3902   cxx_binding_clear (&decls);
3903   if (!qualified_lookup_using_namespace (name, scope, &decls, 0))
3904     /* Lookup error */
3905     return;
3906
3907   if (!decls.value && !decls.type)
3908     {
3909       error ("`%D' not declared", name);
3910       return;
3911     }
3912
3913   /* Check for using functions.  */
3914   if (decls.value && is_overloaded_fn (decls.value))
3915     {
3916       tree tmp, tmp1;
3917
3918       if (oldval && !is_overloaded_fn (oldval))
3919         {
3920           if (!DECL_IMPLICIT_TYPEDEF_P (oldval))
3921             error ("`%D' is already declared in this scope", name);
3922           oldval = NULL_TREE;
3923         }
3924
3925       *newval = oldval;
3926       for (tmp = decls.value; tmp; tmp = OVL_NEXT (tmp))
3927         {
3928           tree new_fn = OVL_CURRENT (tmp);
3929
3930           /* [namespace.udecl]
3931
3932              If a function declaration in namespace scope or block
3933              scope has the same name and the same parameter types as a
3934              function introduced by a using declaration the program is
3935              ill-formed.  */
3936           for (tmp1 = oldval; tmp1; tmp1 = OVL_NEXT (tmp1))
3937             {
3938               tree old_fn = OVL_CURRENT (tmp1);
3939
3940               if (new_fn == old_fn)
3941                 /* The function already exists in the current namespace.  */
3942                 break;
3943               else if (OVL_USED (tmp1))
3944                 continue; /* this is a using decl */
3945               else if (compparms (TYPE_ARG_TYPES (TREE_TYPE (new_fn)),
3946                                   TYPE_ARG_TYPES (TREE_TYPE (old_fn))))
3947                 {
3948                   /* There was already a non-using declaration in
3949                      this scope with the same parameter types. If both
3950                      are the same extern "C" functions, that's ok.  */
3951                   if (decls_match (new_fn, old_fn))
3952                     {
3953                       /* If the OLD_FN was a builtin, there is now a
3954                          real declaration.  */
3955                       if (DECL_ANTICIPATED (old_fn))
3956                         DECL_ANTICIPATED (old_fn) = 0;
3957                       break;
3958                     }
3959                   else if (!DECL_ANTICIPATED (old_fn))
3960                     {
3961                       /* If the OLD_FN was really declared, the
3962                          declarations don't match.  */
3963                       error ("`%D' is already declared in this scope", name);
3964                       break;
3965                     }
3966
3967                   /* If the OLD_FN was not really there, just ignore
3968                      it and keep going.  */
3969                 }
3970             }
3971
3972           /* If we broke out of the loop, there's no reason to add
3973              this function to the using declarations for this
3974              scope.  */
3975           if (tmp1)
3976             continue;
3977             
3978           *newval = build_overload (OVL_CURRENT (tmp), *newval);
3979           if (TREE_CODE (*newval) != OVERLOAD)
3980             *newval = ovl_cons (*newval, NULL_TREE);
3981           OVL_USED (*newval) = 1;
3982         }
3983     }
3984   else 
3985     {
3986       *newval = decls.value;
3987       if (oldval && !decls_match (*newval, oldval))
3988         error ("`%D' is already declared in this scope", name);
3989     }
3990
3991   *newtype = decls.type;
3992   if (oldtype && *newtype && !same_type_p (oldtype, *newtype))
3993     {
3994       error ("using declaration `%D' introduced ambiguous type `%T'",
3995                 name, oldtype);
3996       return;
3997     }
3998 }
3999
4000 /* Process a using-declaration not appearing in class or local scope.  */
4001
4002 void
4003 do_toplevel_using_decl (tree decl)
4004 {
4005   tree scope, name;
4006   tree oldval, oldtype, newval, newtype;
4007   cxx_binding *binding;
4008
4009   decl = validate_nonmember_using_decl (decl, &scope, &name);
4010   if (decl == NULL_TREE)
4011     return;
4012   
4013   binding = binding_for_name (NAMESPACE_LEVEL (current_namespace), name);
4014
4015   oldval = BINDING_VALUE (binding);
4016   oldtype = BINDING_TYPE (binding);
4017
4018   do_nonmember_using_decl (scope, name, oldval, oldtype, &newval, &newtype);
4019
4020   /* Copy declarations found.  */
4021   if (newval)
4022     BINDING_VALUE (binding) = newval;
4023   if (newtype)
4024     BINDING_TYPE (binding) = newtype;
4025   return;
4026 }
4027
4028 /* Process a using-declaration at function scope.  */
4029
4030 void
4031 do_local_using_decl (tree decl)
4032 {
4033   tree scope, name;
4034   tree oldval, oldtype, newval, newtype;
4035
4036   decl = validate_nonmember_using_decl (decl, &scope, &name);
4037   if (decl == NULL_TREE)
4038     return;
4039
4040   if (building_stmt_tree ()
4041       && at_function_scope_p ())
4042     add_decl_stmt (decl);
4043
4044   oldval = lookup_name_current_level (name);
4045   oldtype = lookup_type_current_level (name);
4046
4047   do_nonmember_using_decl (scope, name, oldval, oldtype, &newval, &newtype);
4048
4049   if (newval)
4050     {
4051       if (is_overloaded_fn (newval))
4052         {
4053           tree fn, term;
4054
4055           /* We only need to push declarations for those functions
4056              that were not already bound in the current level.
4057              The old value might be NULL_TREE, it might be a single
4058              function, or an OVERLOAD.  */
4059           if (oldval && TREE_CODE (oldval) == OVERLOAD)
4060             term = OVL_FUNCTION (oldval);
4061           else
4062             term = oldval;
4063           for (fn = newval; fn && OVL_CURRENT (fn) != term; 
4064                fn = OVL_NEXT (fn))
4065             push_overloaded_decl (OVL_CURRENT (fn), 
4066                                   PUSH_LOCAL | PUSH_USING);
4067         }
4068       else
4069         push_local_binding (name, newval, PUSH_USING);
4070     }
4071   if (newtype)
4072     set_identifier_type_value (name, newtype);
4073 }
4074
4075 tree
4076 do_class_using_decl (tree decl)
4077 {
4078   tree name, value;
4079
4080   if (TREE_CODE (decl) != SCOPE_REF
4081       || !TREE_OPERAND (decl, 0)
4082       || !TYPE_P (TREE_OPERAND (decl, 0)))
4083     {
4084       error ("using-declaration for non-member at class scope");
4085       return NULL_TREE;
4086     }
4087   name = TREE_OPERAND (decl, 1);
4088   if (TREE_CODE (name) == BIT_NOT_EXPR)
4089     {
4090       error ("using-declaration for destructor");
4091       return NULL_TREE;
4092     }
4093   else if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
4094     {
4095       name = TREE_OPERAND (name, 0);
4096       error ("a using-declaration cannot specify a template-id.  Try  `using %T::%D'", TREE_OPERAND (decl, 0), name);
4097       return NULL_TREE;
4098     }
4099   if (TREE_CODE (name) == TYPE_DECL)
4100     {
4101       tree type = TREE_TYPE (name);
4102       if (CLASSTYPE_USE_TEMPLATE (TREE_TYPE (name)))
4103         {
4104           name = DECL_NAME (CLASSTYPE_TI_TEMPLATE (type));
4105           error ("a using-declaration cannot specify a template-id.");
4106           return NULL_TREE;
4107         }
4108       name = DECL_NAME (name);
4109     }
4110   else if (TREE_CODE (name) == TEMPLATE_DECL)
4111      name = DECL_NAME (name);
4112   else if (BASELINK_P (name))
4113     {
4114       tree fns;
4115
4116       fns = BASELINK_FUNCTIONS (name);
4117       if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
4118         {
4119           fns = TREE_OPERAND (fns, 0);
4120           error ("a using-declaration cannot specify a template-id.  Try  `using %T::%D'", 
4121                  BASELINK_ACCESS_BINFO (name),
4122                  DECL_NAME (get_first_fn (fns)));
4123         }
4124       name = DECL_NAME (get_first_fn (fns));
4125     }
4126
4127   my_friendly_assert (TREE_CODE (name) == IDENTIFIER_NODE, 980716);
4128
4129   value = build_lang_decl (USING_DECL, name, void_type_node);
4130   DECL_INITIAL (value) = TREE_OPERAND (decl, 0);
4131   return value;
4132 }
4133
4134 /* Process a using-directive.  */
4135
4136 void
4137 do_using_directive (tree namespace)
4138 {
4139   if (building_stmt_tree ())
4140     add_stmt (build_stmt (USING_STMT, namespace));
4141   
4142   /* using namespace A::B::C; */
4143   if (TREE_CODE (namespace) == SCOPE_REF)
4144       namespace = TREE_OPERAND (namespace, 1);
4145   if (TREE_CODE (namespace) == IDENTIFIER_NODE)
4146     {
4147       /* Lookup in lexer did not find a namespace.  */
4148       if (!processing_template_decl)
4149         error ("namespace `%T' undeclared", namespace);
4150       return;
4151     }
4152   if (TREE_CODE (namespace) != NAMESPACE_DECL)
4153     {
4154       if (!processing_template_decl)
4155         error ("`%T' is not a namespace", namespace);
4156       return;
4157     }
4158   namespace = ORIGINAL_NAMESPACE (namespace);
4159   if (!toplevel_bindings_p ())
4160     push_using_directive (namespace);
4161   else
4162     /* direct usage */
4163     add_using_namespace (current_namespace, namespace, 0);
4164 }
4165
4166 void
4167 check_default_args (tree x)
4168 {
4169   tree arg = TYPE_ARG_TYPES (TREE_TYPE (x));
4170   bool saw_def = false;
4171   int i = 0 - (TREE_CODE (TREE_TYPE (x)) == METHOD_TYPE);
4172   for (; arg && arg != void_list_node; arg = TREE_CHAIN (arg), ++i)
4173     {
4174       if (TREE_PURPOSE (arg))
4175         saw_def = true;
4176       else if (saw_def)
4177         {
4178           cp_error_at ("default argument missing for parameter %P of `%+#D'",
4179                        i, x);
4180           break;
4181         }
4182     }
4183 }
4184
4185 void
4186 mark_used (tree decl)
4187 {
4188   TREE_USED (decl) = 1;
4189   if (processing_template_decl || skip_evaluation)
4190     return;
4191
4192   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_DECLARED_INLINE_P (decl)
4193       && !TREE_ASM_WRITTEN (decl))
4194     /* Remember it, so we can check it was defined.  */
4195     defer_fn (decl);
4196
4197   assemble_external (decl);
4198
4199   /* Is it a synthesized method that needs to be synthesized?  */
4200   if (TREE_CODE (decl) == FUNCTION_DECL
4201       && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
4202       && DECL_ARTIFICIAL (decl) 
4203       && !DECL_THUNK_P (decl)
4204       && ! DECL_INITIAL (decl)
4205       /* Kludge: don't synthesize for default args.  */
4206       && current_function_decl)
4207     {
4208       synthesize_method (decl);
4209       /* If we've already synthesized the method we don't need to
4210          instantiate it, so we can return right away.  */
4211       return;
4212     }
4213
4214   /* If this is a function or variable that is an instance of some
4215      template, we now know that we will need to actually do the
4216      instantiation. We check that DECL is not an explicit
4217      instantiation because that is not checked in instantiate_decl.  */
4218   if ((DECL_NON_THUNK_FUNCTION_P (decl) || TREE_CODE (decl) == VAR_DECL)
4219       && DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
4220       && (!DECL_EXPLICIT_INSTANTIATION (decl)
4221           || (TREE_CODE (decl) == FUNCTION_DECL 
4222               && DECL_INLINE (DECL_TEMPLATE_RESULT 
4223                               (template_for_substitution (decl))))))
4224     {
4225       bool defer;
4226
4227       /* Normally, we put off instantiating functions in order to
4228          improve compile times.  Maintaining a stack of active
4229          functions is expensive, and the inliner knows to
4230          instantiate any functions it might need.
4231
4232          However, if instantiating this function might help us mark
4233          the current function TREE_NOTHROW, we go ahead and
4234          instantiate it now.  */
4235       defer = (!flag_exceptions
4236                || TREE_CODE (decl) != FUNCTION_DECL
4237                /* If the called function can't throw, we don't need to
4238                   generate its body to find that out.  */
4239                || TREE_NOTHROW (decl)
4240                || !cfun
4241                /* If we already know the current function can't throw,
4242                   then we don't need to work hard to prove it.  */
4243                || TREE_NOTHROW (current_function_decl)
4244                /* If we already know that the current function *can*
4245                   throw, there's no point in gathering more
4246                   information.  */
4247                || cp_function_chain->can_throw);
4248
4249       instantiate_decl (decl, defer);
4250     }
4251 }
4252
4253 /* Called when a class-head is encountered.  TAG_KIND is the class-key
4254    for the class.  SCOPE, if non-NULL, is the type or namespace
4255    indicated in the nested-name-specifier for the declaration of the
4256    class.  ID is the name of the class, if any; it may be a TYPE_DECL,
4257    or an IDENTIFIER_NODE.  ATTRIBUTES are attributes that apply to the
4258    class.
4259
4260    Return a TYPE_DECL for the class being defined.  */
4261
4262 tree
4263 handle_class_head (enum tag_types tag_kind, tree scope, tree id,
4264                    tree attributes)
4265 {
4266   tree decl = NULL_TREE;
4267   tree current = current_scope ();
4268   bool xrefd_p = false;
4269   bool new_type_p;
4270   tree context;
4271
4272   if (current == NULL_TREE)
4273     current = current_namespace;
4274
4275   if (scope)
4276     {
4277       if (TREE_CODE (id) == TYPE_DECL)
4278         /* We must bash typedefs back to the main decl of the
4279            type. Otherwise we become confused about scopes.  */
4280         decl = TYPE_MAIN_DECL (TREE_TYPE (id));
4281       else if (DECL_CLASS_TEMPLATE_P (id))
4282         decl = DECL_TEMPLATE_RESULT (id);
4283       else
4284         {
4285           if (TYPE_P (scope))
4286             {
4287               /* According to the suggested resolution of core issue
4288                  180, 'typename' is assumed after a class-key.  */
4289               decl = make_typename_type (scope, id, tf_error);
4290               if (decl != error_mark_node)
4291                 decl = TYPE_MAIN_DECL (decl);
4292               else
4293                 decl = NULL_TREE;
4294             }
4295           else if (scope == current)
4296             {
4297               /* We've been given AGGR SCOPE::ID, when we're already
4298                  inside SCOPE.  Be nice about it.  */
4299               if (pedantic)
4300                 pedwarn ("extra qualification `%T::' on member `%D' ignored",
4301                          scope, id);
4302             }
4303           else
4304             error ("`%T' does not have a class or union named `%D'",
4305                    scope, id);
4306         }
4307     }
4308   
4309   if (!decl)
4310     {
4311       decl = xref_tag (tag_kind, id, attributes, false);
4312       if (decl == error_mark_node)
4313         return error_mark_node;
4314       decl = TYPE_MAIN_DECL (decl);
4315       xrefd_p = true;
4316     }
4317
4318   if (!TYPE_BINFO (TREE_TYPE (decl)))
4319     {
4320       error ("`%T' is not a class or union type", decl);
4321       return error_mark_node;
4322     }
4323   
4324   /* For a definition, we want to enter the containing scope before
4325      looking up any base classes etc. Only do so, if this is different
4326      to the current scope.  */
4327   context = CP_DECL_CONTEXT (decl);
4328   
4329   new_type_p = (current != context
4330                 && TREE_CODE (context) != TEMPLATE_TYPE_PARM
4331                 && TREE_CODE (context) != BOUND_TEMPLATE_TEMPLATE_PARM);
4332   if (new_type_p)
4333     push_scope (context);
4334   
4335   if (!xrefd_p 
4336       && PROCESSING_REAL_TEMPLATE_DECL_P ()
4337       && !CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
4338     decl = push_template_decl (decl);
4339
4340   return decl;
4341 }
4342
4343 #include "gt-cp-decl2.h"