OSDN Git Service

ff6ae1ecd7c1a989301a5dfa1fe3d343db45d333
[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 Free Software Foundation, Inc.
4    Hacked by Michael Tiemann (tiemann@cygnus.com)
5
6 This file is part of GNU CC.
7
8 GNU CC 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 GNU CC 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 GNU CC; 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 "tree.h"
34 #include "rtl.h"
35 #include "expr.h"
36 #include "flags.h"
37 #include "cp-tree.h"
38 #include "decl.h"
39 #include "lex.h"
40 #include "output.h"
41 #include "except.h"
42 #include "toplev.h"
43 #include "ggc.h"
44 #include "timevar.h"
45 #include "cpplib.h"
46 #include "target.h"
47 extern cpp_reader *parse_in;
48
49 /* This structure contains information about the initializations
50    and/or destructions required for a particular priority level.  */
51 typedef struct priority_info_s {
52   /* Non-zero if there have been any initializations at this priority
53      throughout the translation unit.  */
54   int initializations_p;
55   /* Non-zero if there have been any destructions at this priority
56      throughout the translation unit.  */
57   int destructions_p;
58 } *priority_info;
59
60 static void mark_vtable_entries PARAMS ((tree));
61 static void grok_function_init PARAMS ((tree, tree));
62 static int finish_vtable_vardecl PARAMS ((tree *, void *));
63 static int prune_vtable_vardecl PARAMS ((tree *, void *));
64 static int is_namespace_ancestor PARAMS ((tree, tree));
65 static void add_using_namespace PARAMS ((tree, tree, int));
66 static tree ambiguous_decl PARAMS ((tree, tree, tree,int));
67 static tree build_anon_union_vars PARAMS ((tree, tree*, int, int));
68 static int acceptable_java_type PARAMS ((tree));
69 static void output_vtable_inherit PARAMS ((tree));
70 static tree start_objects PARAMS ((int, int));
71 static void finish_objects PARAMS ((int, int, tree));
72 static tree merge_functions PARAMS ((tree, tree));
73 static tree decl_namespace PARAMS ((tree));
74 static tree validate_nonmember_using_decl PARAMS ((tree, tree *, tree *));
75 static void do_nonmember_using_decl PARAMS ((tree, tree, tree, tree,
76                                            tree *, tree *));
77 static tree start_static_storage_duration_function PARAMS ((void));
78 static void finish_static_storage_duration_function PARAMS ((tree));
79 static priority_info get_priority_info PARAMS ((int));
80 static void do_static_initialization PARAMS ((tree, tree));
81 static void do_static_destruction PARAMS ((tree));
82 static tree start_static_initialization_or_destruction PARAMS ((tree, int));
83 static void finish_static_initialization_or_destruction PARAMS ((tree));
84 static void generate_ctor_or_dtor_function PARAMS ((int, int));
85 static int generate_ctor_and_dtor_functions_for_priority
86                                   PARAMS ((splay_tree_node, void *));
87 static tree prune_vars_needing_no_initialization PARAMS ((tree));
88 static void write_out_vars PARAMS ((tree));
89 static void import_export_class PARAMS ((tree));
90 static tree key_method PARAMS ((tree));
91 static int compare_options PARAMS ((const PTR, const PTR));
92 static tree get_guard_bits PARAMS ((tree));
93
94 /* A list of static class variables.  This is needed, because a
95    static class variable can be declared inside the class without
96    an initializer, and then initialized, statically, outside the class.  */
97 static varray_type pending_statics;
98 #define pending_statics_used \
99   (pending_statics ? pending_statics->elements_used : 0)
100
101 /* A list of functions which were declared inline, but which we
102    may need to emit outline anyway.  */
103 static varray_type deferred_fns;
104 #define deferred_fns_used \
105   (deferred_fns ? deferred_fns->elements_used : 0)
106
107 /* Flag used when debugging spew.c */
108
109 extern int spew_debug;
110
111 /* Nonzero if we're done parsing and into end-of-file activities.  */
112
113 int at_eof;
114
115 /* Functions called along with real static constructors and destructors.  */
116
117 tree static_ctors;
118 tree static_dtors;
119
120 /* The :: namespace. */
121
122 tree global_namespace;
123 \f
124 /* C (and C++) language-specific option variables.  */
125
126 /* Nonzero means don't recognize the keyword `asm'.  */
127
128 int flag_no_asm;
129
130 /* Nonzero means don't recognize any extension keywords.  */
131
132 int flag_no_gnu_keywords;
133
134 /* Nonzero means to treat bitfields as unsigned unless they say `signed'.  */
135
136 int flag_signed_bitfields = 1;
137
138 /* Nonzero means enable obscure standard features and disable GNU
139    extensions that might cause standard-compliant code to be
140    miscompiled.  */
141
142 int flag_ansi;
143
144 /* Nonzero means do emit exported implementations of functions even if
145    they can be inlined.  */
146
147 int flag_implement_inlines = 1;
148
149 /* Nonzero means do emit exported implementations of templates, instead of
150    multiple static copies in each file that needs a definition.  */
151
152 int flag_external_templates;
153
154 /* Nonzero means that the decision to emit or not emit the implementation of a
155    template depends on where the template is instantiated, rather than where
156    it is defined.  */
157
158 int flag_alt_external_templates;
159
160 /* Nonzero means that implicit instantiations will be emitted if needed.  */
161
162 int flag_implicit_templates = 1;
163
164 /* Nonzero means that implicit instantiations of inline templates will be
165    emitted if needed, even if instantiations of non-inline templates
166    aren't.  */
167
168 int flag_implicit_inline_templates = 1;
169
170 /* Nonzero means warn about implicit declarations.  */
171
172 int warn_implicit = 1;
173
174 /* Nonzero means warn about usage of long long when `-pedantic'.  */
175
176 int warn_long_long = 1;
177
178 /* Nonzero means warn when all ctors or dtors are private, and the class
179    has no friends.  */
180
181 int warn_ctor_dtor_privacy = 1;
182
183 /* Nonzero means generate separate instantiation control files and juggle
184    them at link time.  */
185
186 int flag_use_repository;
187
188 /* Nonzero if we want to issue diagnostics that the standard says are not
189    required.  */
190
191 int flag_optional_diags = 1;
192
193 /* Nonzero means give string constants the type `const char *', as mandated
194    by the standard.  */
195
196 int flag_const_strings = 1;
197
198 /* Nonzero means warn about deprecated conversion from string constant to
199    `char *'.  */
200
201 int warn_write_strings;
202
203 /* Nonzero means warn about pointer casts that can drop a type qualifier
204    from the pointer target type.  */
205
206 int warn_cast_qual;
207
208 /* Nonzero means warn about sizeof(function) or addition/subtraction
209    of function pointers.  */
210
211 int warn_pointer_arith = 1;
212
213 /* Nonzero means warn for any function def without prototype decl.  */
214
215 int warn_missing_prototypes;
216
217 /* Nonzero means warn about multiple (redundant) decls for the same single
218    variable or function.  */
219
220 int warn_redundant_decls;
221
222 /* Warn if initializer is not completely bracketed.  */
223
224 int warn_missing_braces;
225
226 /* Warn about comparison of signed and unsigned values.  */
227
228 int warn_sign_compare;
229
230 /* Warn about testing equality of floating point numbers. */
231
232 int warn_float_equal = 0;
233
234 /* Warn about functions which might be candidates for format attributes.  */
235
236 int warn_missing_format_attribute;
237
238 /* Warn about a subscript that has type char.  */
239
240 int warn_char_subscripts;
241
242 /* Warn if a type conversion is done that might have confusing results.  */
243
244 int warn_conversion;
245
246 /* Warn if adding () is suggested.  */
247
248 int warn_parentheses;
249
250 /* Non-zero means warn in function declared in derived class has the
251    same name as a virtual in the base class, but fails to match the
252    type signature of any virtual function in the base class.  */
253
254 int warn_overloaded_virtual;
255
256 /* Non-zero means warn when declaring a class that has a non virtual
257    destructor, when it really ought to have a virtual one.  */
258
259 int warn_nonvdtor;
260
261 /* Non-zero means warn when the compiler will reorder code.  */
262
263 int warn_reorder;
264
265 /* Non-zero means warn when synthesis behavior differs from Cfront's.  */
266
267 int warn_synth;
268
269 /* Non-zero means warn when we convert a pointer to member function
270    into a pointer to (void or function).  */
271
272 int warn_pmf2ptr = 1;
273
274 /* Nonzero means warn about violation of some Effective C++ style rules.  */
275
276 int warn_ecpp;
277
278 /* Nonzero means warn where overload resolution chooses a promotion from
279    unsigned to signed over a conversion to an unsigned of the same size.  */
280
281 int warn_sign_promo;
282
283 /* Nonzero means warn when an old-style cast is used.  */
284
285 int warn_old_style_cast;
286
287 /* Warn about #pragma directives that are not recognised.  */      
288
289 int warn_unknown_pragmas; /* Tri state variable.  */  
290
291 /* Nonzero means warn about use of multicharacter literals.  */
292
293 int warn_multichar = 1;
294
295 /* Nonzero means warn when non-templatized friend functions are
296    declared within a template */
297
298 int warn_nontemplate_friend = 1;
299
300 /* Nonzero means complain about deprecated features.  */
301
302 int warn_deprecated = 1;
303
304 /* Nonzero means `$' can be in an identifier.  */
305
306 #ifndef DOLLARS_IN_IDENTIFIERS
307 #define DOLLARS_IN_IDENTIFIERS 1
308 #endif
309 int dollars_in_ident = DOLLARS_IN_IDENTIFIERS;
310
311 /* Nonzero means allow Microsoft extensions without a pedwarn.  */
312
313 int flag_ms_extensions;
314
315 /* C++ specific flags.  */   
316
317 /* Nonzero means we should attempt to elide constructors when possible.  */
318
319 int flag_elide_constructors = 1;
320
321 /* Nonzero means that member functions defined in class scope are
322    inline by default.  */
323
324 int flag_default_inline = 1;
325
326 /* Controls whether compiler generates 'type descriptor' that give
327    run-time type information.  */
328
329 int flag_rtti = 1;
330
331 /* Nonzero if we want to support huge (> 2^(sizeof(short)*8-1) bytes)
332    objects.  */
333
334 int flag_huge_objects;
335
336 /* Nonzero if we want to conserve space in the .o files.  We do this
337    by putting uninitialized data and runtime initialized data into
338    .common instead of .data at the expense of not flagging multiple
339    definitions.  */
340
341 int flag_conserve_space;
342
343 /* Nonzero if we want to obey access control semantics.  */
344
345 int flag_access_control = 1;
346
347 /* Nonzero if we want to understand the operator names, i.e. 'bitand'.  */
348
349 int flag_operator_names = 1;
350
351 /* Nonzero if we want to check the return value of new and avoid calling
352    constructors if it is a null pointer.  */
353
354 int flag_check_new;
355
356 /* Nonzero if we want the new ISO rules for pushing a new scope for `for'
357    initialization variables.
358    0: Old rules, set by -fno-for-scope.
359    2: New ISO rules, set by -ffor-scope.
360    1: Try to implement new ISO rules, but with backup compatibility
361    (and warnings).  This is the default, for now.  */
362
363 int flag_new_for_scope = 1;
364
365 /* Nonzero if we want to emit defined symbols with common-like linkage as
366    weak symbols where possible, in order to conform to C++ semantics.
367    Otherwise, emit them as local symbols.  */
368
369 int flag_weak = 1;
370
371 /* Nonzero to use __cxa_atexit, rather than atexit, to register
372    destructors for local statics and global objects.  */
373
374 int flag_use_cxa_atexit;
375
376 /* Maximum template instantiation depth.  This limit is rather
377    arbitrary, but it exists to limit the time it takes to notice
378    infinite template instantiations.  */
379
380 int max_tinst_depth = 500;
381
382 /* Nonzero means output .vtable_{entry,inherit} for use in doing vtable gc.  */
383
384 int flag_vtable_gc;
385
386 /* Nonzero means make the default pedwarns warnings instead of errors.
387    The value of this flag is ignored if -pedantic is specified.  */
388
389 int flag_permissive;
390
391 /* Nonzero means to implement standard semantics for exception
392    specifications, calling unexpected if an exception is thrown that
393    doesn't match the specification.  Zero means to treat them as
394    assertions and optimize accordingly, but not check them.  */
395
396 int flag_enforce_eh_specs = 1;
397
398 /* Table of language-dependent -f options.
399    STRING is the option name.  VARIABLE is the address of the variable.
400    ON_VALUE is the value to store in VARIABLE
401     if `-fSTRING' is seen as an option.
402    (If `-fno-STRING' is seen as an option, the opposite value is stored.)  */
403
404 static const struct { const char *const string; int *const variable; const int on_value;}
405 lang_f_options[] =
406 {
407   /* C/C++ options.  */
408   {"signed-char", &flag_signed_char, 1},
409   {"unsigned-char", &flag_signed_char, 0},
410   {"signed-bitfields", &flag_signed_bitfields, 1},
411   {"unsigned-bitfields", &flag_signed_bitfields, 0},
412   {"short-enums", &flag_short_enums, 1},
413   {"short-double", &flag_short_double, 1},
414   {"short-wchar", &flag_short_wchar, 1},
415   {"asm", &flag_no_asm, 0},
416   {"builtin", &flag_no_builtin, 0},
417
418   /* C++-only options.  */
419   {"access-control", &flag_access_control, 1},
420   {"check-new", &flag_check_new, 1},
421   {"conserve-space", &flag_conserve_space, 1},
422   {"const-strings", &flag_const_strings, 1},
423   {"default-inline", &flag_default_inline, 1},
424   {"dollars-in-identifiers", &dollars_in_ident, 1},
425   {"elide-constructors", &flag_elide_constructors, 1},
426   {"enforce-eh-specs", &flag_enforce_eh_specs, 1},
427   {"external-templates", &flag_external_templates, 1},
428   {"for-scope", &flag_new_for_scope, 2},
429   {"gnu-keywords", &flag_no_gnu_keywords, 0},
430   {"handle-exceptions", &flag_exceptions, 1},
431   {"implement-inlines", &flag_implement_inlines, 1},
432   {"implicit-inline-templates", &flag_implicit_inline_templates, 1},
433   {"implicit-templates", &flag_implicit_templates, 1},
434   {"ms-extensions", &flag_ms_extensions, 1},
435   {"nonansi-builtins", &flag_no_nonansi_builtin, 0},
436   {"operator-names", &flag_operator_names, 1},
437   {"optional-diags", &flag_optional_diags, 1},
438   {"permissive", &flag_permissive, 1},
439   {"repo", &flag_use_repository, 1},
440   {"rtti", &flag_rtti, 1},
441   {"stats", &flag_detailed_statistics, 1},
442   {"vtable-gc", &flag_vtable_gc, 1},
443   {"use-cxa-atexit", &flag_use_cxa_atexit, 1},
444   {"weak", &flag_weak, 1}
445 };
446
447 /* The list of `-f' options that we no longer support.  The `-f'
448    prefix is not given in this table.  The `-fno-' variants are not
449    listed here.  This table must be kept in alphabetical order.  */
450 static const char * const unsupported_options[] = {
451   "all-virtual",
452   "cond-mismatch",
453   "enum-int-equiv",
454   "guiding-decls",
455   "honor-std",
456   "huge-objects",
457   "labels-ok",
458   "new-abi",
459   "nonnull-objects",
460   "squangle",
461   "strict-prototype",
462   "this-is-variable",
463   "vtable-thunks",
464   "xref"
465 };
466
467 /* Compare two option strings, pointed two by P1 and P2, for use with
468    bsearch.  */
469
470 static int
471 compare_options (p1, p2)
472      const PTR p1;
473      const PTR p2;
474 {
475   return strcmp (*((const char *const *) p1), *((const char *const *) p2));
476 }
477
478 /* Decode the string P as a language-specific option.
479    Return the number of strings consumed for a valid option.
480    Otherwise return 0.  Should not complain if it does not
481    recognise the option.  */
482
483 int   
484 cxx_decode_option (argc, argv)
485      int argc;
486      char **argv;
487 {
488   int strings_processed;
489   const char *p = argv[0];
490
491   strings_processed = cpp_handle_option (parse_in, argc, argv, 0);
492
493   if (p[0] == '-' && p[1] == 'f')
494     {
495       /* Some kind of -f option.
496          P's value is the option sans `-f'.
497          Search for it in the table of options.  */
498       const char *option_value = NULL;
499       const char *positive_option;
500       size_t j;
501
502       p += 2;
503       /* Try special -f options.  */
504
505       /* See if this is one of the options no longer supported.  We
506          used to support these options, so we continue to accept them,
507          with a warning.  */
508       if (strncmp (p, "no-", strlen ("no-")) == 0)
509         positive_option = p + strlen ("no-");
510       else
511         positive_option = p;
512
513       /* If the option is present, issue a warning.  Indicate to our
514          caller that the option was processed successfully.  */
515       if (bsearch (&positive_option, 
516                    unsupported_options, 
517                    (sizeof (unsupported_options) 
518                     / sizeof (unsupported_options[0])),
519                    sizeof (unsupported_options[0]),
520                    compare_options))
521         {
522           warning ("-f%s is no longer supported", p);
523           return 1;
524         }
525
526       if (!strcmp (p, "handle-exceptions")
527           || !strcmp (p, "no-handle-exceptions"))
528         warning ("-fhandle-exceptions has been renamed to -fexceptions (and is now on by default)");
529       else if (! strcmp (p, "alt-external-templates"))
530         {
531           flag_external_templates = 1;
532           flag_alt_external_templates = 1;
533           cp_deprecated ("-falt-external-templates");
534         }
535       else if (! strcmp (p, "no-alt-external-templates"))
536         flag_alt_external_templates = 0;
537       else if (!strcmp (p, "repo"))
538         {
539           flag_use_repository = 1;
540           flag_implicit_templates = 0;
541         }
542       else if (!strcmp (p, "external-templates"))
543         {
544           flag_external_templates = 1;
545           cp_deprecated ("-fexternal-templates");
546         }
547       else if ((option_value
548                 = skip_leading_substring (p, "template-depth-")))
549         max_tinst_depth
550           = read_integral_parameter (option_value, p - 2, max_tinst_depth);
551       else if ((option_value
552                 = skip_leading_substring (p, "name-mangling-version-")))
553         {
554           warning ("-fname-mangling-version is no longer supported");
555           return 1;
556         }
557       else if (dump_switch_p (p))
558         ;
559       else 
560         {
561           int found = 0;
562
563           for (j = 0;
564                !found && j < (sizeof (lang_f_options) 
565                               / sizeof (lang_f_options[0]));
566                j++)
567             {
568               if (!strcmp (p, lang_f_options[j].string))
569                 {
570                   *lang_f_options[j].variable = lang_f_options[j].on_value;
571                   /* A goto here would be cleaner,
572                      but breaks the VAX pcc.  */
573                   found = 1;
574                 }
575               else if (p[0] == 'n' && p[1] == 'o' && p[2] == '-'
576                        && ! strcmp (p+3, lang_f_options[j].string))
577                 {
578                   *lang_f_options[j].variable = ! lang_f_options[j].on_value;
579                   found = 1;
580                 }
581             }
582
583           return found;
584         }
585     }
586   else if (p[0] == '-' && p[1] == 'W')
587     {
588       int setting = 1;
589
590       /* The -W options control the warning behavior of the compiler.  */
591       p += 2;
592
593       if (p[0] == 'n' && p[1] == 'o' && p[2] == '-')
594         setting = 0, p += 3;
595
596       if (!strcmp (p, "implicit"))
597         warn_implicit = setting;
598       else if (!strcmp (p, "long-long"))
599         warn_long_long = setting;
600       else if (!strcmp (p, "return-type"))
601         warn_return_type = setting;
602       else if (!strcmp (p, "ctor-dtor-privacy"))
603         warn_ctor_dtor_privacy = setting;
604       else if (!strcmp (p, "write-strings"))
605         warn_write_strings = setting;
606       else if (!strcmp (p, "cast-qual"))
607         warn_cast_qual = setting;
608       else if (!strcmp (p, "char-subscripts"))
609         warn_char_subscripts = setting;
610       else if (!strcmp (p, "pointer-arith"))
611         warn_pointer_arith = setting;
612       else if (!strcmp (p, "missing-prototypes"))
613         warn_missing_prototypes = setting;
614       else if (!strcmp (p, "strict-prototypes"))
615         {
616           if (setting == 0)
617             warning ("-Wno-strict-prototypes is not supported in C++");
618         }
619       else if (!strcmp (p, "redundant-decls"))
620         warn_redundant_decls = setting;
621       else if (!strcmp (p, "missing-braces"))
622         warn_missing_braces = setting;
623       else if (!strcmp (p, "sign-compare"))
624         warn_sign_compare = setting;
625       else if (!strcmp (p, "float-equal"))
626         warn_float_equal = setting;
627       else if (!strcmp (p, "format"))
628         set_Wformat (setting);
629       else if (!strcmp (p, "format=2"))
630         set_Wformat (2);
631       else if (!strcmp (p, "format-y2k"))
632         warn_format_y2k = setting;
633       else if (!strcmp (p, "format-extra-args"))
634         warn_format_extra_args = setting;
635       else if (!strcmp (p, "format-nonliteral"))
636         warn_format_nonliteral = setting;
637       else if (!strcmp (p, "format-security"))
638         warn_format_security = setting;
639       else if (!strcmp (p, "missing-format-attribute"))
640         warn_missing_format_attribute = setting;
641       else if (!strcmp (p, "conversion"))
642         warn_conversion = setting;
643       else if (!strcmp (p, "parentheses"))
644         warn_parentheses = setting;
645       else if (!strcmp (p, "non-virtual-dtor"))
646         warn_nonvdtor = setting;
647       else if (!strcmp (p, "reorder"))
648         warn_reorder = setting;
649       else if (!strcmp (p, "synth"))
650         warn_synth = setting;
651       else if (!strcmp (p, "pmf-conversions"))
652         warn_pmf2ptr = setting;
653       else if (!strcmp (p, "effc++"))
654         warn_ecpp = setting;
655       else if (!strcmp (p, "sign-promo"))
656         warn_sign_promo = setting;
657       else if (!strcmp (p, "old-style-cast"))
658         warn_old_style_cast = setting;
659       else if (!strcmp (p, "overloaded-virtual"))
660         warn_overloaded_virtual = setting;
661       else if (!strcmp (p, "multichar"))
662         warn_multichar = setting;
663       else if (!strcmp (p, "unknown-pragmas"))
664         /* Set to greater than 1, so that even unknown pragmas in
665            system headers will be warned about.  */  
666         warn_unknown_pragmas = setting * 2;
667       else if (!strcmp (p, "non-template-friend"))
668         warn_nontemplate_friend = setting;
669       else if (!strcmp (p, "deprecated"))
670         warn_deprecated = setting;
671       else if (!strcmp (p, "comment"))
672         ;                       /* cpp handles this one.  */
673       else if (!strcmp (p, "comments"))
674         ;                       /* cpp handles this one.  */
675       else if (!strcmp (p, "trigraphs"))
676         ;                       /* cpp handles this one.  */
677       else if (!strcmp (p, "import"))
678         ;                       /* cpp handles this one.  */
679       else if (!strcmp (p, "all"))
680         {
681           warn_return_type = setting;
682           set_Wunused (setting);
683           warn_implicit = setting;
684           warn_switch = setting;
685           set_Wformat (setting);
686           warn_parentheses = setting;
687           warn_missing_braces = setting;
688           warn_sign_compare = setting;
689           warn_multichar = setting;
690           /* We save the value of warn_uninitialized, since if they put
691              -Wuninitialized on the command line, we need to generate a
692              warning about not using it without also specifying -O.  */
693           if (warn_uninitialized != 1)
694             warn_uninitialized = (setting ? 2 : 0);
695           /* Only warn about unknown pragmas that are not in system
696              headers.  */                                        
697           warn_unknown_pragmas = 1;       
698
699           /* C++-specific warnings.  */
700           warn_ctor_dtor_privacy = setting;
701           warn_nonvdtor = setting;
702           warn_reorder = setting;
703           warn_nontemplate_friend = setting;           
704         }
705       else return strings_processed;
706     }
707   else if (!strcmp (p, "-ansi"))
708     flag_no_nonansi_builtin = 1, flag_ansi = 1,
709     flag_noniso_default_format_attributes = 0, flag_no_gnu_keywords = 1;
710 #ifdef SPEW_DEBUG
711   /* Undocumented, only ever used when you're invoking cc1plus by hand, since
712      it's probably safe to assume no sane person would ever want to use this
713      under normal circumstances.  */
714   else if (!strcmp (p, "-spew-debug"))
715     spew_debug = 1;
716 #endif
717   else
718     return strings_processed;
719
720   return 1;
721 }
722 \f
723 /* Incorporate `const' and `volatile' qualifiers for member functions.
724    FUNCTION is a TYPE_DECL or a FUNCTION_DECL.
725    QUALS is a list of qualifiers.  Returns any explicit
726    top-level qualifiers of the method's this pointer, anything other than
727    TYPE_UNQUALIFIED will be an extension.  */
728
729 int
730 grok_method_quals (ctype, function, quals)
731      tree ctype, function, quals;
732 {
733   tree fntype = TREE_TYPE (function);
734   tree raises = TYPE_RAISES_EXCEPTIONS (fntype);
735   int type_quals = TYPE_UNQUALIFIED;
736   int dup_quals = TYPE_UNQUALIFIED;
737   int this_quals = TYPE_UNQUALIFIED;
738
739   do
740     {
741       int tq = cp_type_qual_from_rid (TREE_VALUE (quals));
742       
743       if ((type_quals | this_quals) & tq)
744         dup_quals |= tq;
745       else if (tq & TYPE_QUAL_RESTRICT)
746         this_quals |= tq;
747       else
748         type_quals |= tq;
749       quals = TREE_CHAIN (quals);
750     } 
751   while (quals);
752
753   if (dup_quals != TYPE_UNQUALIFIED)
754     error ("duplicate type qualifiers in %s declaration",
755               TREE_CODE (function) == FUNCTION_DECL 
756               ? "member function" : "type");
757
758   ctype = cp_build_qualified_type (ctype, type_quals);
759   fntype = build_cplus_method_type (ctype, TREE_TYPE (fntype),
760                                     (TREE_CODE (fntype) == METHOD_TYPE
761                                      ? TREE_CHAIN (TYPE_ARG_TYPES (fntype))
762                                      : TYPE_ARG_TYPES (fntype)));
763   if (raises)
764     fntype = build_exception_variant (fntype, raises);
765
766   TREE_TYPE (function) = fntype;
767   return this_quals;
768 }
769
770 /* Warn when -fexternal-templates is used and #pragma
771    interface/implementation is not used all the times it should be,
772    inform the user.  */
773
774 void
775 warn_if_unknown_interface (decl)
776      tree decl;
777 {
778   static int already_warned = 0;
779   if (already_warned++)
780     return;
781
782   if (flag_alt_external_templates)
783     {
784       tree til = tinst_for_decl ();
785       int sl = lineno;
786       const char *sf = input_filename;
787
788       if (til)
789         {
790           lineno = TINST_LINE (til);
791           input_filename = TINST_FILE (til);
792         }
793       warning ("template `%#D' instantiated in file without #pragma interface",
794                   decl);
795       lineno = sl;
796       input_filename = sf;
797     }
798   else
799     cp_warning_at ("template `%#D' defined in file without #pragma interface",
800                    decl);
801 }
802
803 /* A subroutine of the parser, to handle a component list.  */
804
805 void
806 grok_x_components (specs)
807      tree specs;
808 {
809   tree t;
810
811   specs = strip_attrs (specs);
812
813   check_tag_decl (specs);
814   t = groktypename (build_tree_list (specs, NULL_TREE)); 
815
816   /* The only case where we need to do anything additional here is an
817      anonymous union field, e.g.: `struct S { union { int i; }; };'.  */
818   if (t == NULL_TREE || !ANON_AGGR_TYPE_P (t))
819     return;
820
821   fixup_anonymous_aggr (t);
822   finish_member_declaration (build_decl (FIELD_DECL, NULL_TREE, t)); 
823 }
824
825 /* Returns a PARM_DECL for a parameter of the indicated TYPE, with the
826    indicated NAME.  */
827
828 tree
829 build_artificial_parm (name, type)
830      tree name;
831      tree type;
832 {
833   tree parm;
834
835   parm = build_decl (PARM_DECL, name, type);
836   DECL_ARTIFICIAL (parm) = 1;
837   /* All our artificial parms are implicitly `const'; they cannot be
838      assigned to.  */
839   TREE_READONLY (parm) = 1;
840   DECL_ARG_TYPE (parm) = type;
841   return parm;
842 }
843
844 /* Constructors for types with virtual baseclasses need an "in-charge" flag
845    saying whether this constructor is responsible for initialization of
846    virtual baseclasses or not.  All destructors also need this "in-charge"
847    flag, which additionally determines whether or not the destructor should
848    free the memory for the object.
849
850    This function adds the "in-charge" flag to member function FN if
851    appropriate.  It is called from grokclassfn and tsubst.
852    FN must be either a constructor or destructor.
853
854    The in-charge flag follows the 'this' parameter, and is followed by the
855    VTT parm (if any), then the user-written parms.  */
856
857 void
858 maybe_retrofit_in_chrg (fn)
859      tree fn;
860 {
861   tree basetype, arg_types, parms, parm, fntype;
862
863   /* If we've already add the in-charge parameter don't do it again.  */
864   if (DECL_HAS_IN_CHARGE_PARM_P (fn))
865     return;
866
867   /* When processing templates we can't know, in general, whether or
868      not we're going to have virtual baseclasses.  */
869   if (uses_template_parms (fn))
870     return;
871
872   /* We don't need an in-charge parameter for constructors that don't
873      have virtual bases.  */
874   if (DECL_CONSTRUCTOR_P (fn)
875       && !TYPE_USES_VIRTUAL_BASECLASSES (DECL_CONTEXT (fn)))
876     return;
877
878   arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
879   basetype = TREE_TYPE (TREE_VALUE (arg_types));
880   arg_types = TREE_CHAIN (arg_types);
881
882   parms = TREE_CHAIN (DECL_ARGUMENTS (fn));
883
884   /* If this is a subobject constructor or destructor, our caller will
885      pass us a pointer to our VTT.  */
886   if (TYPE_USES_VIRTUAL_BASECLASSES (DECL_CONTEXT (fn)))
887     {
888       parm = build_artificial_parm (vtt_parm_identifier, vtt_parm_type);
889
890       /* First add it to DECL_ARGUMENTS between 'this' and the real args...  */
891       TREE_CHAIN (parm) = parms;
892       parms = parm;
893
894       /* ...and then to TYPE_ARG_TYPES.  */
895       arg_types = hash_tree_chain (vtt_parm_type, arg_types);
896
897       DECL_HAS_VTT_PARM_P (fn) = 1;
898     }
899
900   /* Then add the in-charge parm (before the VTT parm).  */
901   parm = build_artificial_parm (in_charge_identifier, integer_type_node);
902   TREE_CHAIN (parm) = parms;
903   parms = parm;
904   arg_types = hash_tree_chain (integer_type_node, arg_types);
905
906   /* Insert our new parameter(s) into the list.  */
907   TREE_CHAIN (DECL_ARGUMENTS (fn)) = parms;
908
909   /* And rebuild the function type.  */
910   fntype = build_cplus_method_type (basetype, TREE_TYPE (TREE_TYPE (fn)),
911                                     arg_types);
912   if (TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn)))
913     fntype = build_exception_variant (fntype,
914                                       TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn)));
915   TREE_TYPE (fn) = fntype;
916
917   /* Now we've got the in-charge parameter.  */
918   DECL_HAS_IN_CHARGE_PARM_P (fn) = 1;
919 }
920
921 /* Classes overload their constituent function names automatically.
922    When a function name is declared in a record structure,
923    its name is changed to it overloaded name.  Since names for
924    constructors and destructors can conflict, we place a leading
925    '$' for destructors.
926
927    CNAME is the name of the class we are grokking for.
928
929    FUNCTION is a FUNCTION_DECL.  It was created by `grokdeclarator'.
930
931    FLAGS contains bits saying what's special about today's
932    arguments.  1 == DESTRUCTOR.  2 == OPERATOR.
933
934    If FUNCTION is a destructor, then we must add the `auto-delete' field
935    as a second parameter.  There is some hair associated with the fact
936    that we must "declare" this variable in the manner consistent with the
937    way the rest of the arguments were declared.
938
939    QUALS are the qualifiers for the this pointer.  */
940
941 void
942 grokclassfn (ctype, function, flags, quals)
943      tree ctype, function;
944      enum overload_flags flags;
945      tree quals;
946 {
947   tree fn_name = DECL_NAME (function);
948   int this_quals = TYPE_UNQUALIFIED;
949
950   /* Even within an `extern "C"' block, members get C++ linkage.  See
951      [dcl.link] for details.  */
952   SET_DECL_LANGUAGE (function, lang_cplusplus);
953
954   if (fn_name == NULL_TREE)
955     {
956       error ("name missing for member function");
957       fn_name = get_identifier ("<anonymous>");
958       DECL_NAME (function) = fn_name;
959     }
960
961   if (quals)
962     this_quals = grok_method_quals (ctype, function, quals);
963
964   if (TREE_CODE (TREE_TYPE (function)) == METHOD_TYPE)
965     {
966       /* Must add the class instance variable up front.  */
967       /* Right now we just make this a pointer.  But later
968          we may wish to make it special.  */
969       tree type = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (function)));
970       tree qual_type;
971       tree parm;
972
973       /* The `this' parameter is implicitly `const'; it cannot be
974          assigned to.  */
975       this_quals |= TYPE_QUAL_CONST;
976       qual_type = cp_build_qualified_type (type, this_quals);
977       parm = build_artificial_parm (this_identifier, qual_type);
978       c_apply_type_quals_to_decl (this_quals, parm);
979       TREE_CHAIN (parm) = last_function_parms;
980       last_function_parms = parm;
981     }
982
983   DECL_ARGUMENTS (function) = last_function_parms;
984   DECL_CONTEXT (function) = ctype;
985
986   if (flags == DTOR_FLAG)
987     DECL_DESTRUCTOR_P (function) = 1;
988
989   if (flags == DTOR_FLAG || DECL_CONSTRUCTOR_P (function))
990     maybe_retrofit_in_chrg (function);
991
992   if (flags == DTOR_FLAG)
993     {
994       DECL_DESTRUCTOR_P (function) = 1;
995       TYPE_HAS_DESTRUCTOR (ctype) = 1;
996     }
997 }
998
999 /* Create an ARRAY_REF, checking for the user doing things backwards
1000    along the way.  */
1001
1002 tree
1003 grok_array_decl (array_expr, index_exp)
1004      tree array_expr, index_exp;
1005 {
1006   tree type = TREE_TYPE (array_expr);
1007   tree p1, p2, i1, i2;
1008
1009   if (type == error_mark_node || index_exp == error_mark_node)
1010     return error_mark_node;
1011   if (processing_template_decl)
1012     return build_min (ARRAY_REF, type ? TREE_TYPE (type) : NULL_TREE,
1013                       array_expr, index_exp);
1014
1015   if (type == NULL_TREE)
1016     {
1017       /* Something has gone very wrong.  Assume we are mistakenly reducing
1018          an expression instead of a declaration.  */
1019       error ("parser may be lost: is there a '{' missing somewhere?");
1020       return NULL_TREE;
1021     }
1022
1023   if (TREE_CODE (type) == OFFSET_TYPE
1024       || TREE_CODE (type) == REFERENCE_TYPE)
1025     type = TREE_TYPE (type);
1026
1027   /* If they have an `operator[]', use that.  */
1028   if (IS_AGGR_TYPE (type) || IS_AGGR_TYPE (TREE_TYPE (index_exp)))
1029     return build_opfncall (ARRAY_REF, LOOKUP_NORMAL,
1030                            array_expr, index_exp, NULL_TREE);
1031
1032   /* Otherwise, create an ARRAY_REF for a pointer or array type.  It
1033      is a little-known fact that, if `a' is an array and `i' is an
1034      int, you can write `i[a]', which means the same thing as `a[i]'.  */
1035
1036   if (TREE_CODE (type) == ARRAY_TYPE)
1037     p1 = array_expr;
1038   else
1039     p1 = build_expr_type_conversion (WANT_POINTER, array_expr, 0);
1040
1041   if (TREE_CODE (TREE_TYPE (index_exp)) == ARRAY_TYPE)
1042     p2 = index_exp;
1043   else
1044     p2 = build_expr_type_conversion (WANT_POINTER, index_exp, 0);
1045
1046   i1 = build_expr_type_conversion (WANT_INT | WANT_ENUM, array_expr, 0);
1047   i2 = build_expr_type_conversion (WANT_INT | WANT_ENUM, index_exp, 0);
1048
1049   if ((p1 && i2) && (i1 && p2))
1050     error ("ambiguous conversion for array subscript");
1051
1052   if (p1 && i2)
1053     array_expr = p1, index_exp = i2;
1054   else if (i1 && p2)
1055     array_expr = p2, index_exp = i1;
1056   else
1057     {
1058       error ("invalid types `%T[%T]' for array subscript",
1059                 type, TREE_TYPE (index_exp));
1060       return error_mark_node;
1061     }
1062
1063   if (array_expr == error_mark_node || index_exp == error_mark_node)
1064     error ("ambiguous conversion for array subscript");
1065
1066   return build_array_ref (array_expr, index_exp);
1067 }
1068
1069 /* Given the cast expression EXP, checking out its validity.   Either return
1070    an error_mark_node if there was an unavoidable error, return a cast to
1071    void for trying to delete a pointer w/ the value 0, or return the
1072    call to delete.  If DOING_VEC is 1, we handle things differently
1073    for doing an array delete.  If DOING_VEC is 2, they gave us the
1074    array size as an argument to delete.
1075    Implements ARM $5.3.4.  This is called from the parser.  */
1076
1077 tree
1078 delete_sanity (exp, size, doing_vec, use_global_delete)
1079      tree exp, size;
1080      int doing_vec, use_global_delete;
1081 {
1082   tree t, type;
1083   /* For a regular vector delete (aka, no size argument) we will pass
1084      this down as a NULL_TREE into build_vec_delete.  */
1085   tree maxindex = NULL_TREE;
1086
1087   if (exp == error_mark_node)
1088     return exp;
1089
1090   if (processing_template_decl)
1091     {
1092       t = build_min (DELETE_EXPR, void_type_node, exp, size);
1093       DELETE_EXPR_USE_GLOBAL (t) = use_global_delete;
1094       DELETE_EXPR_USE_VEC (t) = doing_vec;
1095       return t;
1096     }
1097
1098   if (TREE_CODE (exp) == OFFSET_REF)
1099     exp = resolve_offset_ref (exp);
1100   exp = convert_from_reference (exp);
1101   t = stabilize_reference (exp);
1102   t = build_expr_type_conversion (WANT_POINTER, t, 1);
1103
1104   if (t == NULL_TREE || t == error_mark_node)
1105     {
1106       error ("type `%#T' argument given to `delete', expected pointer",
1107                 TREE_TYPE (exp));
1108       return error_mark_node;
1109     }
1110
1111   if (doing_vec == 2)
1112     {
1113       maxindex = cp_build_binary_op (MINUS_EXPR, size, integer_one_node);
1114       pedwarn ("anachronistic use of array size in vector delete");
1115     }
1116
1117   type = TREE_TYPE (t);
1118
1119   /* As of Valley Forge, you can delete a pointer to const.  */
1120
1121   /* You can't delete functions.  */
1122   if (TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE)
1123     {
1124       error ("cannot delete a function.  Only pointer-to-objects are valid arguments to `delete'");
1125       return error_mark_node;
1126     }
1127
1128   /* Deleting ptr to void is undefined behaviour [expr.delete/3].  */
1129   if (TREE_CODE (TREE_TYPE (type)) == VOID_TYPE)
1130     {
1131       warning ("deleting `%T' is undefined", type);
1132       doing_vec = 0;
1133     }
1134
1135   /* An array can't have been allocated by new, so complain.  */
1136   if (TREE_CODE (t) == ADDR_EXPR
1137       && TREE_CODE (TREE_OPERAND (t, 0)) == VAR_DECL
1138       && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == ARRAY_TYPE)
1139     warning ("deleting array `%#D'", TREE_OPERAND (t, 0));
1140
1141   /* Deleting a pointer with the value zero is valid and has no effect.  */
1142   if (integer_zerop (t))
1143     return build1 (NOP_EXPR, void_type_node, t);
1144
1145   if (doing_vec)
1146     return build_vec_delete (t, maxindex, sfk_deleting_destructor,
1147                              use_global_delete);
1148   else
1149     {
1150       if (IS_AGGR_TYPE (TREE_TYPE (type))
1151           && TYPE_GETS_REG_DELETE (TREE_TYPE (type)))
1152         {
1153           /* Only do access checking here; we'll be calling op delete
1154              from the destructor.  */
1155           tree tmp = build_op_delete_call (DELETE_EXPR, t, size_zero_node,
1156                                            LOOKUP_NORMAL, NULL_TREE);
1157           if (tmp == error_mark_node)
1158             return error_mark_node;
1159         }
1160
1161       return build_delete (type, t, sfk_deleting_destructor,
1162                            LOOKUP_NORMAL, use_global_delete);
1163     }
1164 }
1165
1166 /* Report an error if the indicated template declaration is not the
1167    sort of thing that should be a member template.  */
1168
1169 void
1170 check_member_template (tmpl)
1171      tree tmpl;
1172 {
1173   tree decl;
1174
1175   my_friendly_assert (TREE_CODE (tmpl) == TEMPLATE_DECL, 0);
1176   decl = DECL_TEMPLATE_RESULT (tmpl);
1177
1178   if (TREE_CODE (decl) == FUNCTION_DECL
1179       || (TREE_CODE (decl) == TYPE_DECL
1180           && IS_AGGR_TYPE (TREE_TYPE (decl))))
1181     {
1182       if (current_function_decl)
1183         /* 14.5.2.2 [temp.mem]
1184            
1185            A local class shall not have member templates. */
1186         error ("invalid declaration of member template `%#D' in local class",
1187                   decl);
1188       
1189       if (TREE_CODE (decl) == FUNCTION_DECL && DECL_VIRTUAL_P (decl))
1190         {
1191           /* 14.5.2.3 [temp.mem]
1192
1193              A member function template shall not be virtual.  */
1194           error 
1195             ("invalid use of `virtual' in template declaration of `%#D'",
1196              decl);
1197           DECL_VIRTUAL_P (decl) = 0;
1198         }
1199
1200       /* The debug-information generating code doesn't know what to do
1201          with member templates.  */ 
1202       DECL_IGNORED_P (tmpl) = 1;
1203     } 
1204   else
1205     error ("template declaration of `%#D'", decl);
1206 }
1207
1208 /* Return true iff TYPE is a valid Java parameter or return type. */
1209
1210 static int
1211 acceptable_java_type (type)
1212      tree type;
1213 {
1214   if (TREE_CODE (type) == VOID_TYPE || TYPE_FOR_JAVA (type))
1215     return 1;
1216   if (TREE_CODE (type) == POINTER_TYPE || TREE_CODE (type) == REFERENCE_TYPE)
1217     {
1218       type = TREE_TYPE (type);
1219       if (TREE_CODE (type) == RECORD_TYPE)
1220         {
1221           tree args;  int i;
1222           if (! TYPE_FOR_JAVA (type))
1223             return 0;
1224           if (! CLASSTYPE_TEMPLATE_INFO (type))
1225             return 1;
1226           args = CLASSTYPE_TI_ARGS (type);
1227           i = TREE_VEC_LENGTH (args);
1228           while (--i >= 0)
1229             {
1230               type = TREE_VEC_ELT (args, i);
1231               if (TREE_CODE (type) == POINTER_TYPE)
1232                 type = TREE_TYPE (type);
1233               if (! TYPE_FOR_JAVA (type))
1234                 return 0;
1235             }
1236           return 1;
1237         }
1238     }
1239   return 0;
1240 }
1241
1242 /* For a METHOD in a Java class CTYPE, return 1 if
1243    the parameter and return types are valid Java types.
1244    Otherwise, print appropriate error messages, and return 0.  */
1245
1246 int
1247 check_java_method (method)
1248      tree method;
1249 {
1250   int jerr = 0;
1251   tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (method));
1252   tree ret_type = TREE_TYPE (TREE_TYPE (method));
1253   if (! acceptable_java_type (ret_type))
1254     {
1255       error ("Java method '%D' has non-Java return type `%T'",
1256                 method, ret_type);
1257       jerr++;
1258     }
1259   for (; arg_types != NULL_TREE; arg_types = TREE_CHAIN (arg_types))
1260     {
1261       tree type = TREE_VALUE (arg_types);
1262       if (! acceptable_java_type (type))
1263         {
1264           error ("Java method '%D' has non-Java parameter type `%T'",
1265                     method, type);
1266           jerr++;
1267         }
1268     }
1269   return jerr ? 0 : 1;
1270 }
1271
1272 /* Sanity check: report error if this function FUNCTION is not
1273    really a member of the class (CTYPE) it is supposed to belong to.
1274    CNAME is the same here as it is for grokclassfn above.  */
1275
1276 tree
1277 check_classfn (ctype, function)
1278      tree ctype, function;
1279 {
1280   tree fn_name = DECL_NAME (function);
1281   tree fndecl, fndecls;
1282   tree method_vec = CLASSTYPE_METHOD_VEC (complete_type (ctype));
1283   tree *methods = 0;
1284   tree *end = 0;
1285   
1286   if (DECL_USE_TEMPLATE (function)
1287       && !(TREE_CODE (function) == TEMPLATE_DECL
1288            && DECL_TEMPLATE_SPECIALIZATION (function))
1289       && is_member_template (DECL_TI_TEMPLATE (function)))
1290     /* Since this is a specialization of a member template,
1291        we're not going to find the declaration in the class.
1292        For example, in:
1293        
1294          struct S { template <typename T> void f(T); };
1295          template <> void S::f(int);
1296        
1297        we're not going to find `S::f(int)', but there's no
1298        reason we should, either.  We let our callers know we didn't
1299        find the method, but we don't complain.  */
1300     return NULL_TREE;
1301       
1302   if (method_vec != 0)
1303     {
1304       methods = &TREE_VEC_ELT (method_vec, 0);
1305       end = TREE_VEC_END (method_vec);
1306
1307       /* First suss out ctors and dtors.  */
1308       if (*methods && fn_name == DECL_NAME (OVL_CURRENT (*methods))
1309           && DECL_CONSTRUCTOR_P (function))
1310         goto got_it;
1311       if (*++methods && fn_name == DECL_NAME (OVL_CURRENT (*methods))
1312           && DECL_DESTRUCTOR_P (function))
1313         goto got_it;
1314
1315       while (++methods != end && *methods)
1316         {
1317           fndecl = *methods;
1318           if (fn_name == DECL_NAME (OVL_CURRENT (*methods)))
1319             {
1320             got_it:
1321               for (fndecls = *methods; fndecls != NULL_TREE;
1322                    fndecls = OVL_NEXT (fndecls))
1323                 {
1324                   fndecl = OVL_CURRENT (fndecls);
1325
1326                   /* We cannot simply call decls_match because this
1327                      doesn't work for static member functions that are 
1328                      pretending to be methods, and because the name
1329                      may have been changed by asm("new_name").  */ 
1330                   if (DECL_NAME (function) == DECL_NAME (fndecl))
1331                     {
1332                       tree p1 = TYPE_ARG_TYPES (TREE_TYPE (function));
1333                       tree p2 = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
1334
1335                       /* Get rid of the this parameter on functions that become
1336                          static.  */
1337                       if (DECL_STATIC_FUNCTION_P (fndecl)
1338                           && TREE_CODE (TREE_TYPE (function)) == METHOD_TYPE)
1339                         p1 = TREE_CHAIN (p1);
1340
1341                       if (same_type_p (TREE_TYPE (TREE_TYPE (function)),
1342                                        TREE_TYPE (TREE_TYPE (fndecl)))
1343                           && compparms (p1, p2)
1344                           && (DECL_TEMPLATE_SPECIALIZATION (function)
1345                               == DECL_TEMPLATE_SPECIALIZATION (fndecl))
1346                           && (!DECL_TEMPLATE_SPECIALIZATION (function)
1347                               || (DECL_TI_TEMPLATE (function) 
1348                                   == DECL_TI_TEMPLATE (fndecl))))
1349                         return fndecl;
1350                     }
1351                 }
1352               break;            /* loser */
1353             }
1354         }
1355     }
1356
1357   if (methods != end && *methods)
1358     {
1359       tree fndecl = *methods;
1360       error ("prototype for `%#D' does not match any in class `%T'",
1361                 function, ctype);
1362       cp_error_at ("candidate%s: %+#D", OVL_NEXT (fndecl) ? "s are" : " is",
1363                    OVL_CURRENT (fndecl));
1364       while (fndecl = OVL_NEXT (fndecl), fndecl)
1365         cp_error_at ("                %#D", OVL_CURRENT(fndecl));
1366     }
1367   else
1368     {
1369       methods = 0;
1370       if (!COMPLETE_TYPE_P (ctype))
1371         incomplete_type_error (function, ctype);
1372       else
1373         error ("no `%#D' member function declared in class `%T'",
1374                   function, ctype);
1375     }
1376
1377   /* If we did not find the method in the class, add it to avoid
1378      spurious errors (unless the CTYPE is not yet defined, in which
1379      case we'll only confuse ourselves when the function is declared
1380      properly within the class.  */
1381   if (COMPLETE_TYPE_P (ctype))
1382     add_method (ctype, function, /*error_p=*/1);
1383   return NULL_TREE;
1384 }
1385
1386 /* We have just processed the DECL, which is a static data member.
1387    Its initializer, if present, is INIT.  The ASMSPEC_TREE, if
1388    present, is the assembly-language name for the data member.
1389    FLAGS is as for cp_finish_decl.  */
1390
1391 void
1392 finish_static_data_member_decl (decl, init, asmspec_tree, flags)
1393      tree decl;
1394      tree init;
1395      tree asmspec_tree;
1396      int flags;
1397 {
1398   my_friendly_assert (TREE_PUBLIC (decl), 0);
1399
1400   DECL_CONTEXT (decl) = current_class_type;
1401
1402   /* We cannot call pushdecl here, because that would fill in the
1403      TREE_CHAIN of our decl.  Instead, we modify cp_finish_decl to do
1404      the right thing, namely, to put this decl out straight away.  */
1405   /* current_class_type can be NULL_TREE in case of error.  */
1406   if (!asmspec_tree && current_class_type)
1407     DECL_INITIAL (decl) = error_mark_node;
1408
1409   if (! processing_template_decl)
1410     {
1411       if (!pending_statics)
1412         VARRAY_TREE_INIT (pending_statics, 32, "pending_statics");
1413       VARRAY_PUSH_TREE (pending_statics, decl);
1414     }
1415
1416   if (LOCAL_CLASS_P (current_class_type))
1417     pedwarn ("local class `%#T' shall not have static data member `%#D'",
1418              current_class_type, decl);
1419
1420   /* Static consts need not be initialized in the class definition.  */
1421   if (init != NULL_TREE && TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (decl)))
1422     {
1423       static int explained = 0;
1424           
1425       error ("initializer invalid for static member with constructor");
1426       if (!explained)
1427         {
1428           error ("(an out of class initialization is required)");
1429           explained = 1;
1430         }
1431       init = NULL_TREE;
1432     }
1433   /* Force the compiler to know when an uninitialized static const
1434      member is being used.  */
1435   if (CP_TYPE_CONST_P (TREE_TYPE (decl)) && init == 0)
1436     TREE_USED (decl) = 1;
1437   DECL_INITIAL (decl) = init;
1438   DECL_IN_AGGR_P (decl) = 1;
1439
1440   cp_finish_decl (decl, init, asmspec_tree, flags);
1441 }
1442
1443 /* Process the specs, declarator (NULL if omitted) and width (NULL if omitted)
1444    of a structure component, returning a _DECL node.
1445    QUALS is a list of type qualifiers for this decl (such as for declaring
1446    const member functions).
1447
1448    This is done during the parsing of the struct declaration.
1449    The _DECL nodes are chained together and the lot of them
1450    are ultimately passed to `build_struct' to make the RECORD_TYPE node.
1451
1452    If class A defines that certain functions in class B are friends, then
1453    the way I have set things up, it is B who is interested in permission
1454    granted by A.  However, it is in A's context that these declarations
1455    are parsed.  By returning a void_type_node, class A does not attempt
1456    to incorporate the declarations of the friends within its structure.
1457
1458    DO NOT MAKE ANY CHANGES TO THIS CODE WITHOUT MAKING CORRESPONDING
1459    CHANGES TO CODE IN `start_method'.  */
1460
1461 tree
1462 grokfield (declarator, declspecs, init, asmspec_tree, attrlist)
1463      tree declarator, declspecs, init, asmspec_tree, attrlist;
1464 {
1465   tree value;
1466   const char *asmspec = 0;
1467   int flags = LOOKUP_ONLYCONVERTING;
1468
1469   /* Convert () initializers to = initializers.  */
1470   if (init == NULL_TREE && declarator != NULL_TREE
1471       && TREE_CODE (declarator) == CALL_EXPR
1472       && TREE_OPERAND (declarator, 0)
1473       && (TREE_CODE (TREE_OPERAND (declarator, 0)) == IDENTIFIER_NODE
1474           || TREE_CODE (TREE_OPERAND (declarator, 0)) == SCOPE_REF)
1475       && parmlist_is_exprlist (CALL_DECLARATOR_PARMS (declarator)))
1476     {
1477       /* It's invalid to try to initialize a data member using a
1478          functional notation, e.g.:
1479          
1480             struct S {
1481               static int i (3);
1482             };
1483             
1484          Explain that to the user.  */
1485       static int explained;
1486
1487       error ("invalid data member initialization");
1488       if (!explained)
1489         {
1490           error ("(use `=' to initialize static data members)");
1491           explained = 1;
1492         }
1493
1494       declarator = TREE_OPERAND (declarator, 0);
1495       flags = 0;
1496     }
1497
1498   if (declspecs == NULL_TREE
1499       && TREE_CODE (declarator) == SCOPE_REF
1500       && TREE_CODE (TREE_OPERAND (declarator, 1)) == IDENTIFIER_NODE)
1501     {
1502       /* Access declaration */
1503       if (! IS_AGGR_TYPE_CODE (TREE_CODE (TREE_OPERAND (declarator, 0))))
1504         ;
1505       else if (TREE_COMPLEXITY (declarator) == current_class_depth)
1506         pop_nested_class ();
1507       return do_class_using_decl (declarator);
1508     }
1509
1510   if (init
1511       && TREE_CODE (init) == TREE_LIST
1512       && TREE_VALUE (init) == error_mark_node
1513       && TREE_CHAIN (init) == NULL_TREE)
1514     init = NULL_TREE;
1515
1516   value = grokdeclarator (declarator, declspecs, FIELD, init != 0, &attrlist);
1517   if (! value || value == error_mark_node)
1518     /* friend or constructor went bad.  */
1519     return value;
1520   if (TREE_TYPE (value) == error_mark_node)
1521     return error_mark_node;  
1522
1523   /* Pass friendly classes back.  */
1524   if (TREE_CODE (value) == VOID_TYPE)
1525     return void_type_node;
1526
1527   if (DECL_NAME (value) != NULL_TREE
1528       && IDENTIFIER_POINTER (DECL_NAME (value))[0] == '_'
1529       && ! strcmp (IDENTIFIER_POINTER (DECL_NAME (value)), "_vptr"))
1530     error ("member `%D' conflicts with virtual function table field name",
1531               value);
1532
1533   /* Stash away type declarations.  */
1534   if (TREE_CODE (value) == TYPE_DECL)
1535     {
1536       DECL_NONLOCAL (value) = 1;
1537       DECL_CONTEXT (value) = current_class_type;
1538
1539       if (CLASS_TYPE_P (TREE_TYPE (value)))
1540         CLASSTYPE_GOT_SEMICOLON (TREE_TYPE (value)) = 1;
1541       
1542       if (processing_template_decl)
1543         value = push_template_decl (value);
1544
1545       return value;
1546     }
1547
1548   if (DECL_IN_AGGR_P (value))
1549     {
1550       error ("`%D' is already defined in `%T'", value,
1551                 DECL_CONTEXT (value));
1552       return void_type_node;
1553     }
1554
1555   if (asmspec_tree)
1556     asmspec = TREE_STRING_POINTER (asmspec_tree);
1557
1558   if (init)
1559     {
1560       if (TREE_CODE (value) == FUNCTION_DECL)
1561         {
1562           grok_function_init (value, init);
1563           init = NULL_TREE;
1564         }
1565       else if (pedantic && TREE_CODE (value) != VAR_DECL)
1566         /* Already complained in grokdeclarator.  */
1567         init = NULL_TREE;
1568       else
1569         {
1570           /* We allow initializers to become parameters to base
1571              initializers.  */
1572           if (TREE_CODE (init) == TREE_LIST)
1573             {
1574               if (TREE_CHAIN (init) == NULL_TREE)
1575                 init = TREE_VALUE (init);
1576               else
1577                 init = digest_init (TREE_TYPE (value), init, (tree *)0);
1578             }
1579           
1580           if (TREE_CODE (init) == CONST_DECL)
1581             init = DECL_INITIAL (init);
1582           else if (TREE_READONLY_DECL_P (init))
1583             init = decl_constant_value (init);
1584           else if (TREE_CODE (init) == CONSTRUCTOR)
1585             init = digest_init (TREE_TYPE (value), init, (tree *)0);
1586           if (init == error_mark_node)
1587             /* We must make this look different than `error_mark_node'
1588                because `decl_const_value' would mis-interpret it
1589                as only meaning that this VAR_DECL is defined.  */
1590             init = build1 (NOP_EXPR, TREE_TYPE (value), init);
1591           else if (processing_template_decl)
1592             ;
1593           else if (! TREE_CONSTANT (init))
1594             {
1595               /* We can allow references to things that are effectively
1596                  static, since references are initialized with the address.  */
1597               if (TREE_CODE (TREE_TYPE (value)) != REFERENCE_TYPE
1598                   || (TREE_STATIC (init) == 0
1599                       && (!DECL_P (init) || DECL_EXTERNAL (init) == 0)))
1600                 {
1601                   error ("field initializer is not constant");
1602                   init = error_mark_node;
1603                 }
1604             }
1605         }
1606     }
1607
1608   if (processing_template_decl && ! current_function_decl
1609       && (TREE_CODE (value) == VAR_DECL || TREE_CODE (value) == FUNCTION_DECL))
1610     value = push_template_decl (value);
1611
1612   if (attrlist)
1613     cplus_decl_attributes (&value, attrlist, 0);
1614
1615   if (TREE_CODE (value) == VAR_DECL)
1616     {
1617       finish_static_data_member_decl (value, init, asmspec_tree, 
1618                                       flags);
1619       return value;
1620     }
1621   if (TREE_CODE (value) == FIELD_DECL)
1622     {
1623       if (asmspec)
1624         error ("`asm' specifiers are not permitted on non-static data members");
1625       if (DECL_INITIAL (value) == error_mark_node)
1626         init = error_mark_node;
1627       cp_finish_decl (value, init, NULL_TREE, flags);
1628       DECL_INITIAL (value) = init;
1629       DECL_IN_AGGR_P (value) = 1;
1630       return value;
1631     }
1632   if (TREE_CODE (value) == FUNCTION_DECL)
1633     {
1634       if (asmspec)
1635         {
1636           /* This must override the asm specifier which was placed
1637              by grokclassfn.  Lay this out fresh.  */
1638           SET_DECL_RTL (value, NULL_RTX);
1639           SET_DECL_ASSEMBLER_NAME (value, get_identifier (asmspec));
1640         }
1641       if (!DECL_FRIEND_P (value))
1642         grok_special_member_properties (value);
1643       
1644       cp_finish_decl (value, init, asmspec_tree, flags);
1645
1646       /* Pass friends back this way.  */
1647       if (DECL_FRIEND_P (value))
1648         return void_type_node;
1649
1650       DECL_IN_AGGR_P (value) = 1;
1651       return value;
1652     }
1653   abort ();
1654   /* NOTREACHED */
1655   return NULL_TREE;
1656 }
1657
1658 /* Like `grokfield', but for bitfields.
1659    WIDTH is non-NULL for bit fields only, and is an INTEGER_CST node.  */
1660
1661 tree
1662 grokbitfield (declarator, declspecs, width)
1663      tree declarator, declspecs, width;
1664 {
1665   register tree value = grokdeclarator (declarator, declspecs, BITFIELD,
1666                                         0, NULL);
1667
1668   if (! value) return NULL_TREE; /* friends went bad.  */
1669
1670   /* Pass friendly classes back.  */
1671   if (TREE_CODE (value) == VOID_TYPE)
1672     return void_type_node;
1673
1674   if (TREE_CODE (value) == TYPE_DECL)
1675     {
1676       error ("cannot declare `%D' to be a bit-field type", value);
1677       return NULL_TREE;
1678     }
1679
1680   /* Usually, finish_struct_1 catches bitfields with invalid types.
1681      But, in the case of bitfields with function type, we confuse
1682      ourselves into thinking they are member functions, so we must
1683      check here.  */
1684   if (TREE_CODE (value) == FUNCTION_DECL)
1685     {
1686       error ("cannot declare bit-field `%D' with function type",
1687              DECL_NAME (value));
1688       return NULL_TREE;
1689     }
1690
1691   if (DECL_IN_AGGR_P (value))
1692     {
1693       error ("`%D' is already defined in the class %T", value,
1694                   DECL_CONTEXT (value));
1695       return void_type_node;
1696     }
1697
1698   if (TREE_STATIC (value))
1699     {
1700       error ("static member `%D' cannot be a bit-field", value);
1701       return NULL_TREE;
1702     }
1703   cp_finish_decl (value, NULL_TREE, NULL_TREE, 0);
1704
1705   if (width != error_mark_node)
1706     {
1707       constant_expression_warning (width);
1708       DECL_INITIAL (value) = width;
1709       SET_DECL_C_BIT_FIELD (value);
1710     }
1711
1712   DECL_IN_AGGR_P (value) = 1;
1713   return value;
1714 }
1715
1716 tree
1717 grokoptypename (declspecs, declarator)
1718      tree declspecs, declarator;
1719 {
1720   tree t = grokdeclarator (declarator, declspecs, TYPENAME, 0, NULL);
1721   return mangle_conv_op_name_for_type (t);
1722 }
1723
1724 /* When a function is declared with an initializer,
1725    do the right thing.  Currently, there are two possibilities:
1726
1727    class B
1728    {
1729     public:
1730      // initialization possibility #1.
1731      virtual void f () = 0;
1732      int g ();
1733    };
1734    
1735    class D1 : B
1736    {
1737     public:
1738      int d1;
1739      // error, no f ();
1740    };
1741    
1742    class D2 : B
1743    {
1744     public:
1745      int d2;
1746      void f ();
1747    };
1748    
1749    class D3 : B
1750    {
1751     public:
1752      int d3;
1753      // initialization possibility #2
1754      void f () = B::f;
1755    };
1756
1757 */
1758
1759 static void
1760 grok_function_init (decl, init)
1761      tree decl;
1762      tree init;
1763 {
1764   /* An initializer for a function tells how this function should
1765      be inherited.  */
1766   tree type = TREE_TYPE (decl);
1767
1768   if (TREE_CODE (type) == FUNCTION_TYPE)
1769     error ("initializer specified for non-member function `%D'", decl);
1770   else if (integer_zerop (init))
1771     DECL_PURE_VIRTUAL_P (decl) = 1;
1772   else
1773     error ("invalid initializer for virtual method `%D'", decl);
1774 }
1775 \f
1776 void
1777 cplus_decl_attributes (decl, attributes, flags)
1778      tree *decl, attributes;
1779      int flags;
1780 {
1781   if (*decl == NULL_TREE || *decl == void_type_node)
1782     return;
1783
1784   if (TREE_CODE (*decl) == TEMPLATE_DECL)
1785     decl = &DECL_TEMPLATE_RESULT (*decl);
1786
1787   decl_attributes (decl, attributes, flags);
1788
1789   if (TREE_CODE (*decl) == TYPE_DECL)
1790     SET_IDENTIFIER_TYPE_VALUE (DECL_NAME (*decl), TREE_TYPE (*decl));
1791 }
1792 \f
1793 /* CONSTRUCTOR_NAME:
1794    Return the name for the constructor (or destructor) for the
1795    specified class.  Argument can be RECORD_TYPE, TYPE_DECL, or
1796    IDENTIFIER_NODE.  When given a template, this routine doesn't
1797    lose the specialization.  */
1798
1799 tree
1800 constructor_name_full (thing)
1801      tree thing;
1802 {
1803   if (TREE_CODE (thing) == TEMPLATE_TYPE_PARM
1804       || TREE_CODE (thing) == BOUND_TEMPLATE_TEMPLATE_PARM
1805       || TREE_CODE (thing) == TYPENAME_TYPE)
1806     thing = TYPE_NAME (thing);
1807   else if (IS_AGGR_TYPE_CODE (TREE_CODE (thing)))
1808     {
1809       if (TYPE_WAS_ANONYMOUS (thing) && TYPE_HAS_CONSTRUCTOR (thing))
1810         thing = DECL_NAME (OVL_CURRENT (TREE_VEC_ELT (CLASSTYPE_METHOD_VEC (thing), 0)));
1811       else
1812         thing = TYPE_NAME (thing);
1813     }
1814   if (TREE_CODE (thing) == TYPE_DECL
1815       || (TREE_CODE (thing) == TEMPLATE_DECL
1816           && TREE_CODE (DECL_TEMPLATE_RESULT (thing)) == TYPE_DECL))
1817     thing = DECL_NAME (thing);
1818   my_friendly_assert (TREE_CODE (thing) == IDENTIFIER_NODE, 197);
1819   return thing;
1820 }
1821
1822 /* CONSTRUCTOR_NAME:
1823    Return the name for the constructor (or destructor) for the
1824    specified class.  Argument can be RECORD_TYPE, TYPE_DECL, or
1825    IDENTIFIER_NODE.  When given a template, return the plain
1826    unspecialized name.  */
1827
1828 tree
1829 constructor_name (thing)
1830      tree thing;
1831 {
1832   tree t;
1833   thing = constructor_name_full (thing);
1834   t = IDENTIFIER_TEMPLATE (thing);
1835   if (!t)
1836     return thing;
1837   return t;
1838 }
1839 \f
1840 /* Defer the compilation of the FN until the end of compilation.  */
1841
1842 void
1843 defer_fn (fn)
1844      tree fn;
1845 {
1846   if (DECL_DEFERRED_FN (fn))
1847     return;
1848   DECL_DEFERRED_FN (fn) = 1;
1849   if (!deferred_fns)
1850     VARRAY_TREE_INIT (deferred_fns, 32, "deferred_fns");
1851
1852   VARRAY_PUSH_TREE (deferred_fns, fn);
1853 }
1854
1855 /* Hunts through the global anonymous union ANON_DECL, building
1856    appropriate VAR_DECLs.  Stores cleanups on the list of ELEMS, and
1857    returns a VAR_DECL whose size is the same as the size of the
1858    ANON_DECL, if one is available.
1859
1860    FIXME: we should really handle anonymous unions by binding the names
1861    of the members to COMPONENT_REFs rather than this kludge.  */
1862
1863 static tree 
1864 build_anon_union_vars (anon_decl, elems, static_p, external_p)
1865      tree anon_decl;
1866      tree* elems;
1867      int static_p;
1868      int external_p;
1869 {
1870   tree type = TREE_TYPE (anon_decl);
1871   tree main_decl = NULL_TREE;
1872   tree field;
1873
1874   /* Rather than write the code to handle the non-union case,
1875      just give an error.  */
1876   if (TREE_CODE (type) != UNION_TYPE)
1877     error ("anonymous struct not inside named type");
1878
1879   for (field = TYPE_FIELDS (type); 
1880        field != NULL_TREE; 
1881        field = TREE_CHAIN (field))
1882     {
1883       tree decl;
1884
1885       if (DECL_ARTIFICIAL (field))
1886         continue;
1887       if (TREE_CODE (field) != FIELD_DECL)
1888         {
1889           cp_pedwarn_at ("`%#D' invalid; an anonymous union can only have non-static data members",
1890                          field);
1891           continue;
1892         }
1893
1894       if (TREE_PRIVATE (field))
1895         cp_pedwarn_at ("private member `%#D' in anonymous union", field);
1896       else if (TREE_PROTECTED (field))
1897         cp_pedwarn_at ("protected member `%#D' in anonymous union", field);
1898
1899       if (DECL_NAME (field) == NULL_TREE
1900           && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1901         {
1902           decl = build_anon_union_vars (field, elems, static_p, external_p);
1903           if (!decl)
1904             continue;
1905         }
1906       else if (DECL_NAME (field) == NULL_TREE)
1907         continue;
1908       else
1909         {
1910           decl = build_decl (VAR_DECL, DECL_NAME (field), TREE_TYPE (field));
1911           /* tell `pushdecl' that this is not tentative.  */
1912           DECL_INITIAL (decl) = error_mark_node;
1913           TREE_PUBLIC (decl) = 0;
1914           TREE_STATIC (decl) = static_p;
1915           DECL_EXTERNAL (decl) = external_p;
1916           decl = pushdecl (decl);
1917           DECL_INITIAL (decl) = NULL_TREE;
1918         }
1919
1920       /* Only write out one anon union element--choose the largest
1921          one.  We used to try to find one the same size as the union,
1922          but that fails if the ABI forces us to align the union more
1923          strictly.  */
1924       if (main_decl == NULL_TREE
1925           || tree_int_cst_lt (DECL_SIZE (main_decl), DECL_SIZE (decl)))
1926         {
1927           if (main_decl)
1928             TREE_ASM_WRITTEN (main_decl) = 1;
1929           main_decl = decl;
1930         }
1931       else 
1932         /* ??? This causes there to be no debug info written out
1933            about this decl.  */
1934         TREE_ASM_WRITTEN (decl) = 1;
1935       
1936       if (DECL_NAME (field) == NULL_TREE
1937           && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1938         /* The remainder of the processing was already done in the
1939            recursive call.  */
1940         continue;
1941
1942       /* If there's a cleanup to do, it belongs in the
1943          TREE_PURPOSE of the following TREE_LIST.  */
1944       *elems = tree_cons (NULL_TREE, decl, *elems);
1945       TREE_TYPE (*elems) = type;
1946     }
1947   
1948   return main_decl;
1949 }
1950
1951 /* Finish off the processing of a UNION_TYPE structure.  If the union is an
1952    anonymous union, then all members must be laid out together.  PUBLIC_P
1953    is nonzero if this union is not declared static.  */
1954
1955 void
1956 finish_anon_union (anon_union_decl)
1957      tree anon_union_decl;
1958 {
1959   tree type = TREE_TYPE (anon_union_decl);
1960   tree main_decl;
1961   int public_p = TREE_PUBLIC (anon_union_decl);
1962   int static_p = TREE_STATIC (anon_union_decl);
1963   int external_p = DECL_EXTERNAL (anon_union_decl);
1964
1965   /* The VAR_DECL's context is the same as the TYPE's context. */
1966   DECL_CONTEXT (anon_union_decl) = DECL_CONTEXT (TYPE_NAME (type));
1967   
1968   if (TYPE_FIELDS (type) == NULL_TREE)
1969     return;
1970
1971   if (public_p)
1972     {
1973       error ("namespace-scope anonymous aggregates must be static");
1974       return;
1975     }
1976
1977   main_decl = build_anon_union_vars (anon_union_decl,
1978                                      &DECL_ANON_UNION_ELEMS (anon_union_decl),
1979                                      static_p, external_p);
1980
1981   if (main_decl == NULL_TREE)
1982     {
1983       warning ("anonymous aggregate with no members");
1984       return;
1985     }
1986
1987   if (static_p)
1988     {
1989       make_decl_rtl (main_decl, 0);
1990       COPY_DECL_RTL (main_decl, anon_union_decl);
1991       expand_anon_union_decl (anon_union_decl, 
1992                               NULL_TREE,
1993                               DECL_ANON_UNION_ELEMS (anon_union_decl));
1994     }
1995   else
1996     add_decl_stmt (anon_union_decl);
1997 }
1998
1999 /* Finish processing a builtin type TYPE.  It's name is NAME,
2000    its fields are in the array FIELDS.  LEN is the number of elements
2001    in FIELDS minus one, or put another way, it is the maximum subscript
2002    used in FIELDS.
2003
2004    It is given the same alignment as ALIGN_TYPE.  */
2005
2006 void
2007 finish_builtin_type (type, name, fields, len, align_type)
2008      tree type;
2009      const char *name;
2010      tree fields[];
2011      int len;
2012      tree align_type;
2013 {
2014   register int i;
2015
2016   TYPE_FIELDS (type) = fields[0];
2017   for (i = 0; i < len; i++)
2018     {
2019       layout_type (TREE_TYPE (fields[i]));
2020       DECL_FIELD_CONTEXT (fields[i]) = type;
2021       TREE_CHAIN (fields[i]) = fields[i+1];
2022     }
2023   DECL_FIELD_CONTEXT (fields[i]) = type;
2024   TYPE_ALIGN (type) = TYPE_ALIGN (align_type);
2025   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (align_type);
2026   layout_type (type);
2027 #if 0 /* not yet, should get fixed properly later */
2028   TYPE_NAME (type) = make_type_decl (get_identifier (name), type);
2029 #else
2030   TYPE_NAME (type) = build_decl (TYPE_DECL, get_identifier (name), type);
2031 #endif
2032   TYPE_STUB_DECL (type) = TYPE_NAME (type);
2033   layout_decl (TYPE_NAME (type), 0);
2034 }
2035 \f
2036 /* Auxiliary functions to make type signatures for
2037    `operator new' and `operator delete' correspond to
2038    what compiler will be expecting.  */
2039
2040 tree
2041 coerce_new_type (type)
2042      tree type;
2043 {
2044   int e = 0;
2045   tree args = TYPE_ARG_TYPES (type);
2046
2047   my_friendly_assert (TREE_CODE (type) == FUNCTION_TYPE, 20001107);
2048   
2049   if (!same_type_p (TREE_TYPE (type), ptr_type_node))
2050     e = 1, error ("`operator new' must return type `%T'", ptr_type_node);
2051
2052   if (!args || args == void_list_node
2053       || !same_type_p (TREE_VALUE (args), c_size_type_node))
2054     {
2055       e = 2;
2056       if (args && args != void_list_node)
2057         args = TREE_CHAIN (args);
2058       pedwarn ("`operator new' takes type `size_t' (`%T') as first parameter", c_size_type_node);
2059     }
2060   switch (e)
2061   {
2062     case 2:
2063       args = tree_cons (NULL_TREE, c_size_type_node, args);
2064       /* FALLTHROUGH */
2065     case 1:
2066       type = build_exception_variant
2067               (build_function_type (ptr_type_node, args),
2068                TYPE_RAISES_EXCEPTIONS (type));
2069       /* FALLTHROUGH */
2070     default:;
2071   }
2072   return type;
2073 }
2074
2075 tree
2076 coerce_delete_type (type)
2077      tree type;
2078 {
2079   int e = 0;
2080   tree args = TYPE_ARG_TYPES (type);
2081   
2082   my_friendly_assert (TREE_CODE (type) == FUNCTION_TYPE, 20001107);
2083
2084   if (!same_type_p (TREE_TYPE (type), void_type_node))
2085     e = 1, error ("`operator delete' must return type `%T'", void_type_node);
2086
2087   if (!args || args == void_list_node
2088       || !same_type_p (TREE_VALUE (args), ptr_type_node))
2089     {
2090       e = 2;
2091       if (args && args != void_list_node)
2092         args = TREE_CHAIN (args);
2093       error ("`operator delete' takes type `%T' as first parameter", ptr_type_node);
2094     }
2095   switch (e)
2096   {
2097     case 2:
2098       args = tree_cons (NULL_TREE, ptr_type_node, args);
2099       /* FALLTHROUGH */
2100     case 1:
2101       type = build_exception_variant
2102               (build_function_type (void_type_node, args),
2103                TYPE_RAISES_EXCEPTIONS (type));
2104       /* FALLTHROUGH */
2105     default:;
2106   }
2107
2108   return type;
2109 }
2110 \f
2111 static void
2112 mark_vtable_entries (decl)
2113      tree decl;
2114 {
2115   tree entries = CONSTRUCTOR_ELTS (DECL_INITIAL (decl));
2116
2117   for (; entries; entries = TREE_CHAIN (entries))
2118     {
2119       tree fnaddr = TREE_VALUE (entries);
2120       tree fn;
2121       
2122       if (TREE_CODE (fnaddr) != ADDR_EXPR
2123           && TREE_CODE (fnaddr) != FDESC_EXPR)
2124         /* This entry is an offset: a virtual base class offset, a
2125            virtual call offset, an RTTI offset, etc.  */
2126         continue;
2127
2128       fn = TREE_OPERAND (fnaddr, 0);
2129       TREE_ADDRESSABLE (fn) = 1;
2130       /* When we don't have vcall offsets, we output thunks whenever
2131          we output the vtables that contain them.  With vcall offsets,
2132          we know all the thunks we'll need when we emit a virtual
2133          function, so we emit the thunks there instead.  */
2134       if (DECL_THUNK_P (fn)) 
2135         use_thunk (fn, /*emit_p=*/0);
2136       mark_used (fn);
2137     }
2138 }
2139
2140 /* Set DECL up to have the closest approximation of "initialized common"
2141    linkage available.  */
2142
2143 void
2144 comdat_linkage (decl)
2145      tree decl;
2146 {
2147   if (flag_weak)
2148     make_decl_one_only (decl);
2149   else if (TREE_CODE (decl) == FUNCTION_DECL 
2150            || (TREE_CODE (decl) == VAR_DECL && DECL_ARTIFICIAL (decl)))
2151     /* We can just emit function and compiler-generated variables
2152        statically; having multiple copies is (for the most part) only
2153        a waste of space.  
2154
2155        There are two correctness issues, however: the address of a
2156        template instantiation with external linkage should be the
2157        same, independent of what translation unit asks for the
2158        address, and this will not hold when we emit multiple copies of
2159        the function.  However, there's little else we can do.  
2160
2161        Also, by default, the typeinfo implementation assumes that
2162        there will be only one copy of the string used as the name for
2163        each type.  Therefore, if weak symbols are unavailable, the
2164        run-time library should perform a more conservative check; it
2165        should perform a string comparison, rather than an address
2166        comparison.  */
2167     TREE_PUBLIC (decl) = 0;
2168   else
2169     {
2170       /* Static data member template instantiations, however, cannot
2171          have multiple copies.  */
2172       if (DECL_INITIAL (decl) == 0
2173           || DECL_INITIAL (decl) == error_mark_node)
2174         DECL_COMMON (decl) = 1;
2175       else if (EMPTY_CONSTRUCTOR_P (DECL_INITIAL (decl)))
2176         {
2177           DECL_COMMON (decl) = 1;
2178           DECL_INITIAL (decl) = error_mark_node;
2179         }
2180       else
2181         {
2182           /* We can't do anything useful; leave vars for explicit
2183              instantiation.  */
2184           DECL_EXTERNAL (decl) = 1;
2185           DECL_NOT_REALLY_EXTERN (decl) = 0;
2186         }
2187     }
2188
2189   if (DECL_LANG_SPECIFIC (decl))
2190     DECL_COMDAT (decl) = 1;
2191 }
2192
2193 /* For win32 we also want to put explicit instantiations in
2194    linkonce sections, so that they will be merged with implicit
2195    instantiations; otherwise we get duplicate symbol errors.  */
2196
2197 void
2198 maybe_make_one_only (decl)
2199      tree decl;
2200 {
2201   /* We used to say that this was not necessary on targets that support weak
2202      symbols, because the implicit instantiations will defer to the explicit
2203      one.  However, that's not actually the case in SVR4; a strong definition
2204      after a weak one is an error.  Also, not making explicit
2205      instantiations one_only means that we can end up with two copies of
2206      some template instantiations. */
2207   if (! flag_weak)
2208     return;
2209
2210   /* We can't set DECL_COMDAT on functions, or finish_file will think
2211      we can get away with not emitting them if they aren't used.  We need
2212      to for variables so that cp_finish_decl will update their linkage,
2213      because their DECL_INITIAL may not have been set properly yet.  */
2214
2215   make_decl_one_only (decl);
2216
2217   if (TREE_CODE (decl) == VAR_DECL && DECL_LANG_SPECIFIC (decl))
2218     DECL_COMDAT (decl) = 1;
2219 }
2220
2221 /* Returns the virtual function with which the vtable for TYPE is
2222    emitted, or NULL_TREE if that heuristic is not applicable to TYPE.  */
2223
2224 static tree
2225 key_method (type)
2226      tree type;
2227 {
2228   tree method;
2229
2230   if (TYPE_FOR_JAVA (type)
2231       || CLASSTYPE_TEMPLATE_INSTANTIATION (type)
2232       || CLASSTYPE_INTERFACE_KNOWN (type))
2233     return NULL_TREE;
2234
2235   for (method = TYPE_METHODS (type); method != NULL_TREE;
2236        method = TREE_CHAIN (method))
2237     if (DECL_VINDEX (method) != NULL_TREE
2238         && ! DECL_DECLARED_INLINE_P (method)
2239         && (! DECL_PURE_VIRTUAL_P (method)
2240 #if 0
2241             /* This would be nice, but we didn't think of it in time.  */
2242             || DECL_DESTRUCTOR_P (method)
2243 #endif
2244             ))
2245       return method;
2246
2247   return NULL_TREE;
2248 }
2249
2250 /* Set TREE_PUBLIC and/or DECL_EXTERN on the vtable DECL,
2251    based on TYPE and other static flags.
2252
2253    Note that anything public is tagged TREE_PUBLIC, whether
2254    it's public in this file or in another one.  */
2255
2256 void
2257 import_export_vtable (decl, type, final)
2258      tree decl, type;
2259      int final;
2260 {
2261   if (DECL_INTERFACE_KNOWN (decl))
2262     return;
2263
2264   if (TYPE_FOR_JAVA (type))
2265     {
2266       TREE_PUBLIC (decl) = 1;
2267       DECL_EXTERNAL (decl) = 1;
2268       DECL_INTERFACE_KNOWN (decl) = 1;
2269     }
2270   else if (CLASSTYPE_INTERFACE_KNOWN (type))
2271     {
2272       TREE_PUBLIC (decl) = 1;
2273       DECL_EXTERNAL (decl) = CLASSTYPE_INTERFACE_ONLY (type);
2274       DECL_INTERFACE_KNOWN (decl) = 1;
2275     }
2276   else
2277     {
2278       /* We can only wait to decide if we have real non-inline virtual
2279          functions in our class, or if we come from a template.  */
2280
2281       int found = (CLASSTYPE_TEMPLATE_INSTANTIATION (type)
2282                    || key_method (type));
2283
2284       if (final || ! found)
2285         {
2286           comdat_linkage (decl);
2287           DECL_EXTERNAL (decl) = 0;
2288         }
2289       else
2290         {
2291           TREE_PUBLIC (decl) = 1;
2292           DECL_EXTERNAL (decl) = 1;
2293         }
2294     }
2295 }
2296
2297 /* Determine whether or not we want to specifically import or export CTYPE,
2298    using various heuristics.  */
2299
2300 static void
2301 import_export_class (ctype)
2302      tree ctype;
2303 {
2304   /* -1 for imported, 1 for exported.  */
2305   int import_export = 0;
2306
2307   /* It only makes sense to call this function at EOF.  The reason is
2308      that this function looks at whether or not the first non-inline
2309      non-abstract virtual member function has been defined in this
2310      translation unit.  But, we can't possibly know that until we've
2311      seen the entire translation unit.  */
2312   my_friendly_assert (at_eof, 20000226);
2313
2314   if (CLASSTYPE_INTERFACE_KNOWN (ctype))
2315     return;
2316
2317   /* If MULTIPLE_SYMBOL_SPACES is defined and we saw a #pragma interface,
2318      we will have CLASSTYPE_INTERFACE_ONLY set but not
2319      CLASSTYPE_INTERFACE_KNOWN.  In that case, we don't want to use this
2320      heuristic because someone will supply a #pragma implementation
2321      elsewhere, and deducing it here would produce a conflict.  */
2322   if (CLASSTYPE_INTERFACE_ONLY (ctype))
2323     return;
2324
2325   if (lookup_attribute ("dllimport", TYPE_ATTRIBUTES (ctype)))
2326     import_export = -1;
2327   else if (lookup_attribute ("dllexport", TYPE_ATTRIBUTES (ctype)))
2328     import_export = 1;
2329
2330   /* If we got -fno-implicit-templates, we import template classes that
2331      weren't explicitly instantiated.  */
2332   if (import_export == 0
2333       && CLASSTYPE_IMPLICIT_INSTANTIATION (ctype)
2334       && ! flag_implicit_templates)
2335     import_export = -1;
2336
2337   /* Base our import/export status on that of the first non-inline,
2338      non-pure virtual function, if any.  */
2339   if (import_export == 0
2340       && TYPE_POLYMORPHIC_P (ctype))
2341     {
2342       tree method = key_method (ctype);
2343       if (method)
2344         import_export = (DECL_REALLY_EXTERN (method) ? -1 : 1);
2345     }
2346
2347 #ifdef MULTIPLE_SYMBOL_SPACES
2348   if (import_export == -1)
2349     import_export = 0;
2350 #endif
2351
2352   if (import_export)
2353     {
2354       SET_CLASSTYPE_INTERFACE_KNOWN (ctype);
2355       CLASSTYPE_INTERFACE_ONLY (ctype) = (import_export < 0);
2356     }
2357 }
2358     
2359 /* We need to describe to the assembler the relationship between
2360    a vtable and the vtable of the parent class.  */
2361
2362 static void
2363 output_vtable_inherit (vars)
2364      tree vars;
2365 {
2366   tree parent;
2367   rtx child_rtx, parent_rtx;
2368
2369   child_rtx = XEXP (DECL_RTL (vars), 0);          /* strip the mem ref  */
2370
2371   parent = binfo_for_vtable (vars);
2372
2373   if (parent == TYPE_BINFO (DECL_CONTEXT (vars)))
2374     parent_rtx = const0_rtx;
2375   else if (parent)
2376     {
2377       parent = get_vtbl_decl_for_binfo (TYPE_BINFO (BINFO_TYPE (parent)));
2378       parent_rtx = XEXP (DECL_RTL (parent), 0);  /* strip the mem ref  */
2379     }
2380   else
2381     abort ();
2382
2383   assemble_vtable_inherit (child_rtx, parent_rtx);
2384 }
2385
2386 static int
2387 finish_vtable_vardecl (t, data)
2388      tree *t;
2389      void *data ATTRIBUTE_UNUSED;
2390 {
2391   tree vars = *t;
2392   tree ctype = DECL_CONTEXT (vars);
2393   import_export_class (ctype);
2394   import_export_vtable (vars, ctype, 1);
2395
2396   if (! DECL_EXTERNAL (vars)
2397       && DECL_NEEDED_P (vars)
2398       && ! TREE_ASM_WRITTEN (vars))
2399     {
2400       if (TREE_TYPE (vars) == void_type_node)
2401         /* It is a dummy vtable made by get_vtable_decl. Ignore it.  */
2402         return 0;
2403       
2404       /* Write it out.  */
2405       mark_vtable_entries (vars);
2406       if (TREE_TYPE (DECL_INITIAL (vars)) == 0)
2407         store_init_value (vars, DECL_INITIAL (vars));
2408
2409       if (write_symbols == DWARF_DEBUG || write_symbols == DWARF2_DEBUG)
2410         {
2411           /* Mark the VAR_DECL node representing the vtable itself as a
2412              "gratuitous" one, thereby forcing dwarfout.c to ignore it.
2413              It is rather important that such things be ignored because
2414              any effort to actually generate DWARF for them will run
2415              into trouble when/if we encounter code like:
2416
2417                 #pragma interface
2418                 struct S { virtual void member (); };
2419
2420               because the artificial declaration of the vtable itself (as
2421               manufactured by the g++ front end) will say that the vtable
2422               is a static member of `S' but only *after* the debug output
2423               for the definition of `S' has already been output.  This causes
2424               grief because the DWARF entry for the definition of the vtable
2425               will try to refer back to an earlier *declaration* of the
2426               vtable as a static member of `S' and there won't be one.
2427               We might be able to arrange to have the "vtable static member"
2428               attached to the member list for `S' before the debug info for
2429               `S' get written (which would solve the problem) but that would
2430               require more intrusive changes to the g++ front end.  */
2431
2432           DECL_IGNORED_P (vars) = 1;
2433         }
2434
2435       /* Always make vtables weak.  */
2436       if (flag_weak)
2437         comdat_linkage (vars);
2438
2439       rest_of_decl_compilation (vars, NULL, 1, 1);
2440
2441       if (flag_vtable_gc)
2442         output_vtable_inherit (vars);
2443
2444       /* Because we're only doing syntax-checking, we'll never end up
2445          actually marking the variable as written.  */
2446       if (flag_syntax_only)
2447         TREE_ASM_WRITTEN (vars) = 1;
2448
2449       /* Since we're writing out the vtable here, also write the debug 
2450          info.  */
2451       note_debug_info_needed (ctype);
2452
2453       return 1;
2454     }
2455
2456   /* If the references to this class' vtables were optimized away, still
2457      emit the appropriate debugging information.  See dfs_debug_mark.  */
2458   if (DECL_COMDAT (vars)
2459       && CLASSTYPE_DEBUG_REQUESTED (ctype))
2460     note_debug_info_needed (ctype);
2461
2462   return 0;
2463 }
2464
2465 static int
2466 prune_vtable_vardecl (t, data)
2467      tree *t;
2468      void *data ATTRIBUTE_UNUSED;
2469 {
2470   *t = TREE_CHAIN (*t);
2471   return 1;
2472 }
2473
2474 /* Determines the proper settings of TREE_PUBLIC and DECL_EXTERNAL for an
2475    inline function or template instantiation at end-of-file.  */
2476
2477 void
2478 import_export_decl (decl)
2479      tree decl;
2480 {
2481   if (DECL_INTERFACE_KNOWN (decl))
2482     return;
2483
2484   if (DECL_TEMPLATE_INSTANTIATION (decl)
2485       || DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl))
2486     {
2487       DECL_NOT_REALLY_EXTERN (decl) = 1;
2488       if ((DECL_IMPLICIT_INSTANTIATION (decl)
2489            || DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl))
2490           && (flag_implicit_templates
2491               || (flag_implicit_inline_templates 
2492                   && DECL_DECLARED_INLINE_P (decl))))
2493         {
2494           if (!TREE_PUBLIC (decl))
2495             /* Templates are allowed to have internal linkage.  See 
2496                [basic.link].  */
2497             ;
2498           else
2499             comdat_linkage (decl);
2500         }
2501       else
2502         DECL_NOT_REALLY_EXTERN (decl) = 0;
2503     }
2504   else if (DECL_FUNCTION_MEMBER_P (decl))
2505     {
2506       if (!DECL_DECLARED_INLINE_P (decl))
2507         {
2508           tree ctype = DECL_CONTEXT (decl);
2509           import_export_class (ctype);
2510           if (CLASSTYPE_INTERFACE_KNOWN (ctype))
2511             {
2512               DECL_NOT_REALLY_EXTERN (decl)
2513                 = ! (CLASSTYPE_INTERFACE_ONLY (ctype)
2514                      || (DECL_DECLARED_INLINE_P (decl) 
2515                          && ! flag_implement_inlines
2516                          && !DECL_VINDEX (decl)));
2517
2518               /* Always make artificials weak.  */
2519               if (DECL_ARTIFICIAL (decl) && flag_weak)
2520                 comdat_linkage (decl);
2521               else
2522                 maybe_make_one_only (decl);
2523             }
2524         }
2525       else
2526         comdat_linkage (decl);
2527     }
2528   else if (tinfo_decl_p (decl, 0))
2529     {
2530       tree ctype = TREE_TYPE (DECL_NAME (decl));
2531
2532       if (IS_AGGR_TYPE (ctype))
2533         import_export_class (ctype);
2534
2535       if (IS_AGGR_TYPE (ctype) && CLASSTYPE_INTERFACE_KNOWN (ctype)
2536           && TYPE_POLYMORPHIC_P (ctype)
2537           /* If -fno-rtti, we're not necessarily emitting this stuff with
2538              the class, so go ahead and emit it now.  This can happen
2539              when a class is used in exception handling.  */
2540           && flag_rtti
2541           /* If the type is a cv-qualified variant of a type, then we
2542              must emit the tinfo function in this translation unit
2543              since it will not be emitted when the vtable for the type
2544              is output (which is when the unqualified version is
2545              generated).  */
2546           && same_type_p (ctype, TYPE_MAIN_VARIANT (ctype)))
2547         {
2548           DECL_NOT_REALLY_EXTERN (decl)
2549             = ! (CLASSTYPE_INTERFACE_ONLY (ctype)
2550                  || (DECL_DECLARED_INLINE_P (decl) 
2551                      && ! flag_implement_inlines
2552                      && !DECL_VINDEX (decl)));
2553
2554           /* Always make artificials weak.  */
2555           if (flag_weak)
2556             comdat_linkage (decl);
2557         }
2558       else if (TYPE_BUILT_IN (ctype) 
2559                && same_type_p (ctype, TYPE_MAIN_VARIANT (ctype)))
2560         DECL_NOT_REALLY_EXTERN (decl) = 0;
2561       else
2562         comdat_linkage (decl);
2563     } 
2564   else
2565     comdat_linkage (decl);
2566
2567   DECL_INTERFACE_KNOWN (decl) = 1;
2568 }
2569
2570 tree
2571 build_cleanup (decl)
2572      tree decl;
2573 {
2574   tree temp;
2575   tree type = TREE_TYPE (decl);
2576
2577   if (TREE_CODE (type) == ARRAY_TYPE)
2578     temp = decl;
2579   else
2580     {
2581       mark_addressable (decl);
2582       temp = build1 (ADDR_EXPR, build_pointer_type (type), decl);
2583     }
2584   temp = build_delete (TREE_TYPE (temp), temp,
2585                        sfk_complete_destructor,
2586                        LOOKUP_NORMAL|LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR, 0);
2587   return temp;
2588 }
2589
2590 /* Returns the initialization guard variable for the variable DECL,
2591    which has static storage duration.  */
2592
2593 tree
2594 get_guard (decl)
2595      tree decl;
2596 {
2597   tree sname;
2598   tree guard;
2599
2600   sname = mangle_guard_variable (decl);
2601   guard = IDENTIFIER_GLOBAL_VALUE (sname);
2602   if (! guard)
2603     {
2604       tree guard_type;
2605
2606       /* We use a type that is big enough to contain a mutex as well
2607          as an integer counter.  */
2608       guard_type = long_long_integer_type_node;
2609       guard = build_decl (VAR_DECL, sname, guard_type);
2610       
2611       /* The guard should have the same linkage as what it guards. */
2612       TREE_PUBLIC (guard) = TREE_PUBLIC (decl);
2613       TREE_STATIC (guard) = TREE_STATIC (decl);
2614       DECL_COMMON (guard) = DECL_COMMON (decl);
2615       DECL_ONE_ONLY (guard) = DECL_ONE_ONLY (decl);
2616       if (TREE_PUBLIC (decl))
2617         DECL_WEAK (guard) = DECL_WEAK (decl);
2618       
2619       DECL_ARTIFICIAL (guard) = 1;
2620       TREE_USED (guard) = 1;
2621       pushdecl_top_level (guard);
2622       cp_finish_decl (guard, NULL_TREE, NULL_TREE, 0);
2623     }
2624   return guard;
2625 }
2626
2627 /* Return those bits of the GUARD variable that should be set when the
2628    guarded entity is actually initialized.  */
2629
2630 static tree
2631 get_guard_bits (guard)
2632      tree guard;
2633 {
2634   /* We only set the first byte of the guard, in order to leave room
2635      for a mutex in the high-order bits.  */
2636   guard = build1 (ADDR_EXPR, 
2637                   build_pointer_type (TREE_TYPE (guard)),
2638                   guard);
2639   guard = build1 (NOP_EXPR, 
2640                   build_pointer_type (char_type_node), 
2641                   guard);
2642   guard = build1 (INDIRECT_REF, char_type_node, guard);
2643
2644   return guard;
2645 }
2646
2647 /* Return an expression which determines whether or not the GUARD
2648    variable has already been initialized.  */
2649
2650 tree
2651 get_guard_cond (guard)
2652      tree guard;
2653 {
2654   tree guard_value;
2655
2656   /* Check to see if the GUARD is zero.  */
2657   guard = get_guard_bits (guard);
2658   guard_value = integer_zero_node;
2659   if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
2660     guard_value = convert (TREE_TYPE (guard), guard_value);
2661   return cp_build_binary_op (EQ_EXPR, guard, guard_value);
2662 }
2663
2664 /* Return an expression which sets the GUARD variable, indicating that
2665    the variable being guarded has been initialized.  */
2666
2667 tree
2668 set_guard (guard)
2669      tree guard;
2670 {
2671   tree guard_init;
2672
2673   /* Set the GUARD to one.  */
2674   guard = get_guard_bits (guard);
2675   guard_init = integer_one_node;
2676   if (!same_type_p (TREE_TYPE (guard_init), TREE_TYPE (guard)))
2677     guard_init = convert (TREE_TYPE (guard), guard_init);
2678   return build_modify_expr (guard, NOP_EXPR, guard_init);
2679 }
2680
2681 /* Start the process of running a particular set of global constructors
2682    or destructors.  Subroutine of do_[cd]tors.  */
2683
2684 static tree
2685 start_objects (method_type, initp)
2686      int method_type, initp;
2687 {
2688   tree fnname;
2689   tree body;
2690   char type[10];
2691
2692   /* Make ctor or dtor function.  METHOD_TYPE may be 'I' or 'D'.  */
2693
2694   if (initp != DEFAULT_INIT_PRIORITY)
2695     {
2696       char joiner;
2697
2698 #ifdef JOINER
2699       joiner = JOINER;
2700 #else
2701       joiner = '_';
2702 #endif
2703
2704       sprintf (type, "%c%c%.5u", method_type, joiner, initp);
2705     }
2706   else
2707     sprintf (type, "%c", method_type);
2708
2709   fnname = get_file_function_name_long (type);
2710
2711   start_function (void_list_node,
2712                   make_call_declarator (fnname, void_list_node, NULL_TREE,
2713                                         NULL_TREE),
2714                   NULL_TREE, SF_DEFAULT);
2715
2716   /* It can be a static function as long as collect2 does not have
2717      to scan the object file to find its ctor/dtor routine.  */
2718   TREE_PUBLIC (current_function_decl) = ! targetm.have_ctors_dtors;
2719
2720   /* Mark this declaration as used to avoid spurious warnings.  */
2721   TREE_USED (current_function_decl) = 1;
2722
2723   /* Mark this function as a global constructor or destructor.  */
2724   if (method_type == 'I')
2725     DECL_GLOBAL_CTOR_P (current_function_decl) = 1;
2726   else
2727     DECL_GLOBAL_DTOR_P (current_function_decl) = 1;
2728   GLOBAL_INIT_PRIORITY (current_function_decl) = initp;
2729
2730   body = begin_compound_stmt (/*has_no_scope=*/0);
2731
2732   /* We cannot allow these functions to be elided, even if they do not
2733      have external linkage.  And, there's no point in deferring
2734      copmilation of thes functions; they're all going to have to be
2735      out anyhow.  */
2736   current_function_cannot_inline
2737     = "static constructors and destructors cannot be inlined";
2738
2739   return body;
2740 }
2741
2742 /* Finish the process of running a particular set of global constructors
2743    or destructors.  Subroutine of do_[cd]tors.  */
2744
2745 static void
2746 finish_objects (method_type, initp, body)
2747      int method_type, initp;
2748      tree body;
2749 {
2750   tree fn;
2751
2752   /* Finish up.  */
2753   finish_compound_stmt (/*has_no_scope=*/0, body);
2754   fn = finish_function (0);
2755   expand_body (fn);
2756
2757   /* When only doing semantic analysis, and no RTL generation, we
2758      can't call functions that directly emit assembly code; there is
2759      no assembly file in which to put the code.  */
2760   if (flag_syntax_only)
2761     return;
2762
2763   if (targetm.have_ctors_dtors)
2764     {
2765       rtx fnsym = XEXP (DECL_RTL (fn), 0);
2766       if (method_type == 'I')
2767         (* targetm.asm_out.constructor) (fnsym, initp);
2768       else
2769         (* targetm.asm_out.destructor) (fnsym, initp);
2770     }
2771 }
2772
2773 /* The names of the parameters to the function created to handle
2774    initializations and destructions for objects with static storage
2775    duration.  */
2776 #define INITIALIZE_P_IDENTIFIER "__initialize_p"
2777 #define PRIORITY_IDENTIFIER "__priority"
2778
2779 /* The name of the function we create to handle initializations and
2780    destructions for objects with static storage duration.  */
2781 #define SSDF_IDENTIFIER "__static_initialization_and_destruction"
2782
2783 /* The declaration for the __INITIALIZE_P argument.  */
2784 static tree initialize_p_decl;
2785
2786 /* The declaration for the __PRIORITY argument.  */
2787 static tree priority_decl;
2788
2789 /* The declaration for the static storage duration function.  */
2790 static tree ssdf_decl;
2791
2792 /* All the static storage duration functions created in this
2793    translation unit.  */
2794 static varray_type ssdf_decls;
2795
2796 /* A map from priority levels to information about that priority
2797    level.  There may be many such levels, so efficient lookup is
2798    important.  */
2799 static splay_tree priority_info_map;
2800
2801 /* Begins the generation of the function that will handle all
2802    initialization and destruction of objects with static storage
2803    duration.  The function generated takes two parameters of type
2804    `int': __INITIALIZE_P and __PRIORITY.  If __INITIALIZE_P is
2805    non-zero, it performs initializations.  Otherwise, it performs
2806    destructions.  It only performs those initializations or
2807    destructions with the indicated __PRIORITY.  The generated function
2808    returns no value.  
2809
2810    It is assumed that this function will only be called once per
2811    translation unit.  */
2812
2813 static tree
2814 start_static_storage_duration_function ()
2815 {
2816   static unsigned ssdf_number;
2817
2818   tree parm_types;
2819   tree type;
2820   tree body;
2821   char id[sizeof (SSDF_IDENTIFIER) + 1 /* '\0' */ + 32];
2822
2823   /* Create the identifier for this function.  It will be of the form
2824      SSDF_IDENTIFIER_<number>.  */
2825   sprintf (id, "%s_%u", SSDF_IDENTIFIER, ssdf_number++);
2826   if (ssdf_number == 0)
2827     {
2828       /* Overflow occurred.  That means there are at least 4 billion
2829          initialization functions.  */
2830       sorry ("too many initialization functions required");
2831       abort ();
2832     }
2833
2834   /* Create the parameters.  */
2835   parm_types = void_list_node;
2836   parm_types = tree_cons (NULL_TREE, integer_type_node, parm_types);
2837   parm_types = tree_cons (NULL_TREE, integer_type_node, parm_types);
2838   type = build_function_type (void_type_node, parm_types);
2839
2840   /* Create the FUNCTION_DECL itself.  */
2841   ssdf_decl = build_lang_decl (FUNCTION_DECL, 
2842                                get_identifier (id),
2843                                type);
2844   TREE_PUBLIC (ssdf_decl) = 0;
2845   DECL_ARTIFICIAL (ssdf_decl) = 1;
2846
2847   /* Put this function in the list of functions to be called from the
2848      static constructors and destructors.  */
2849   if (!ssdf_decls)
2850     {
2851       VARRAY_TREE_INIT (ssdf_decls, 32, "ssdf_decls");
2852
2853       /* Take this opportunity to initialize the map from priority
2854          numbers to information about that priority level. */
2855       priority_info_map = splay_tree_new (splay_tree_compare_ints,
2856                                           /*delete_key_fn=*/0,
2857                                           /*delete_value_fn=*/
2858                                           (splay_tree_delete_value_fn) &free);
2859
2860       /* We always need to generate functions for the
2861          DEFAULT_INIT_PRIORITY so enter it now.  That way when we walk
2862          priorities later, we'll be sure to find the
2863          DEFAULT_INIT_PRIORITY.  */
2864       get_priority_info (DEFAULT_INIT_PRIORITY);
2865     }
2866
2867   VARRAY_PUSH_TREE (ssdf_decls, ssdf_decl);
2868
2869   /* Create the argument list.  */
2870   initialize_p_decl = build_decl (PARM_DECL,
2871                                   get_identifier (INITIALIZE_P_IDENTIFIER),
2872                                   integer_type_node);
2873   DECL_CONTEXT (initialize_p_decl) = ssdf_decl;
2874   DECL_ARG_TYPE (initialize_p_decl) = integer_type_node;
2875   TREE_USED (initialize_p_decl) = 1;
2876   priority_decl = build_decl (PARM_DECL, get_identifier (PRIORITY_IDENTIFIER),
2877                               integer_type_node);
2878   DECL_CONTEXT (priority_decl) = ssdf_decl;
2879   DECL_ARG_TYPE (priority_decl) = integer_type_node;
2880   TREE_USED (priority_decl) = 1;
2881
2882   TREE_CHAIN (initialize_p_decl) = priority_decl;
2883   DECL_ARGUMENTS (ssdf_decl) = initialize_p_decl;
2884
2885   /* Put the function in the global scope.  */
2886   pushdecl (ssdf_decl);
2887
2888   /* Start the function itself.  This is equivalent to declarating the
2889      function as:
2890
2891        static void __ssdf (int __initialize_p, init __priority_p);
2892        
2893      It is static because we only need to call this function from the
2894      various constructor and destructor functions for this module.  */
2895   start_function (/*specs=*/NULL_TREE, 
2896                   ssdf_decl,
2897                   /*attrs=*/NULL_TREE,
2898                   SF_PRE_PARSED);
2899
2900   /* Set up the scope of the outermost block in the function.  */
2901   body = begin_compound_stmt (/*has_no_scope=*/0);
2902
2903   /* This function must not be deferred because we are depending on
2904      its compilation to tell us what is TREE_SYMBOL_REFERENCED.  */
2905   current_function_cannot_inline 
2906     = "static storage duration functions cannot be inlined";
2907
2908   return body;
2909 }
2910
2911 /* Finish the generation of the function which performs initialization
2912    and destruction of objects with static storage duration.  After
2913    this point, no more such objects can be created.  */
2914
2915 static void
2916 finish_static_storage_duration_function (body)
2917      tree body;
2918 {
2919   /* Close out the function.  */
2920   finish_compound_stmt (/*has_no_scope=*/0, body);
2921   expand_body (finish_function (0));
2922 }
2923
2924 /* Return the information about the indicated PRIORITY level.  If no
2925    code to handle this level has yet been generated, generate the
2926    appropriate prologue.  */
2927
2928 static priority_info
2929 get_priority_info (priority)
2930      int priority;
2931 {
2932   priority_info pi;
2933   splay_tree_node n;
2934
2935   n = splay_tree_lookup (priority_info_map, 
2936                          (splay_tree_key) priority);
2937   if (!n)
2938     {
2939       /* Create a new priority information structure, and insert it
2940          into the map.  */
2941       pi = (priority_info) xmalloc (sizeof (struct priority_info_s));
2942       pi->initializations_p = 0;
2943       pi->destructions_p = 0;
2944       splay_tree_insert (priority_info_map,
2945                          (splay_tree_key) priority,
2946                          (splay_tree_value) pi);
2947     }
2948   else
2949     pi = (priority_info) n->value;
2950
2951   return pi;
2952 }
2953
2954 /* Set up to handle the initialization or destruction of DECL.  If
2955    INITP is non-zero, we are initializing the variable.  Otherwise, we
2956    are destroying it.  */
2957
2958 static tree
2959 start_static_initialization_or_destruction (decl, initp)
2960      tree decl;
2961      int initp;
2962 {
2963   tree guard_if_stmt = NULL_TREE;
2964   int priority;
2965   tree cond;
2966   tree guard;
2967   tree init_cond;
2968   priority_info pi;
2969
2970   /* Figure out the priority for this declaration.  */
2971   priority = DECL_INIT_PRIORITY (decl);
2972   if (!priority)
2973     priority = DEFAULT_INIT_PRIORITY;
2974
2975   /* Remember that we had an initialization or finalization at this
2976      priority.  */
2977   pi = get_priority_info (priority);
2978   if (initp)
2979     pi->initializations_p = 1;
2980   else
2981     pi->destructions_p = 1;
2982
2983   /* Trick the compiler into thinking we are at the file and line
2984      where DECL was declared so that error-messages make sense, and so
2985      that the debugger will show somewhat sensible file and line
2986      information.  */
2987   input_filename = DECL_SOURCE_FILE (decl);
2988   lineno = DECL_SOURCE_LINE (decl);
2989
2990   /* Because of:
2991
2992        [class.access.spec]
2993
2994        Access control for implicit calls to the constructors,
2995        the conversion functions, or the destructor called to
2996        create and destroy a static data member is performed as
2997        if these calls appeared in the scope of the member's
2998        class.  
2999
3000      we pretend we are in a static member function of the class of
3001      which the DECL is a member.  */
3002   if (member_p (decl))
3003     {
3004       DECL_CONTEXT (current_function_decl) = DECL_CONTEXT (decl);
3005       DECL_STATIC_FUNCTION_P (current_function_decl) = 1;
3006     }
3007   
3008   /* Conditionalize this initialization on being in the right priority
3009      and being initializing/finalizing appropriately.  */
3010   guard_if_stmt = begin_if_stmt ();
3011   cond = cp_build_binary_op (EQ_EXPR,
3012                              priority_decl,
3013                              build_int_2 (priority, 0));
3014   init_cond = initp ? integer_one_node : integer_zero_node;
3015   init_cond = cp_build_binary_op (EQ_EXPR,
3016                                   initialize_p_decl,
3017                                   init_cond);
3018   cond = cp_build_binary_op (TRUTH_ANDIF_EXPR, cond, init_cond);
3019
3020   /* Assume we don't need a guard.  */
3021   guard = NULL_TREE;
3022   /* We need a guard if this is an object with external linkage that
3023      might be initialized in more than one place.  (For example, a
3024      static data member of a template, when the data member requires
3025      construction.)  */
3026   if (TREE_PUBLIC (decl) && (DECL_COMMON (decl) 
3027                              || DECL_ONE_ONLY (decl)
3028                              || DECL_WEAK (decl)))
3029     {
3030       tree guard_cond;
3031
3032       guard = get_guard (decl);
3033
3034       /* When using __cxa_atexit, we just check the GUARD as we would
3035          for a local static.  */
3036       if (flag_use_cxa_atexit)
3037         {
3038           /* When using __cxa_atexit, we never try to destroy
3039              anything from a static destructor.  */
3040           my_friendly_assert (initp, 20000629);
3041           guard_cond = get_guard_cond (guard);
3042         }
3043       /* If we don't have __cxa_atexit, then we will be running
3044          destructors from .fini sections, or their equivalents.  So,
3045          we need to know how many times we've tried to initialize this
3046          object.  We do initializations only if the GUARD is zero,
3047          i.e., if we are the first to initialize the variable.  We do
3048          destructions only if the GUARD is one, i.e., if we are the
3049          last to destroy the variable.  */
3050       else if (initp)
3051         guard_cond 
3052           = cp_build_binary_op (EQ_EXPR,
3053                                 build_unary_op (PREINCREMENT_EXPR,
3054                                                 guard,
3055                                                 /*noconvert=*/1),
3056                                 integer_one_node);
3057       else
3058         guard_cond 
3059           = cp_build_binary_op (EQ_EXPR,
3060                                 build_unary_op (PREDECREMENT_EXPR,
3061                                                 guard,
3062                                                 /*noconvert=*/1),
3063                                 integer_zero_node);
3064
3065       cond = cp_build_binary_op (TRUTH_ANDIF_EXPR, cond, guard_cond);
3066     }
3067
3068   finish_if_stmt_cond (cond, guard_if_stmt);
3069
3070   /* If we're using __cxa_atexit, we have not already set the GUARD,
3071      so we must do so now.  */
3072   if (guard && initp && flag_use_cxa_atexit)
3073     finish_expr_stmt (set_guard (guard));
3074
3075   return guard_if_stmt;
3076 }
3077
3078 /* We've just finished generating code to do an initialization or
3079    finalization.  GUARD_IF_STMT is the if-statement we used to guard
3080    the initialization.  */
3081
3082 static void
3083 finish_static_initialization_or_destruction (guard_if_stmt)
3084      tree guard_if_stmt;
3085 {
3086   finish_then_clause (guard_if_stmt);
3087   finish_if_stmt ();
3088
3089   /* Now that we're done with DECL we don't need to pretend to be a
3090      member of its class any longer.  */
3091   DECL_CONTEXT (current_function_decl) = NULL_TREE;
3092   DECL_STATIC_FUNCTION_P (current_function_decl) = 0;
3093 }
3094
3095 /* Generate code to do the static initialization of DECL.  The
3096    initialization is INIT.  If DECL may be initialized more than once
3097    in different object files, GUARD is the guard variable to 
3098    check.  PRIORITY is the priority for the initialization.  */
3099
3100 static void
3101 do_static_initialization (decl, init)
3102      tree decl;
3103      tree init;
3104 {
3105   tree expr;
3106   tree guard_if_stmt;
3107
3108   /* Set up for the initialization.  */
3109   guard_if_stmt
3110     = start_static_initialization_or_destruction (decl,
3111                                                   /*initp=*/1);
3112   
3113   /* Do the initialization itself.  */
3114   if (IS_AGGR_TYPE (TREE_TYPE (decl))
3115       || TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE)
3116     expr = build_aggr_init (decl, init, 0);
3117   else
3118     {
3119       expr = build (INIT_EXPR, TREE_TYPE (decl), decl, init);
3120       TREE_SIDE_EFFECTS (expr) = 1;
3121     }
3122   finish_expr_stmt (expr);
3123
3124   /* If we're using __cxa_atexit, register a a function that calls the
3125      destructor for the object.  */
3126   if (flag_use_cxa_atexit)
3127     register_dtor_fn (decl);
3128
3129   /* Finsh up.  */
3130   finish_static_initialization_or_destruction (guard_if_stmt);
3131 }
3132
3133 /* Generate code to do the static destruction of DECL.  If DECL may be
3134    initialized more than once in different object files, GUARD is the
3135    guard variable to check.  PRIORITY is the priority for the
3136    destruction.  */
3137
3138 static void
3139 do_static_destruction (decl)
3140      tree decl;
3141 {
3142   tree guard_if_stmt;
3143
3144   /* If we're using __cxa_atexit, then destructors are registered
3145      immediately after objects are initialized.  */
3146   my_friendly_assert (!flag_use_cxa_atexit, 20000121);
3147
3148   /* If we don't need a destructor, there's nothing to do.  */
3149   if (TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
3150     return;
3151
3152   /* Actually do the destruction.  */
3153   guard_if_stmt = start_static_initialization_or_destruction (decl,
3154                                                                /*initp=*/0);
3155   finish_expr_stmt (build_cleanup (decl));
3156   finish_static_initialization_or_destruction (guard_if_stmt);
3157 }
3158
3159 /* VARS is a list of variables with static storage duration which may
3160    need initialization and/or finalization.  Remove those variables
3161    that don't really need to be initialized or finalized, and return
3162    the resulting list.  The order in which the variables appear in
3163    VARS is in reverse order of the order in which they should actually
3164    be initialized.  The list we return is in the unreversed order;
3165    i.e., the first variable should be initialized first.  */
3166
3167 static tree
3168 prune_vars_needing_no_initialization (vars)
3169      tree vars;
3170 {
3171   tree var;
3172   tree result;
3173
3174   for (var = vars, result = NULL_TREE;
3175        var;
3176        var = TREE_CHAIN (var))
3177     {
3178       tree decl = TREE_VALUE (var);
3179       tree init = TREE_PURPOSE (var);
3180
3181       /* Deal gracefully with error.  */
3182       if (decl == error_mark_node)
3183         continue;
3184
3185       /* The only things that can be initialized are variables.  */
3186       my_friendly_assert (TREE_CODE (decl) == VAR_DECL, 19990420);
3187
3188       /* If this object is not defined, we don't need to do anything
3189          here.  */
3190       if (DECL_EXTERNAL (decl))
3191         continue;
3192
3193       /* Also, if the initializer already contains errors, we can bail
3194          out now.  */
3195       if (init && TREE_CODE (init) == TREE_LIST 
3196           && value_member (error_mark_node, init))
3197         continue;
3198
3199       /* This variable is going to need initialization and/or
3200          finalization, so we add it to the list.  */
3201       result = tree_cons (init, decl, result);
3202     }
3203
3204   return result;
3205 }
3206
3207 /* Make sure we have told the back end about all the variables in
3208    VARS.  */
3209
3210 static void
3211 write_out_vars (vars)
3212      tree vars;
3213 {
3214   tree v;
3215
3216   for (v = vars; v; v = TREE_CHAIN (v))
3217     if (! TREE_ASM_WRITTEN (TREE_VALUE (v)))
3218       rest_of_decl_compilation (TREE_VALUE (v), 0, 1, 1);
3219 }
3220
3221 /* Generate a static constructor (if CONSTRUCTOR_P) or destructor
3222    (otherwise) that will initialize all gobal objects with static
3223    storage duration having the indicated PRIORITY.  */
3224
3225 static void
3226 generate_ctor_or_dtor_function (constructor_p, priority)
3227      int constructor_p;
3228      int priority;
3229 {
3230   char function_key;
3231   tree arguments;
3232   tree body;
3233   size_t i;
3234
3235   /* We use `I' to indicate initialization and `D' to indicate
3236      destruction.  */
3237   if (constructor_p)
3238     function_key = 'I';
3239   else
3240     function_key = 'D';
3241
3242   /* Begin the function.  */
3243   body = start_objects (function_key, priority);
3244
3245   /* Call the static storage duration function with appropriate
3246      arguments.  */
3247   for (i = 0; i < ssdf_decls->elements_used; ++i) 
3248     {
3249       arguments = tree_cons (NULL_TREE, build_int_2 (priority, 0), 
3250                              NULL_TREE);
3251       arguments = tree_cons (NULL_TREE, build_int_2 (constructor_p, 0),
3252                              arguments);
3253       finish_expr_stmt (build_function_call (VARRAY_TREE (ssdf_decls, i),
3254                                              arguments));
3255     }
3256
3257   /* If we're generating code for the DEFAULT_INIT_PRIORITY, throw in
3258      calls to any functions marked with attributes indicating that
3259      they should be called at initialization- or destruction-time.  */
3260   if (priority == DEFAULT_INIT_PRIORITY)
3261     {
3262       tree fns;
3263       
3264       for (fns = constructor_p ? static_ctors : static_dtors; 
3265            fns;
3266            fns = TREE_CHAIN (fns))
3267         finish_expr_stmt (build_function_call (TREE_VALUE (fns), NULL_TREE));
3268     }
3269
3270   /* Close out the function.  */
3271   finish_objects (function_key, priority, body);
3272 }
3273
3274 /* Generate constructor and destructor functions for the priority
3275    indicated by N.  */
3276
3277 static int
3278 generate_ctor_and_dtor_functions_for_priority (n, data)
3279      splay_tree_node n;
3280      void *data ATTRIBUTE_UNUSED;
3281 {
3282   int priority = (int) n->key;
3283   priority_info pi = (priority_info) n->value;
3284
3285   /* Generate the functions themselves, but only if they are really
3286      needed.  */
3287   if (pi->initializations_p
3288       || (priority == DEFAULT_INIT_PRIORITY && static_ctors))
3289     generate_ctor_or_dtor_function (/*constructor_p=*/1,
3290                                     priority);
3291   if (pi->destructions_p
3292       || (priority == DEFAULT_INIT_PRIORITY && static_dtors))
3293     generate_ctor_or_dtor_function (/*constructor_p=*/0,
3294                                     priority);
3295
3296   /* Keep iterating.  */
3297   return 0;
3298 }
3299
3300 /* This routine is called from the last rule in yyparse ().
3301    Its job is to create all the code needed to initialize and
3302    destroy the global aggregates.  We do the destruction
3303    first, since that way we only need to reverse the decls once.  */
3304
3305 void
3306 finish_file ()
3307 {
3308   tree vars;
3309   int reconsider;
3310   size_t i;
3311
3312   at_eof = 1;
3313
3314   /* Bad parse errors.  Just forget about it.  */
3315   if (! global_bindings_p () || current_class_type || decl_namespace_list)
3316     return;
3317
3318   /* Otherwise, GDB can get confused, because in only knows
3319      about source for LINENO-1 lines.  */
3320   lineno -= 1;
3321
3322   interface_unknown = 1;
3323   interface_only = 0;
3324
3325   /* We now have to write out all the stuff we put off writing out.
3326      These include:
3327
3328        o Template specializations that we have not yet instantiated,
3329          but which are needed.
3330        o Initialization and destruction for non-local objects with
3331          static storage duration.  (Local objects with static storage
3332          duration are initialized when their scope is first entered,
3333          and are cleaned up via atexit.)
3334        o Virtual function tables.  
3335
3336      All of these may cause others to be needed.  For example,
3337      instantiating one function may cause another to be needed, and
3338      generating the intiailzer for an object may cause templates to be
3339      instantiated, etc., etc.  */
3340
3341   timevar_push (TV_VARCONST);
3342
3343   emit_support_tinfos ();
3344   
3345   do 
3346     {
3347       reconsider = 0;
3348
3349       /* If there are templates that we've put off instantiating, do
3350          them now.  */
3351       instantiate_pending_templates ();
3352
3353       /* Write out virtual tables as required.  Note that writing out
3354          the virtual table for a template class may cause the
3355          instantiation of members of that class.  */
3356       if (walk_globals (vtable_decl_p,
3357                         finish_vtable_vardecl,
3358                         /*data=*/0))
3359         reconsider = 1;
3360       
3361       /* Write out needed type info variables. Writing out one variable
3362          might cause others to be needed.  */
3363       if (walk_globals (tinfo_decl_p, emit_tinfo_decl, /*data=*/0))
3364         reconsider = 1;
3365
3366       /* The list of objects with static storage duration is built up
3367          in reverse order.  We clear STATIC_AGGREGATES so that any new
3368          aggregates added during the initialization of these will be
3369          initialized in the correct order when we next come around the
3370          loop.  */
3371       vars = prune_vars_needing_no_initialization (static_aggregates);
3372       static_aggregates = NULL_TREE;
3373
3374       if (vars)
3375         {
3376           tree v;
3377
3378           /* We need to start a new initialization function each time
3379              through the loop.  That's because we need to know which
3380              vtables have been referenced, and TREE_SYMBOL_REFERENCED
3381              isn't computed until a function is finished, and written
3382              out.  That's a deficiency in the back-end.  When this is
3383              fixed, these initialization functions could all become
3384              inline, with resulting performance improvements.  */
3385           tree ssdf_body = start_static_storage_duration_function ();
3386
3387           /* Make sure the back end knows about all the variables.  */
3388           write_out_vars (vars);
3389
3390           /* First generate code to do all the initializations.  */
3391           for (v = vars; v; v = TREE_CHAIN (v))
3392             do_static_initialization (TREE_VALUE (v),
3393                                       TREE_PURPOSE (v));
3394
3395           /* Then, generate code to do all the destructions.  Do these
3396              in reverse order so that the most recently constructed
3397              variable is the first destroyed.  If we're using
3398              __cxa_atexit, then we don't need to do this; functions
3399              were registered at initialization time to destroy the
3400              local statics.  */
3401           if (!flag_use_cxa_atexit)
3402             {
3403               vars = nreverse (vars);
3404               for (v = vars; v; v = TREE_CHAIN (v))
3405                 do_static_destruction (TREE_VALUE (v));
3406             }
3407           else
3408             vars = NULL_TREE;
3409
3410           /* Finish up the static storage duration function for this
3411              round.  */
3412           finish_static_storage_duration_function (ssdf_body);
3413
3414           /* All those initializations and finalizations might cause
3415              us to need more inline functions, more template
3416              instantiations, etc.  */
3417           reconsider = 1;
3418         }
3419       
3420       /* Go through the various inline functions, and see if any need
3421          synthesizing.  */
3422       for (i = 0; i < deferred_fns_used; ++i)
3423         {
3424           tree decl = VARRAY_TREE (deferred_fns, i);
3425           import_export_decl (decl);
3426           if (DECL_ARTIFICIAL (decl) && ! DECL_INITIAL (decl)
3427               && TREE_USED (decl)
3428               && (! DECL_REALLY_EXTERN (decl) || DECL_INLINE (decl)))
3429             {
3430               /* Even though we're already at the top-level, we push
3431                  there again.  That way, when we pop back a few lines
3432                  hence, all of our state is restored.  Otherwise,
3433                  finish_function doesn't clean things up, and we end
3434                  up with CURRENT_FUNCTION_DECL set.  */
3435               push_to_top_level ();
3436               synthesize_method (decl);
3437               pop_from_top_level ();
3438               reconsider = 1;
3439             }
3440         }
3441
3442       /* We lie to the back-end, pretending that some functions are
3443          not defined when they really are.  This keeps these functions
3444          from being put out unnecessarily.  But, we must stop lying
3445          when the functions are referenced, or if they are not comdat
3446          since they need to be put out now.  */
3447       for (i = 0; i < deferred_fns_used; ++i)
3448         {
3449           tree decl = VARRAY_TREE (deferred_fns, i);
3450       
3451           if (DECL_NOT_REALLY_EXTERN (decl)
3452               && DECL_INITIAL (decl)
3453               && DECL_NEEDED_P (decl))
3454             DECL_EXTERNAL (decl) = 0;
3455
3456           /* If we're going to need to write this function out, and
3457              there's already a body for it, create RTL for it now.
3458              (There might be no body if this is a method we haven't
3459              gotten around to synthesizing yet.)  */
3460           if (!DECL_EXTERNAL (decl)
3461               && DECL_NEEDED_P (decl)
3462               && DECL_SAVED_TREE (decl)
3463               && !TREE_ASM_WRITTEN (decl))
3464             {
3465               int saved_not_really_extern;
3466
3467               /* When we call finish_function in expand_body, it will
3468                  try to reset DECL_NOT_REALLY_EXTERN so we save and
3469                  restore it here.  */
3470               saved_not_really_extern = DECL_NOT_REALLY_EXTERN (decl);
3471               /* Generate RTL for this function now that we know we
3472                  need it.  */
3473               expand_body (decl);
3474               /* Undo the damage done by finish_function.  */
3475               DECL_EXTERNAL (decl) = 0;
3476               DECL_NOT_REALLY_EXTERN (decl) = saved_not_really_extern;
3477               /* If we're compiling -fsyntax-only pretend that this
3478                  function has been written out so that we don't try to
3479                  expand it again.  */
3480               if (flag_syntax_only)
3481                 TREE_ASM_WRITTEN (decl) = 1;
3482               reconsider = 1;
3483             }
3484         }
3485
3486       if (deferred_fns_used
3487           && wrapup_global_declarations (&VARRAY_TREE (deferred_fns, 0),
3488                                          deferred_fns_used))
3489         reconsider = 1;
3490       if (walk_namespaces (wrapup_globals_for_namespace, /*data=*/0))
3491         reconsider = 1;
3492
3493       /* Static data members are just like namespace-scope globals.  */
3494       for (i = 0; i < pending_statics_used; ++i) 
3495         {
3496           tree decl = VARRAY_TREE (pending_statics, i);
3497           if (TREE_ASM_WRITTEN (decl))
3498             continue;
3499           import_export_decl (decl);
3500           if (DECL_NOT_REALLY_EXTERN (decl) && ! DECL_IN_AGGR_P (decl))
3501             DECL_EXTERNAL (decl) = 0;
3502         }
3503       if (pending_statics
3504           && wrapup_global_declarations (&VARRAY_TREE (pending_statics, 0),
3505                                          pending_statics_used))
3506         reconsider = 1;
3507     } 
3508   while (reconsider);
3509
3510   /* We give C linkage to static constructors and destructors.  */
3511   push_lang_context (lang_name_c);
3512
3513   /* Generate initialization and destruction functions for all
3514      priorities for which they are required.  */
3515   if (priority_info_map)
3516     splay_tree_foreach (priority_info_map, 
3517                         generate_ctor_and_dtor_functions_for_priority,
3518                         /*data=*/0);
3519
3520   /* We're done with the splay-tree now.  */
3521   if (priority_info_map)
3522     splay_tree_delete (priority_info_map);
3523
3524   /* We're done with static constructors, so we can go back to "C++"
3525      linkage now.  */
3526   pop_lang_context ();
3527
3528   /* Now delete from the chain of variables all virtual function tables.
3529      We output them all ourselves, because each will be treated
3530      specially.  We don't do this if we're just doing semantic
3531      analysis, and not code-generation.  */
3532   if (!flag_syntax_only)
3533     walk_globals (vtable_decl_p, prune_vtable_vardecl, /*data=*/0);
3534
3535   /* Now, issue warnings about static, but not defined, functions,
3536      etc., and emit debugging information.  */
3537   walk_namespaces (wrapup_globals_for_namespace, /*data=*/&reconsider);
3538   if (pending_statics)
3539     check_global_declarations (&VARRAY_TREE (pending_statics, 0),
3540                                pending_statics_used);
3541
3542   finish_repo ();
3543
3544   /* The entire file is now complete.  If requested, dump everything
3545      to a file.   */
3546   {
3547     int flags;
3548     FILE *stream = dump_begin (TDI_all, &flags);
3549
3550     if (stream)
3551       {
3552         dump_node (global_namespace, flags & ~TDF_SLIM, stream);
3553         dump_end (TDI_all, stream);
3554       }
3555   }
3556   
3557   timevar_pop (TV_VARCONST);
3558
3559   if (flag_detailed_statistics)
3560     {
3561       dump_tree_statistics ();
3562       dump_time_statistics ();
3563     }
3564 }
3565
3566 /* This is something of the form 'A()()()()()+1' that has turned out to be an
3567    expr.  Since it was parsed like a type, we need to wade through and fix
3568    that.  Unfortunately, since operator() is left-associative, we can't use
3569    tail recursion.  In the above example, TYPE is `A', and DECL is
3570    `()()()()()'.
3571
3572    Maybe this shouldn't be recursive, but how often will it actually be
3573    used?  (jason) */
3574
3575 tree
3576 reparse_absdcl_as_expr (type, decl)
3577      tree type, decl;
3578 {
3579   /* do build_functional_cast (type, NULL_TREE) at bottom */
3580   if (TREE_OPERAND (decl, 0) == NULL_TREE)
3581     return build_functional_cast (type, NULL_TREE);
3582
3583   /* recurse */
3584   decl = reparse_absdcl_as_expr (type, TREE_OPERAND (decl, 0));
3585
3586   decl = build_x_function_call (decl, NULL_TREE, current_class_ref);
3587
3588   if (TREE_CODE (decl) == CALL_EXPR
3589       && (! TREE_TYPE (decl)
3590           || TREE_CODE (TREE_TYPE (decl)) != VOID_TYPE))
3591     decl = require_complete_type (decl);
3592
3593   return decl;
3594 }
3595
3596 /* This is something of the form `int ((int)(int)(int)1)' that has turned
3597    out to be an expr.  Since it was parsed like a type, we need to wade
3598    through and fix that.  Since casts are right-associative, we are
3599    reversing the order, so we don't have to recurse.
3600
3601    In the above example, DECL is the `(int)(int)(int)', and EXPR is the
3602    `1'.  */
3603
3604 tree
3605 reparse_absdcl_as_casts (decl, expr)
3606      tree decl, expr;
3607 {
3608   tree type;
3609   int non_void_p = 0;
3610   
3611   if (TREE_CODE (expr) == CONSTRUCTOR
3612       && TREE_TYPE (expr) == 0)
3613     {
3614       type = groktypename (TREE_VALUE (CALL_DECLARATOR_PARMS (decl)));
3615       decl = TREE_OPERAND (decl, 0);
3616
3617       if (processing_template_decl)
3618         TREE_TYPE (expr) = type;
3619       else
3620         {
3621           expr = digest_init (type, expr, (tree *) 0);
3622           if (TREE_CODE (type) == ARRAY_TYPE && !COMPLETE_TYPE_P (type))
3623             {
3624               int failure = complete_array_type (type, expr, 1);
3625               my_friendly_assert (!failure, 78);
3626             }
3627         }
3628     }
3629
3630   while (decl)
3631     {
3632       type = groktypename (TREE_VALUE (CALL_DECLARATOR_PARMS (decl)));
3633       decl = TREE_OPERAND (decl, 0);
3634       if (!VOID_TYPE_P (type))
3635         non_void_p = 1;
3636       expr = build_c_cast (type, expr);
3637     }
3638
3639   if (warn_old_style_cast && ! in_system_header
3640       && non_void_p && current_lang_name != lang_name_c)
3641     warning ("use of old-style cast");
3642
3643   return expr;
3644 }
3645
3646 /* Given plain tree nodes for an expression, build up the full semantics.  */
3647
3648 tree
3649 build_expr_from_tree (t)
3650      tree t;
3651 {
3652   if (t == NULL_TREE || t == error_mark_node)
3653     return t;
3654
3655   switch (TREE_CODE (t))
3656     {
3657     case IDENTIFIER_NODE:
3658       return do_identifier (t, 0, NULL_TREE);
3659
3660     case LOOKUP_EXPR:
3661       if (LOOKUP_EXPR_GLOBAL (t))
3662         return do_scoped_id (TREE_OPERAND (t, 0), 0);
3663       else
3664         return do_identifier (TREE_OPERAND (t, 0), 0, NULL_TREE);
3665
3666     case TEMPLATE_ID_EXPR:
3667       return (lookup_template_function
3668               (build_expr_from_tree (TREE_OPERAND (t, 0)),
3669                build_expr_from_tree (TREE_OPERAND (t, 1))));
3670
3671     case INDIRECT_REF:
3672       return build_x_indirect_ref
3673         (build_expr_from_tree (TREE_OPERAND (t, 0)), "unary *");
3674
3675     case CAST_EXPR:
3676       return build_functional_cast
3677         (TREE_TYPE (t), build_expr_from_tree (TREE_OPERAND (t, 0)));
3678
3679     case REINTERPRET_CAST_EXPR:
3680       return build_reinterpret_cast
3681         (TREE_TYPE (t), build_expr_from_tree (TREE_OPERAND (t, 0)));
3682
3683     case CONST_CAST_EXPR:
3684       return build_const_cast
3685         (TREE_TYPE (t), build_expr_from_tree (TREE_OPERAND (t, 0)));
3686
3687     case DYNAMIC_CAST_EXPR:
3688       return build_dynamic_cast
3689         (TREE_TYPE (t), build_expr_from_tree (TREE_OPERAND (t, 0)));
3690
3691     case STATIC_CAST_EXPR:
3692       return build_static_cast
3693         (TREE_TYPE (t), build_expr_from_tree (TREE_OPERAND (t, 0)));
3694
3695     case PREDECREMENT_EXPR:
3696     case PREINCREMENT_EXPR:
3697     case POSTDECREMENT_EXPR:
3698     case POSTINCREMENT_EXPR:
3699     case NEGATE_EXPR:
3700     case BIT_NOT_EXPR:
3701     case ABS_EXPR:
3702     case TRUTH_NOT_EXPR:
3703     case ADDR_EXPR:
3704     case CONVERT_EXPR:      /* Unary + */
3705     case REALPART_EXPR:
3706     case IMAGPART_EXPR:
3707       if (TREE_TYPE (t))
3708         return t;
3709       return build_x_unary_op (TREE_CODE (t),
3710                                build_expr_from_tree (TREE_OPERAND (t, 0)));
3711
3712     case PLUS_EXPR:
3713     case MINUS_EXPR:
3714     case MULT_EXPR:
3715     case TRUNC_DIV_EXPR:
3716     case CEIL_DIV_EXPR:
3717     case FLOOR_DIV_EXPR:
3718     case ROUND_DIV_EXPR:
3719     case EXACT_DIV_EXPR:
3720     case BIT_AND_EXPR:
3721     case BIT_ANDTC_EXPR:
3722     case BIT_IOR_EXPR:
3723     case BIT_XOR_EXPR:
3724     case TRUNC_MOD_EXPR:
3725     case FLOOR_MOD_EXPR:
3726     case TRUTH_ANDIF_EXPR:
3727     case TRUTH_ORIF_EXPR:
3728     case TRUTH_AND_EXPR:
3729     case TRUTH_OR_EXPR:
3730     case RSHIFT_EXPR:
3731     case LSHIFT_EXPR:
3732     case RROTATE_EXPR:
3733     case LROTATE_EXPR:
3734     case EQ_EXPR:
3735     case NE_EXPR:
3736     case MAX_EXPR:
3737     case MIN_EXPR:
3738     case LE_EXPR:
3739     case GE_EXPR:
3740     case LT_EXPR:
3741     case GT_EXPR:
3742     case MEMBER_REF:
3743       return build_x_binary_op
3744         (TREE_CODE (t), 
3745          build_expr_from_tree (TREE_OPERAND (t, 0)),
3746          build_expr_from_tree (TREE_OPERAND (t, 1)));
3747
3748     case DOTSTAR_EXPR:
3749       return build_m_component_ref
3750         (build_expr_from_tree (TREE_OPERAND (t, 0)),
3751          build_expr_from_tree (TREE_OPERAND (t, 1)));
3752
3753     case SCOPE_REF:
3754       return build_offset_ref (TREE_OPERAND (t, 0), TREE_OPERAND (t, 1));
3755
3756     case ARRAY_REF:
3757       if (TREE_OPERAND (t, 0) == NULL_TREE)
3758         /* new-type-id */
3759         return build_nt (ARRAY_REF, NULL_TREE,
3760                          build_expr_from_tree (TREE_OPERAND (t, 1)));
3761       return grok_array_decl (build_expr_from_tree (TREE_OPERAND (t, 0)),
3762                               build_expr_from_tree (TREE_OPERAND (t, 1)));
3763
3764     case SIZEOF_EXPR:
3765     case ALIGNOF_EXPR:
3766       {
3767         tree r = build_expr_from_tree (TREE_OPERAND (t, 0));
3768         if (!TYPE_P (r))
3769           return TREE_CODE (t) == SIZEOF_EXPR ? expr_sizeof (r) : c_alignof_expr (r);
3770         else
3771           return TREE_CODE (t) == SIZEOF_EXPR ? c_sizeof (r) : c_alignof (r);
3772       }
3773
3774     case MODOP_EXPR:
3775       return build_x_modify_expr
3776         (build_expr_from_tree (TREE_OPERAND (t, 0)),
3777          TREE_CODE (TREE_OPERAND (t, 1)),
3778          build_expr_from_tree (TREE_OPERAND (t, 2)));
3779
3780     case ARROW_EXPR:
3781       return build_x_arrow
3782         (build_expr_from_tree (TREE_OPERAND (t, 0)));
3783
3784     case NEW_EXPR:
3785       return build_new
3786         (build_expr_from_tree (TREE_OPERAND (t, 0)),
3787          build_expr_from_tree (TREE_OPERAND (t, 1)),
3788          build_expr_from_tree (TREE_OPERAND (t, 2)),
3789          NEW_EXPR_USE_GLOBAL (t));
3790
3791     case DELETE_EXPR:
3792       return delete_sanity
3793         (build_expr_from_tree (TREE_OPERAND (t, 0)),
3794          build_expr_from_tree (TREE_OPERAND (t, 1)),
3795          DELETE_EXPR_USE_VEC (t), DELETE_EXPR_USE_GLOBAL (t));
3796
3797     case COMPOUND_EXPR:
3798       if (TREE_OPERAND (t, 1) == NULL_TREE)
3799         return build_x_compound_expr
3800           (build_expr_from_tree (TREE_OPERAND (t, 0)));
3801       else
3802         abort ();
3803
3804     case METHOD_CALL_EXPR:
3805       if (TREE_CODE (TREE_OPERAND (t, 0)) == SCOPE_REF)
3806         {
3807           tree ref = TREE_OPERAND (t, 0);
3808           tree name = TREE_OPERAND (ref, 1);
3809           
3810           if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
3811             name = build_nt (TEMPLATE_ID_EXPR,
3812                              TREE_OPERAND (name, 0),
3813                              build_expr_from_tree (TREE_OPERAND (name, 1)));
3814             
3815           return build_scoped_method_call
3816             (build_expr_from_tree (TREE_OPERAND (t, 1)),
3817              build_expr_from_tree (TREE_OPERAND (ref, 0)),
3818              name,
3819              build_expr_from_tree (TREE_OPERAND (t, 2)));
3820         }
3821       else 
3822         {
3823           tree fn = TREE_OPERAND (t, 0);
3824
3825           /* We can get a TEMPLATE_ID_EXPR here on code like:
3826
3827                x->f<2>();
3828               
3829              so we must resolve that.  However, we can also get things
3830              like a BIT_NOT_EXPR here, when referring to a destructor,
3831              and things like that are not correctly resolved by
3832              build_expr_from_tree.  So, just use build_expr_from_tree
3833              when we really need it.  */
3834           if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
3835             fn = lookup_template_function
3836               (TREE_OPERAND (fn, 0),
3837                build_expr_from_tree (TREE_OPERAND (fn, 1)));
3838
3839           return build_method_call
3840             (build_expr_from_tree (TREE_OPERAND (t, 1)),
3841              fn,
3842              build_expr_from_tree (TREE_OPERAND (t, 2)),
3843              NULL_TREE, LOOKUP_NORMAL);
3844         }
3845
3846     case CALL_EXPR:
3847       if (TREE_CODE (TREE_OPERAND (t, 0)) == SCOPE_REF)
3848         {
3849           tree ref = TREE_OPERAND (t, 0);
3850           tree name = TREE_OPERAND (ref, 1);
3851           
3852           if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
3853             name = build_nt (TEMPLATE_ID_EXPR,
3854                              TREE_OPERAND (name, 0),
3855                              build_expr_from_tree (TREE_OPERAND (name, 1)));
3856             
3857           return build_member_call
3858             (build_expr_from_tree (TREE_OPERAND (ref, 0)),
3859              name,
3860              build_expr_from_tree (TREE_OPERAND (t, 1)));
3861         }
3862       else
3863         {
3864           tree name = TREE_OPERAND (t, 0);
3865           tree id;
3866           tree args = build_expr_from_tree (TREE_OPERAND (t, 1));
3867           if (args != NULL_TREE && TREE_CODE (name) == LOOKUP_EXPR
3868               && !LOOKUP_EXPR_GLOBAL (name)
3869               && TREE_CODE ((id = TREE_OPERAND (name, 0))) == IDENTIFIER_NODE
3870               && (!current_class_type
3871                   || !lookup_member (current_class_type, id, 0, 0)))
3872             {
3873               /* Do Koenig lookup if there are no class members. */
3874               name = do_identifier (id, 0, args);
3875             }
3876           else if (TREE_CODE (name) == TEMPLATE_ID_EXPR
3877               || ! really_overloaded_fn (name))
3878             name = build_expr_from_tree (name);
3879           return build_x_function_call (name, args, current_class_ref);
3880         }
3881
3882     case COND_EXPR:
3883       return build_x_conditional_expr
3884         (build_expr_from_tree (TREE_OPERAND (t, 0)),
3885          build_expr_from_tree (TREE_OPERAND (t, 1)),
3886          build_expr_from_tree (TREE_OPERAND (t, 2)));
3887
3888     case PSEUDO_DTOR_EXPR:
3889       return (finish_pseudo_destructor_call_expr 
3890               (build_expr_from_tree (TREE_OPERAND (t, 0)),
3891                build_expr_from_tree (TREE_OPERAND (t, 1)),
3892                build_expr_from_tree (TREE_OPERAND (t, 2))));
3893
3894     case TREE_LIST:
3895       {
3896         tree purpose, value, chain;
3897
3898         if (t == void_list_node)
3899           return t;
3900
3901         purpose = TREE_PURPOSE (t);
3902         if (purpose)
3903           purpose = build_expr_from_tree (purpose);
3904         value = TREE_VALUE (t);
3905         if (value)
3906           value = build_expr_from_tree (value);
3907         chain = TREE_CHAIN (t);
3908         if (chain && chain != void_type_node)
3909           chain = build_expr_from_tree (chain);
3910         return tree_cons (purpose, value, chain);
3911       }
3912
3913     case COMPONENT_REF:
3914       {
3915         tree object = build_expr_from_tree (TREE_OPERAND (t, 0));
3916         tree field = TREE_OPERAND (t, 1);
3917         
3918         /* We use a COMPONENT_REF to indicate things of the form `x.b'
3919            and `x.A::b'.  We must distinguish between those cases
3920            here.  */
3921         if (TREE_CODE (field) == SCOPE_REF)
3922           return build_object_ref (object, 
3923                                    TREE_OPERAND (field, 0),
3924                                    TREE_OPERAND (field, 1));
3925         else
3926           return build_x_component_ref (object, field,
3927                                         NULL_TREE, 1);
3928       }
3929
3930     case THROW_EXPR:
3931       return build_throw (build_expr_from_tree (TREE_OPERAND (t, 0)));
3932
3933     case CONSTRUCTOR:
3934       {
3935         tree r;
3936         tree elts;
3937         tree type = TREE_TYPE (t);
3938         bool purpose_p;
3939
3940         /* digest_init will do the wrong thing if we let it.  */
3941         if (type && TYPE_PTRMEMFUNC_P (type))
3942           return t;
3943
3944         r = NULL_TREE;
3945         /* We do not want to process the purpose of aggregate
3946            initializers as they are identifier nodes which will be
3947            looked up by digest_init.  */
3948         purpose_p = !(type && IS_AGGR_TYPE (type));
3949         for (elts = CONSTRUCTOR_ELTS (t); elts; elts = TREE_CHAIN (elts))
3950           {
3951             tree purpose = TREE_PURPOSE (elts);
3952             tree value = TREE_VALUE (elts);
3953             
3954             if (purpose && purpose_p)
3955               purpose = build_expr_from_tree (purpose);
3956             value = build_expr_from_tree (value);
3957             r = tree_cons (purpose, value, r);
3958           }
3959         
3960         r = build_nt (CONSTRUCTOR, NULL_TREE, nreverse (r));
3961         TREE_HAS_CONSTRUCTOR (r) = TREE_HAS_CONSTRUCTOR (t);
3962
3963         if (type)
3964           return digest_init (type, r, 0);
3965         return r;
3966       }
3967
3968     case TYPEID_EXPR:
3969       if (TYPE_P (TREE_OPERAND (t, 0)))
3970         return get_typeid (TREE_OPERAND (t, 0));
3971       return build_typeid (build_expr_from_tree (TREE_OPERAND (t, 0)));
3972
3973     case VAR_DECL:
3974       return convert_from_reference (t);
3975
3976     case VA_ARG_EXPR:
3977       return build_va_arg (build_expr_from_tree (TREE_OPERAND (t, 0)),
3978                            TREE_TYPE (t));
3979
3980     default:
3981       return t;
3982     }
3983 }
3984
3985 /* This is something of the form `int (*a)++' that has turned out to be an
3986    expr.  It was only converted into parse nodes, so we need to go through
3987    and build up the semantics.  Most of the work is done by
3988    build_expr_from_tree, above.
3989
3990    In the above example, TYPE is `int' and DECL is `*a'.  */
3991
3992 tree
3993 reparse_decl_as_expr (type, decl)
3994      tree type, decl;
3995 {
3996   decl = build_expr_from_tree (decl);
3997   if (type)
3998     return build_functional_cast (type, build_tree_list (NULL_TREE, decl));
3999   else
4000     return decl;
4001 }
4002
4003 /* This is something of the form `int (*a)' that has turned out to be a
4004    decl.  It was only converted into parse nodes, so we need to do the
4005    checking that make_{pointer,reference}_declarator do.  */
4006
4007 tree
4008 finish_decl_parsing (decl)
4009      tree decl;
4010 {
4011   switch (TREE_CODE (decl))
4012     {
4013     case IDENTIFIER_NODE:
4014       return decl;
4015     case INDIRECT_REF:
4016       return make_pointer_declarator
4017         (NULL_TREE, finish_decl_parsing (TREE_OPERAND (decl, 0)));
4018     case ADDR_EXPR:
4019       return make_reference_declarator
4020         (NULL_TREE, finish_decl_parsing (TREE_OPERAND (decl, 0)));
4021     case BIT_NOT_EXPR:
4022       TREE_OPERAND (decl, 0) = finish_decl_parsing (TREE_OPERAND (decl, 0));
4023       return decl;
4024     case SCOPE_REF:
4025       push_nested_class (TREE_TYPE (TREE_OPERAND (decl, 0)), 3);
4026       TREE_COMPLEXITY (decl) = current_class_depth;
4027       return decl;
4028     case ARRAY_REF:
4029       TREE_OPERAND (decl, 0) = finish_decl_parsing (TREE_OPERAND (decl, 0));
4030       return decl;
4031     case TREE_LIST:
4032       /* For attribute handling.  */
4033       TREE_VALUE (decl) = finish_decl_parsing (TREE_VALUE (decl));
4034       return decl;
4035     case TEMPLATE_ID_EXPR:
4036       return decl;
4037     default:
4038       abort ();
4039       return NULL_TREE;
4040     }
4041 }
4042
4043 /* Return 1 if root encloses child. */
4044
4045 static int
4046 is_namespace_ancestor (root, child)
4047      tree root, child;
4048 {
4049   if (root == child)
4050     return 1;
4051   if (root == global_namespace)
4052     return 1;
4053   if (child == global_namespace)
4054     return 0;
4055   return is_namespace_ancestor (root, CP_DECL_CONTEXT (child));
4056 }
4057   
4058
4059 /* Return the namespace that is the common ancestor 
4060    of two given namespaces. */
4061
4062 tree
4063 namespace_ancestor (ns1, ns2)
4064      tree ns1, ns2;
4065 {
4066   if (is_namespace_ancestor (ns1, ns2))
4067     return ns1;
4068   return namespace_ancestor (CP_DECL_CONTEXT (ns1), ns2);
4069 }
4070
4071 /* Insert used into the using list of user. Set indirect_flag if this
4072    directive is not directly from the source. Also find the common
4073    ancestor and let our users know about the new namespace */
4074 static void 
4075 add_using_namespace (user, used, indirect)
4076      tree user;
4077      tree used;
4078      int indirect;
4079 {
4080   tree t;
4081   /* Using oneself is a no-op. */
4082   if (user == used)
4083     return;
4084   my_friendly_assert (TREE_CODE (user) == NAMESPACE_DECL, 380);
4085   my_friendly_assert (TREE_CODE (used) == NAMESPACE_DECL, 380);
4086   /* Check if we already have this. */
4087   t = purpose_member (used, DECL_NAMESPACE_USING (user));
4088   if (t != NULL_TREE)
4089     {
4090       if (!indirect)
4091         /* Promote to direct usage. */
4092         TREE_INDIRECT_USING (t) = 0;
4093       return;
4094     }
4095
4096   /* Add used to the user's using list. */
4097   DECL_NAMESPACE_USING (user) 
4098     = tree_cons (used, namespace_ancestor (user, used), 
4099                  DECL_NAMESPACE_USING (user));
4100
4101   TREE_INDIRECT_USING (DECL_NAMESPACE_USING (user)) = indirect;
4102
4103   /* Add user to the used's users list. */
4104   DECL_NAMESPACE_USERS (used)
4105     = tree_cons (user, 0, DECL_NAMESPACE_USERS (used));
4106
4107   /* Recursively add all namespaces used. */
4108   for (t = DECL_NAMESPACE_USING (used); t; t = TREE_CHAIN (t))
4109     /* indirect usage */
4110     add_using_namespace (user, TREE_PURPOSE (t), 1);
4111
4112   /* Tell everyone using us about the new used namespaces. */
4113   for (t = DECL_NAMESPACE_USERS (user); t; t = TREE_CHAIN (t))
4114     add_using_namespace (TREE_PURPOSE (t), used, 1);
4115 }
4116
4117 /* Combines two sets of overloaded functions into an OVERLOAD chain, removing
4118    duplicates.  The first list becomes the tail of the result.
4119
4120    The algorithm is O(n^2).  We could get this down to O(n log n) by
4121    doing a sort on the addresses of the functions, if that becomes
4122    necessary.  */
4123
4124 static tree
4125 merge_functions (s1, s2)
4126      tree s1;
4127      tree s2;
4128 {
4129   for (; s2; s2 = OVL_NEXT (s2))
4130     {
4131       tree fn2 = OVL_CURRENT (s2);
4132       tree fns1;
4133
4134       for (fns1 = s1; fns1; fns1 = OVL_NEXT (fns1))
4135         {
4136           tree fn1 = OVL_CURRENT (fns1);
4137
4138           /* If the function from S2 is already in S1, there is no
4139              need to add it again.  For `extern "C"' functions, we
4140              might have two FUNCTION_DECLs for the same function, in
4141              different namespaces; again, we only need one of them.  */
4142           if (fn1 == fn2 
4143               || (DECL_EXTERN_C_P (fn1) && DECL_EXTERN_C_P (fn2)
4144                   && DECL_NAME (fn1) == DECL_NAME (fn2)))
4145             break;
4146         }
4147       
4148       /* If we exhausted all of the functions in S1, FN2 is new.  */
4149       if (!fns1)
4150         s1 = build_overload (fn2, s1);
4151     }
4152   return s1;
4153 }
4154
4155 /* This should return an error not all definitions define functions.
4156    It is not an error if we find two functions with exactly the
4157    same signature, only if these are selected in overload resolution.
4158    old is the current set of bindings, new the freshly-found binding.
4159    XXX Do we want to give *all* candidates in case of ambiguity?
4160    XXX In what way should I treat extern declarations?
4161    XXX I don't want to repeat the entire duplicate_decls here */
4162
4163 static tree
4164 ambiguous_decl (name, old, new, flags)
4165      tree name;
4166      tree old;
4167      tree new;
4168      int flags;
4169 {
4170   tree val, type;
4171   my_friendly_assert (old != NULL_TREE, 393);
4172   /* Copy the value. */
4173   val = BINDING_VALUE (new);
4174   if (val)
4175     switch (TREE_CODE (val))
4176       {
4177       case TEMPLATE_DECL:
4178         /* If we expect types or namespaces, and not templates,
4179            or this is not a template class. */
4180         if (LOOKUP_QUALIFIERS_ONLY (flags)
4181             && !DECL_CLASS_TEMPLATE_P (val))
4182           val = NULL_TREE;
4183         break;
4184       case TYPE_DECL:
4185         if (LOOKUP_NAMESPACES_ONLY (flags))
4186           val = NULL_TREE;
4187         break;
4188       case NAMESPACE_DECL:
4189         if (LOOKUP_TYPES_ONLY (flags))
4190           val = NULL_TREE;
4191         break;
4192       default:
4193         if (LOOKUP_QUALIFIERS_ONLY (flags))
4194           val = NULL_TREE;
4195       }
4196         
4197   if (!BINDING_VALUE (old))
4198     BINDING_VALUE (old) = val;
4199   else if (val && val != BINDING_VALUE (old))
4200     {
4201       if (is_overloaded_fn (BINDING_VALUE (old)) 
4202           && is_overloaded_fn (val))
4203         {
4204           BINDING_VALUE (old) = merge_functions (BINDING_VALUE (old),
4205                                                  val);
4206         }
4207       else
4208         {
4209           /* Some declarations are functions, some are not. */
4210           if (flags & LOOKUP_COMPLAIN)
4211             {
4212               /* If we've already given this error for this lookup,
4213                  BINDING_VALUE (old) is error_mark_node, so let's not
4214                  repeat ourselves.  */
4215               if (BINDING_VALUE (old) != error_mark_node)
4216                 {
4217                   error ("use of `%D' is ambiguous", name);
4218                   cp_error_at ("  first declared as `%#D' here",
4219                                BINDING_VALUE (old));
4220                 }
4221               cp_error_at ("  also declared as `%#D' here", val);
4222             }
4223           BINDING_VALUE (old) = error_mark_node;
4224         }
4225     }
4226   /* ... and copy the type. */
4227   type = BINDING_TYPE (new);
4228   if (LOOKUP_NAMESPACES_ONLY (flags))
4229     type = NULL_TREE;
4230   if (!BINDING_TYPE (old))
4231     BINDING_TYPE (old) = type;
4232   else if (type && BINDING_TYPE (old) != type)
4233     {
4234       if (flags & LOOKUP_COMPLAIN)
4235         {
4236           error ("`%D' denotes an ambiguous type",name);
4237           cp_error_at ("  first type here", BINDING_TYPE (old));
4238           cp_error_at ("  other type here", type);
4239         }
4240     }
4241   return old;
4242 }
4243
4244 /* Subroutine of unualified_namespace_lookup:
4245    Add the bindings of NAME in used namespaces to VAL.
4246    We are currently looking for names in namespace SCOPE, so we
4247    look through USINGS for using-directives of namespaces
4248    which have SCOPE as a common ancestor with the current scope.
4249    Returns zero on errors. */
4250
4251 int
4252 lookup_using_namespace (name, val, usings, scope, flags, spacesp)
4253      tree name, val, usings, scope;
4254      int flags;
4255      tree *spacesp;
4256 {
4257   tree iter;
4258   tree val1;
4259   /* Iterate over all used namespaces in current, searching for using
4260      directives of scope. */
4261   for (iter = usings; iter; iter = TREE_CHAIN (iter))
4262     if (TREE_VALUE (iter) == scope)
4263       {
4264         if (spacesp)
4265           *spacesp = tree_cons (TREE_PURPOSE (iter), NULL_TREE,
4266                                 *spacesp);
4267         val1 = binding_for_name (name, TREE_PURPOSE (iter));
4268         /* Resolve ambiguities. */
4269         val = ambiguous_decl (name, val, val1, flags);
4270       }
4271   return BINDING_VALUE (val) != error_mark_node;
4272 }
4273
4274 /* [namespace.qual]
4275    Accepts the NAME to lookup and its qualifying SCOPE.
4276    Returns the name/type pair found into the CPLUS_BINDING RESULT,
4277    or 0 on error. */
4278
4279 int
4280 qualified_lookup_using_namespace (name, scope, result, flags)
4281      tree name;
4282      tree scope;
4283      tree result;
4284      int flags;
4285 {
4286   /* Maintain a list of namespaces visited... */
4287   tree seen = NULL_TREE;
4288   /* ... and a list of namespace yet to see. */
4289   tree todo = NULL_TREE;
4290   tree usings;
4291   /* Look through namespace aliases.  */
4292   scope = ORIGINAL_NAMESPACE (scope);
4293   while (scope && (result != error_mark_node))
4294     {
4295       seen = tree_cons (scope, NULL_TREE, seen);
4296       result = ambiguous_decl (name, result,
4297                                binding_for_name (name, scope), flags);
4298       if (!BINDING_VALUE (result) && !BINDING_TYPE (result))
4299         /* Consider using directives. */
4300         for (usings = DECL_NAMESPACE_USING (scope); usings;
4301              usings = TREE_CHAIN (usings))
4302           /* If this was a real directive, and we have not seen it. */
4303           if (!TREE_INDIRECT_USING (usings)
4304               && !purpose_member (TREE_PURPOSE (usings), seen))
4305             todo = tree_cons (TREE_PURPOSE (usings), NULL_TREE, todo);
4306       if (todo)
4307         {
4308           scope = TREE_PURPOSE (todo);
4309           todo = TREE_CHAIN (todo);
4310         }
4311       else
4312         scope = NULL_TREE; /* If there never was a todo list. */
4313     }
4314   return result != error_mark_node;
4315 }
4316
4317 /* [namespace.memdef]/2 */
4318
4319 /* Set the context of a declaration to scope. Complain if we are not
4320    outside scope. */
4321
4322 void
4323 set_decl_namespace (decl, scope, friendp)
4324      tree decl;
4325      tree scope;
4326      int friendp;
4327 {
4328   tree old;
4329   
4330   /* Get rid of namespace aliases. */
4331   scope = ORIGINAL_NAMESPACE (scope);
4332   
4333   /* It is ok for friends to be qualified in parallel space.  */
4334   if (!friendp && !is_namespace_ancestor (current_namespace, scope))
4335     error ("declaration of `%D' not in a namespace surrounding `%D'",
4336               decl, scope);
4337   DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
4338   if (scope != current_namespace)
4339     {
4340       /* See whether this has been declared in the namespace. */
4341       old = namespace_binding (DECL_NAME (decl), scope);
4342       if (!old)
4343         /* No old declaration at all. */
4344         goto complain;
4345       /* A template can be explicitly specialized in any namespace.  */
4346       if (processing_explicit_instantiation)
4347         return;
4348       if (!is_overloaded_fn (decl))
4349         /* Don't compare non-function decls with decls_match here,
4350            since it can't check for the correct constness at this
4351            point. pushdecl will find those errors later.  */
4352         return;
4353       /* Since decl is a function, old should contain a function decl. */
4354       if (!is_overloaded_fn (old))
4355         goto complain;
4356       if (processing_template_decl || processing_specialization)
4357         /* We have not yet called push_template_decl to turn the
4358            FUNCTION_DECL into a TEMPLATE_DECL, so the declarations
4359            won't match.  But, we'll check later, when we construct the
4360            template.  */
4361         return;
4362       for (; old; old = OVL_NEXT (old))
4363         if (decls_match (decl, OVL_CURRENT (old)))
4364           return;
4365     }
4366   else
4367     return;
4368  complain:
4369   error ("`%D' should have been declared inside `%D'",
4370             decl, scope);
4371
4372
4373 /* Compute the namespace where a declaration is defined. */
4374
4375 static tree
4376 decl_namespace (decl)
4377      tree decl;
4378 {
4379   if (TYPE_P (decl))
4380     decl = TYPE_STUB_DECL (decl);
4381   while (DECL_CONTEXT (decl))
4382     {
4383       decl = DECL_CONTEXT (decl);
4384       if (TREE_CODE (decl) == NAMESPACE_DECL)
4385         return decl;
4386       if (TYPE_P (decl))
4387         decl = TYPE_STUB_DECL (decl);
4388       my_friendly_assert (DECL_P (decl), 390);
4389     }
4390
4391   return global_namespace;
4392 }
4393
4394 /* Return the namespace where the current declaration is declared. */
4395
4396 tree
4397 current_decl_namespace ()
4398 {
4399   tree result;
4400   /* If we have been pushed into a different namespace, use it. */
4401   if (decl_namespace_list)
4402     return TREE_PURPOSE (decl_namespace_list);
4403
4404   if (current_class_type)
4405     result = decl_namespace (TYPE_STUB_DECL (current_class_type));
4406   else if (current_function_decl)
4407     result = decl_namespace (current_function_decl);
4408   else 
4409     result = current_namespace;
4410   return result;
4411 }
4412
4413 /* Temporarily set the namespace for the current declaration. */
4414
4415 void
4416 push_decl_namespace (decl)
4417      tree decl;
4418 {
4419   if (TREE_CODE (decl) != NAMESPACE_DECL)
4420     decl = decl_namespace (decl);
4421   decl_namespace_list = tree_cons (ORIGINAL_NAMESPACE (decl),
4422                                    NULL_TREE, decl_namespace_list);
4423 }
4424
4425 void
4426 pop_decl_namespace ()
4427 {
4428   decl_namespace_list = TREE_CHAIN (decl_namespace_list);
4429 }
4430
4431 /* Enter a class or namespace scope. */
4432
4433 void
4434 push_scope (t)
4435      tree t;
4436 {
4437   if (TREE_CODE (t) == NAMESPACE_DECL)
4438     push_decl_namespace (t);
4439   else
4440     pushclass (t, 2);
4441 }
4442
4443 /* Leave scope pushed by push_scope. */
4444
4445 void
4446 pop_scope (t)
4447      tree t;
4448 {
4449   if (TREE_CODE (t) == NAMESPACE_DECL)
4450     pop_decl_namespace ();
4451   else
4452     popclass ();
4453 }
4454
4455 /* [basic.lookup.koenig] */
4456 /* A non-zero return value in the functions below indicates an error.
4457    All nodes allocated in the procedure are on the scratch obstack. */
4458
4459 struct arg_lookup
4460 {
4461   tree name;
4462   tree namespaces;
4463   tree classes;
4464   tree functions;
4465 };
4466
4467 static int arg_assoc         PARAMS ((struct arg_lookup*, tree));
4468 static int arg_assoc_args    PARAMS ((struct arg_lookup*, tree));
4469 static int arg_assoc_type    PARAMS ((struct arg_lookup*, tree));
4470 static int add_function      PARAMS ((struct arg_lookup *, tree));
4471 static int arg_assoc_namespace PARAMS ((struct arg_lookup *, tree));
4472 static int arg_assoc_class   PARAMS ((struct arg_lookup *, tree));
4473 static int arg_assoc_template_arg PARAMS ((struct arg_lookup*, tree));
4474
4475 /* Add a function to the lookup structure.
4476    Returns 1 on error.  */
4477
4478 static int
4479 add_function (k, fn)
4480      struct arg_lookup *k;
4481      tree fn;
4482 {
4483   /* We used to check here to see if the function was already in the list,
4484      but that's O(n^2), which is just too expensive for function lookup.
4485      Now we deal with the occasional duplicate in joust.  In doing this, we
4486      assume that the number of duplicates will be small compared to the
4487      total number of functions being compared, which should usually be the
4488      case.  */
4489
4490   /* We must find only functions, or exactly one non-function. */
4491   if (!k->functions) 
4492     k->functions = fn;
4493   else if (is_overloaded_fn (k->functions) && is_overloaded_fn (fn))
4494     k->functions = build_overload (fn, k->functions);
4495   else
4496     {
4497       tree f1 = OVL_CURRENT (k->functions);
4498       tree f2 = fn;
4499       if (is_overloaded_fn (f1))
4500         {
4501           fn = f1; f1 = f2; f2 = fn;
4502         }
4503       cp_error_at ("`%D' is not a function,", f1);
4504       cp_error_at ("  conflict with `%D'", f2);
4505       error ("  in call to `%D'", k->name);
4506       return 1;
4507     }
4508
4509   return 0;
4510 }
4511
4512 /* Add functions of a namespace to the lookup structure.
4513    Returns 1 on error.  */
4514
4515 static int
4516 arg_assoc_namespace (k, scope)
4517      struct arg_lookup *k;
4518      tree scope;
4519 {
4520   tree value;
4521
4522   if (purpose_member (scope, k->namespaces))
4523     return 0;
4524   k->namespaces = tree_cons (scope, NULL_TREE, k->namespaces);
4525   
4526   value = namespace_binding (k->name, scope);
4527   if (!value)
4528     return 0;
4529
4530   for (; value; value = OVL_NEXT (value))
4531     if (add_function (k, OVL_CURRENT (value)))
4532       return 1;
4533   
4534   return 0;
4535 }
4536
4537 /* Adds everything associated with a template argument to the lookup
4538    structure.  Returns 1 on error.  */
4539
4540 static int
4541 arg_assoc_template_arg (k, arg)
4542      struct arg_lookup* k;
4543      tree arg;
4544 {
4545   /* [basic.lookup.koenig]
4546
4547      If T is a template-id, its associated namespaces and classes are
4548      ... the namespaces and classes associated with the types of the
4549      template arguments provided for template type parameters
4550      (excluding template template parameters); the namespaces in which
4551      any template template arguments are defined; and the classes in
4552      which any member templates used as template template arguments
4553      are defined.  [Note: non-type template arguments do not
4554      contribute to the set of associated namespaces.  ]  */
4555
4556   /* Consider first template template arguments.  */
4557   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4558       || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
4559     return 0;
4560   else if (TREE_CODE (arg) == TEMPLATE_DECL)
4561     {
4562       tree ctx = CP_DECL_CONTEXT (arg);
4563
4564       /* It's not a member template.  */
4565       if (TREE_CODE (ctx) == NAMESPACE_DECL)
4566         return arg_assoc_namespace (k, ctx);
4567       /* Otherwise, it must be member template.  */
4568       else 
4569         return arg_assoc_class (k, ctx);
4570     }
4571   /* It's not a template template argument, but it is a type template
4572      argument.  */
4573   else if (TYPE_P (arg))
4574     return arg_assoc_type (k, arg);
4575   /* It's a non-type template argument.  */
4576   else
4577     return 0;
4578 }
4579
4580 /* Adds everything associated with class to the lookup structure.
4581    Returns 1 on error.  */
4582
4583 static int
4584 arg_assoc_class (k, type)
4585      struct arg_lookup* k;
4586      tree type;
4587 {
4588   tree list, friends, context;
4589   int i;
4590   
4591   /* Backend build structures, such as __builtin_va_list, aren't
4592      affected by all this.  */
4593   if (!CLASS_TYPE_P (type))
4594     return 0;
4595
4596   if (purpose_member (type, k->classes))
4597     return 0;
4598   k->classes = tree_cons (type, NULL_TREE, k->classes);
4599   
4600   context = decl_namespace (TYPE_MAIN_DECL (type));
4601   if (arg_assoc_namespace (k, context))
4602     return 1;
4603   
4604   /* Process baseclasses. */
4605   for (i = 0; i < CLASSTYPE_N_BASECLASSES (type); i++)
4606     if (arg_assoc_class (k, TYPE_BINFO_BASETYPE (type, i)))
4607       return 1;
4608   
4609   /* Process friends. */
4610   for (list = DECL_FRIENDLIST (TYPE_MAIN_DECL (type)); list; 
4611        list = TREE_CHAIN (list))
4612     if (k->name == TREE_PURPOSE (list))
4613       for (friends = TREE_VALUE (list); friends; 
4614            friends = TREE_CHAIN (friends))
4615         /* Only interested in global functions with potentially hidden
4616            (i.e. unqualified) declarations. */
4617         if (TREE_PURPOSE (friends) == error_mark_node && TREE_VALUE (friends)
4618             && decl_namespace (TREE_VALUE (friends)) == context)
4619           if (add_function (k, TREE_VALUE (friends)))
4620             return 1;
4621
4622   /* Process template arguments.  */
4623   if (CLASSTYPE_TEMPLATE_INFO (type))
4624     {
4625       list = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
4626       for (i = 0; i < TREE_VEC_LENGTH (list); ++i) 
4627         arg_assoc_template_arg (k, TREE_VEC_ELT (list, i));
4628     }
4629
4630   return 0;
4631 }
4632
4633 /* Adds everything associated with a given type.
4634    Returns 1 on error.  */
4635
4636 static int
4637 arg_assoc_type (k, type)
4638      struct arg_lookup *k;
4639      tree type;
4640 {
4641   switch (TREE_CODE (type))
4642     {
4643     case VOID_TYPE:
4644     case INTEGER_TYPE:
4645     case REAL_TYPE:
4646     case COMPLEX_TYPE:
4647     case VECTOR_TYPE:
4648     case CHAR_TYPE:
4649     case BOOLEAN_TYPE:
4650       return 0;
4651     case RECORD_TYPE:
4652       if (TYPE_PTRMEMFUNC_P (type))
4653         return arg_assoc_type (k, TYPE_PTRMEMFUNC_FN_TYPE (type));
4654       return arg_assoc_class (k, type);
4655     case POINTER_TYPE:
4656     case REFERENCE_TYPE:
4657     case ARRAY_TYPE:
4658       return arg_assoc_type (k, TREE_TYPE (type));
4659     case UNION_TYPE:
4660     case ENUMERAL_TYPE:
4661       return arg_assoc_namespace (k, decl_namespace (TYPE_MAIN_DECL (type)));
4662     case OFFSET_TYPE:
4663       /* Pointer to member: associate class type and value type. */
4664       if (arg_assoc_type (k, TYPE_OFFSET_BASETYPE (type)))
4665         return 1;
4666       return arg_assoc_type (k, TREE_TYPE (type));
4667     case METHOD_TYPE:
4668       /* The basetype is referenced in the first arg type, so just
4669          fall through.  */
4670     case FUNCTION_TYPE:
4671       /* Associate the parameter types. */
4672       if (arg_assoc_args (k, TYPE_ARG_TYPES (type)))
4673         return 1;
4674       /* Associate the return type. */
4675       return arg_assoc_type (k, TREE_TYPE (type));
4676     case TEMPLATE_TYPE_PARM:
4677     case BOUND_TEMPLATE_TEMPLATE_PARM:
4678       return 0;
4679     case TYPENAME_TYPE:
4680       return 0;
4681     case LANG_TYPE:
4682       if (type == unknown_type_node)
4683         return 0;
4684       /* else fall through */
4685     default:
4686       abort ();
4687     }
4688   return 0;
4689 }
4690
4691 /* Adds everything associated with arguments.  Returns 1 on error.  */
4692
4693 static int
4694 arg_assoc_args (k, args)
4695      struct arg_lookup* k;
4696      tree args;
4697 {
4698   for (; args; args = TREE_CHAIN (args))
4699     if (arg_assoc (k, TREE_VALUE (args)))
4700       return 1;
4701   return 0;
4702 }
4703
4704 /* Adds everything associated with a given tree_node.  Returns 1 on error.  */
4705
4706 static int
4707 arg_assoc (k, n)
4708      struct arg_lookup* k;
4709      tree n;
4710 {
4711   if (n == error_mark_node)
4712     return 0;
4713
4714   if (TYPE_P (n))
4715     return arg_assoc_type (k, n);
4716
4717   if (! type_unknown_p (n))
4718     return arg_assoc_type (k, TREE_TYPE (n));
4719
4720   if (TREE_CODE (n) == ADDR_EXPR)
4721     n = TREE_OPERAND (n, 0);
4722   if (TREE_CODE (n) == COMPONENT_REF)
4723     n = TREE_OPERAND (n, 1);
4724   if (TREE_CODE (n) == OFFSET_REF)
4725     n = TREE_OPERAND (n, 1);
4726   while (TREE_CODE (n) == TREE_LIST)
4727     n = TREE_VALUE (n);
4728
4729   if (TREE_CODE (n) == FUNCTION_DECL)
4730     return arg_assoc_type (k, TREE_TYPE (n));
4731   if (TREE_CODE (n) == TEMPLATE_ID_EXPR)
4732     {
4733       /* [basic.lookup.koenig]
4734
4735          If T is a template-id, its associated namespaces and classes
4736          are the namespace in which the template is defined; for
4737          member templates, the member template's class...  */
4738       tree template = TREE_OPERAND (n, 0);
4739       tree args = TREE_OPERAND (n, 1);
4740       tree ctx;
4741       tree arg;
4742
4743       if (TREE_CODE (template) == COMPONENT_REF)
4744         template = TREE_OPERAND (template, 1);
4745       
4746       /* First, the template.  There may actually be more than one if
4747          this is an overloaded function template.  But, in that case,
4748          we only need the first; all the functions will be in the same
4749          namespace.  */
4750       template = OVL_CURRENT (template);
4751
4752       ctx = CP_DECL_CONTEXT (template);
4753        
4754       if (TREE_CODE (ctx) == NAMESPACE_DECL)
4755         {
4756           if (arg_assoc_namespace (k, ctx) == 1)
4757             return 1;
4758         }
4759       /* It must be a member template.  */
4760       else if (arg_assoc_class (k, ctx) == 1)
4761         return 1;
4762
4763       /* Now the arguments.  */
4764       for (arg = args; arg != NULL_TREE; arg = TREE_CHAIN (arg))
4765         if (arg_assoc_template_arg (k, TREE_VALUE (arg)) == 1)
4766           return 1;
4767     }
4768   else
4769     {
4770       my_friendly_assert (TREE_CODE (n) == OVERLOAD, 980715);
4771       
4772       for (; n; n = OVL_CHAIN (n))
4773         if (arg_assoc_type (k, TREE_TYPE (OVL_FUNCTION (n))))
4774           return 1;
4775     }
4776
4777   return 0;
4778 }
4779
4780 /* Performs Koenig lookup depending on arguments, where fns
4781    are the functions found in normal lookup. */
4782
4783 tree
4784 lookup_arg_dependent (name, fns, args)
4785      tree name;
4786      tree fns;
4787      tree args;
4788 {
4789   struct arg_lookup k;
4790   tree fn = NULL_TREE;
4791
4792   k.name = name;
4793   k.functions = fns;
4794   k.classes = NULL_TREE;
4795
4796   /* Note that we've already looked at some namespaces during normal
4797      unqualified lookup, unless we found a decl in function scope.  */
4798   if (fns)
4799     fn = OVL_CURRENT (fns);
4800   if (fn && TREE_CODE (fn) == FUNCTION_DECL && DECL_LOCAL_FUNCTION_P (fn))
4801     k.namespaces = NULL_TREE;
4802   else
4803     unqualified_namespace_lookup (name, 0, &k.namespaces);
4804
4805   arg_assoc_args (&k, args);
4806   return k.functions;
4807 }
4808
4809 /* Process a namespace-alias declaration. */
4810
4811 void
4812 do_namespace_alias (alias, namespace)
4813      tree alias, namespace;
4814 {
4815   if (TREE_CODE (namespace) != NAMESPACE_DECL)
4816     {
4817       /* The parser did not find it, so it's not there. */
4818       error ("unknown namespace `%D'", namespace);
4819       return;
4820     }
4821
4822   namespace = ORIGINAL_NAMESPACE (namespace);
4823
4824   /* Build the alias. */
4825   alias = build_lang_decl (NAMESPACE_DECL, alias, void_type_node);     
4826   DECL_NAMESPACE_ALIAS (alias) = namespace;
4827   pushdecl (alias);
4828 }
4829
4830 /* Check a non-member using-declaration. Return the name and scope
4831    being used, and the USING_DECL, or NULL_TREE on failure. */
4832
4833 static tree
4834 validate_nonmember_using_decl (decl, scope, name)
4835      tree decl;
4836      tree *scope;
4837      tree *name;
4838 {
4839   if (TREE_CODE (decl) == SCOPE_REF)
4840     {
4841       *scope = TREE_OPERAND (decl, 0);
4842       *name = TREE_OPERAND (decl, 1);
4843
4844       if (!processing_template_decl)
4845         {
4846           /* [namespace.udecl]
4847              A using-declaration for a class member shall be a
4848              member-declaration.  */
4849           if(TREE_CODE (*scope) != NAMESPACE_DECL)
4850             {
4851               if (TYPE_P (*scope))
4852                 error ("`%T' is not a namespace", *scope);
4853               else
4854                 error ("`%D' is not a namespace", *scope);
4855               return NULL_TREE;
4856             }
4857           
4858           /* 7.3.3/5
4859              A using-declaration shall not name a template-id.  */
4860           if (TREE_CODE (*name) == TEMPLATE_ID_EXPR)
4861             {
4862               *name = TREE_OPERAND (*name, 0);
4863               error ("a using-declaration cannot specify a template-id.  Try `using %D'", *name);
4864               return NULL_TREE;
4865             }
4866         }
4867     }
4868   else if (TREE_CODE (decl) == IDENTIFIER_NODE
4869            || TREE_CODE (decl) == TYPE_DECL
4870            || TREE_CODE (decl) == TEMPLATE_DECL)
4871     {
4872       *scope = global_namespace;
4873       *name = decl;
4874     }
4875   else if (TREE_CODE (decl) == NAMESPACE_DECL)
4876     {
4877       error ("namespace `%D' not allowed in using-declaration", decl);
4878       return NULL_TREE;
4879     }
4880   else
4881     abort ();
4882   if (DECL_P (*name))
4883     *name = DECL_NAME (*name);
4884   /* Make a USING_DECL. */
4885   return push_using_decl (*scope, *name);
4886 }
4887
4888 /* Process local and global using-declarations. */
4889
4890 static void
4891 do_nonmember_using_decl (scope, name, oldval, oldtype, newval, newtype)
4892      tree scope, name;
4893      tree oldval, oldtype;
4894      tree *newval, *newtype;
4895 {
4896   tree decls;
4897
4898   *newval = *newtype = NULL_TREE;
4899   decls = make_node (CPLUS_BINDING);
4900   if (!qualified_lookup_using_namespace (name, scope, decls, 0))
4901     /* Lookup error */
4902     return;
4903
4904   if (!BINDING_VALUE (decls) && !BINDING_TYPE (decls))
4905     {
4906       error ("`%D' not declared", name);
4907       return;
4908     }
4909
4910   /* Check for using functions. */
4911   if (BINDING_VALUE (decls) && is_overloaded_fn (BINDING_VALUE (decls)))
4912     {
4913       tree tmp, tmp1;
4914
4915       if (oldval && !is_overloaded_fn (oldval))
4916         {
4917           duplicate_decls (OVL_CURRENT (BINDING_VALUE (decls)), oldval);
4918           oldval = NULL_TREE;
4919         }
4920
4921       *newval = oldval;
4922       for (tmp = BINDING_VALUE (decls); tmp; tmp = OVL_NEXT (tmp))
4923         {
4924           tree new_fn = OVL_CURRENT (tmp);
4925
4926           /* [namespace.udecl]
4927
4928              If a function declaration in namespace scope or block
4929              scope has the same name and the same parameter types as a
4930              function introduced by a using declaration the program is
4931              ill-formed.  */
4932           for (tmp1 = oldval; tmp1; tmp1 = OVL_NEXT (tmp1))
4933             {
4934               tree old_fn = OVL_CURRENT (tmp1);
4935
4936               if (new_fn == old_fn)
4937                 /* The function already exists in the current namespace.  */
4938                 break;
4939               else if (OVL_USED (tmp1))
4940                 continue; /* this is a using decl */
4941               else if (compparms (TYPE_ARG_TYPES (TREE_TYPE (new_fn)),
4942                                   TYPE_ARG_TYPES (TREE_TYPE (old_fn))))
4943                 {
4944                   /* There was already a non-using declaration in
4945                      this scope with the same parameter types. If both
4946                      are the same extern "C" functions, that's ok.  */
4947                   if (!decls_match (new_fn, old_fn))
4948                     error ("`%D' is already declared in this scope", name);
4949                   break;
4950                 }
4951             }
4952
4953           /* If we broke out of the loop, there's no reason to add
4954              this function to the using declarations for this
4955              scope.  */
4956           if (tmp1)
4957             continue;
4958             
4959           *newval = build_overload (OVL_CURRENT (tmp), *newval);
4960           if (TREE_CODE (*newval) != OVERLOAD)
4961             *newval = ovl_cons (*newval, NULL_TREE);
4962           OVL_USED (*newval) = 1;
4963         }
4964     }
4965   else 
4966     {
4967       *newval = BINDING_VALUE (decls);
4968       if (oldval)
4969         duplicate_decls (*newval, oldval);
4970     } 
4971
4972   *newtype = BINDING_TYPE (decls);
4973   if (oldtype && *newtype && oldtype != *newtype)
4974     {
4975       error ("using declaration `%D' introduced ambiguous type `%T'",
4976                 name, oldtype);
4977       return;
4978     }
4979 }
4980
4981 /* Process a using-declaration not appearing in class or local scope. */
4982
4983 void
4984 do_toplevel_using_decl (decl)
4985      tree decl;
4986 {
4987   tree scope, name, binding;
4988   tree oldval, oldtype, newval, newtype;
4989
4990   decl = validate_nonmember_using_decl (decl, &scope, &name);
4991   if (decl == NULL_TREE)
4992     return;
4993   
4994   binding = binding_for_name (name, current_namespace);
4995
4996   oldval = BINDING_VALUE (binding);
4997   oldtype = BINDING_TYPE (binding);
4998
4999   do_nonmember_using_decl (scope, name, oldval, oldtype, &newval, &newtype);
5000
5001   /* Copy declarations found. */
5002   if (newval)
5003     BINDING_VALUE (binding) = newval;
5004   if (newtype)
5005     BINDING_TYPE (binding) = newtype;
5006   return;
5007 }
5008
5009 /* Process a using-declaration at function scope.  */
5010
5011 void
5012 do_local_using_decl (decl)
5013      tree decl;
5014 {
5015   tree scope, name;
5016   tree oldval, oldtype, newval, newtype;
5017
5018   decl = validate_nonmember_using_decl (decl, &scope, &name);
5019   if (decl == NULL_TREE)
5020     return;
5021
5022   if (building_stmt_tree ()
5023       && at_function_scope_p ())
5024     add_decl_stmt (decl);
5025
5026   oldval = lookup_name_current_level (name);
5027   oldtype = lookup_type_current_level (name);
5028
5029   do_nonmember_using_decl (scope, name, oldval, oldtype, &newval, &newtype);
5030
5031   if (newval)
5032     {
5033       if (is_overloaded_fn (newval))
5034         {
5035           tree fn, term;
5036
5037           /* We only need to push declarations for those functions
5038              that were not already bound in the current level.
5039              The old value might be NULL_TREE, it might be a single
5040              function, or an OVERLOAD.  */
5041           if (oldval && TREE_CODE (oldval) == OVERLOAD)
5042             term = OVL_FUNCTION (oldval);
5043           else
5044             term = oldval;
5045           for (fn = newval; fn && OVL_CURRENT (fn) != term; 
5046                fn = OVL_NEXT (fn))
5047             push_overloaded_decl (OVL_CURRENT (fn), 
5048                                   PUSH_LOCAL | PUSH_USING);
5049         }
5050       else
5051         push_local_binding (name, newval, PUSH_USING);
5052     }
5053   if (newtype)
5054     set_identifier_type_value (name, newtype);
5055 }
5056
5057 tree
5058 do_class_using_decl (decl)
5059      tree decl;
5060 {
5061   tree name, value;
5062
5063   if (TREE_CODE (decl) != SCOPE_REF
5064       || !TYPE_P (TREE_OPERAND (decl, 0)))
5065     {
5066       error ("using-declaration for non-member at class scope");
5067       return NULL_TREE;
5068     }
5069   name = TREE_OPERAND (decl, 1);
5070   if (TREE_CODE (name) == BIT_NOT_EXPR)
5071     {
5072       error ("using-declaration for destructor");
5073       return NULL_TREE;
5074     }
5075   else if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
5076     {
5077       name = TREE_OPERAND (name, 0);
5078       error ("a using-declaration cannot specify a template-id.  Try  `using %T::%D'", TREE_OPERAND (decl, 0), name);
5079       return NULL_TREE;
5080     }
5081   if (TREE_CODE (name) == TYPE_DECL || TREE_CODE (name) == TEMPLATE_DECL)
5082     name = DECL_NAME (name);
5083
5084   my_friendly_assert (TREE_CODE (name) == IDENTIFIER_NODE, 980716);
5085
5086   value = build_lang_decl (USING_DECL, name, void_type_node);
5087   DECL_INITIAL (value) = TREE_OPERAND (decl, 0);
5088   return value;
5089 }
5090
5091 /* Process a using-directive. */
5092
5093 void
5094 do_using_directive (namespace)
5095      tree namespace;
5096 {
5097   if (building_stmt_tree ())
5098     add_stmt (build_stmt (USING_STMT, namespace));
5099   
5100   /* using namespace A::B::C; */
5101   if (TREE_CODE (namespace) == SCOPE_REF)
5102       namespace = TREE_OPERAND (namespace, 1);
5103   if (TREE_CODE (namespace) == IDENTIFIER_NODE)
5104     {
5105       /* Lookup in lexer did not find a namespace. */
5106       if (!processing_template_decl)
5107         error ("namespace `%T' undeclared", namespace);
5108       return;
5109     }
5110   if (TREE_CODE (namespace) != NAMESPACE_DECL)
5111     {
5112       if (!processing_template_decl)
5113         error ("`%T' is not a namespace", namespace);
5114       return;
5115     }
5116   namespace = ORIGINAL_NAMESPACE (namespace);
5117   if (!toplevel_bindings_p ())
5118     push_using_directive (namespace);
5119   else
5120     /* direct usage */
5121     add_using_namespace (current_namespace, namespace, 0);
5122 }
5123
5124 void
5125 check_default_args (x)
5126      tree x;
5127 {
5128   tree arg = TYPE_ARG_TYPES (TREE_TYPE (x));
5129   int saw_def = 0, i = 0 - (TREE_CODE (TREE_TYPE (x)) == METHOD_TYPE);
5130   for (; arg && arg != void_list_node; arg = TREE_CHAIN (arg), ++i)
5131     {
5132       if (TREE_PURPOSE (arg))
5133         saw_def = 1;
5134       else if (saw_def)
5135         {
5136           cp_error_at ("default argument missing for parameter %P of `%+#D'",
5137                        i, x);
5138           break;
5139         }
5140     }
5141 }
5142
5143 void
5144 mark_used (decl)
5145      tree decl;
5146 {
5147   TREE_USED (decl) = 1;
5148   if (processing_template_decl)
5149     return;
5150   assemble_external (decl);
5151
5152   /* Is it a synthesized method that needs to be synthesized?  */
5153   if (TREE_CODE (decl) == FUNCTION_DECL
5154       && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
5155       && DECL_ARTIFICIAL (decl) 
5156       && ! DECL_INITIAL (decl)
5157       /* Kludge: don't synthesize for default args.  */
5158       && current_function_decl)
5159     {
5160       synthesize_method (decl);
5161       /* If we've already synthesized the method we don't need to
5162          instantiate it, so we can return right away.  */
5163       return;
5164     }
5165
5166   /* If this is a function or variable that is an instance of some
5167      template, we now know that we will need to actually do the
5168      instantiation. We check that DECL is not an explicit
5169      instantiation because that is not checked in instantiate_decl.  */
5170   if ((DECL_NON_THUNK_FUNCTION_P (decl) || TREE_CODE (decl) == VAR_DECL)
5171       && DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
5172       && (!DECL_EXPLICIT_INSTANTIATION (decl)
5173           || (TREE_CODE (decl) == FUNCTION_DECL && DECL_INLINE (decl))))
5174     instantiate_decl (decl, /*defer_ok=*/1);
5175 }
5176
5177 /* Helper function for class_head_decl and class_head_defn
5178    nonterminals. AGGR is the class, union or struct tag. SCOPE is the
5179    explicit scope used (NULL for no scope resolution). ID is the
5180    name. DEFN_P is true, if this is a definition of the class and
5181    NEW_TYPE_P is set to non-zero, if we push into the scope containing
5182    the to be defined aggregate.
5183    
5184    Return a TYPE_DECL for the type declared by ID in SCOPE.  */
5185
5186 tree
5187 handle_class_head (aggr, scope, id, defn_p, new_type_p)
5188      tree aggr, scope, id;
5189      int defn_p;
5190      int *new_type_p;
5191 {
5192   tree decl = NULL_TREE;
5193   tree current = current_scope ();
5194   bool xrefd_p = false;
5195   
5196   if (current == NULL_TREE)
5197     current = current_namespace;
5198
5199   *new_type_p = 0;
5200   
5201   if (scope)
5202     {
5203       if (TREE_CODE (id) == TYPE_DECL)
5204         /* We must bash typedefs back to the main decl of the
5205            type. Otherwise we become confused about scopes.  */
5206         decl = TYPE_MAIN_DECL (TREE_TYPE (id));
5207       else if (DECL_CLASS_TEMPLATE_P (id))
5208         decl = DECL_TEMPLATE_RESULT (id);
5209       else
5210         {
5211           if (TYPE_P (scope))
5212             {
5213               /* According to the suggested resolution of core issue
5214                  180, 'typename' is assumed after a class-key.  */
5215               decl = make_typename_type (scope, id, tf_error);
5216               if (decl != error_mark_node)
5217                 decl = TYPE_MAIN_DECL (decl);
5218               else
5219                 decl = NULL_TREE;
5220             }
5221           else if (scope == current)
5222             {
5223               /* We've been given AGGR SCOPE::ID, when we're already
5224                  inside SCOPE.  Be nice about it.  */
5225               if (pedantic)
5226                 pedwarn ("extra qualification `%T::' on member `%D' ignored",
5227                          scope, id);
5228             }
5229           else
5230             error ("`%T' does not have a class or union named `%D'",
5231                    scope, id);
5232         }
5233     }
5234   
5235   if (!decl)
5236     {
5237       decl = TYPE_MAIN_DECL (xref_tag (aggr, id, !defn_p));
5238       xrefd_p = true;
5239     }
5240
5241   if (!TYPE_BINFO (TREE_TYPE (decl)))
5242     {
5243       error ("`%T' is not a class or union type", decl);
5244       return error_mark_node;
5245     }
5246   
5247   if (defn_p)
5248     {
5249       /* For a definition, we want to enter the containing scope
5250          before looking up any base classes etc. Only do so, if this
5251          is different to the current scope.  */
5252       tree context = CP_DECL_CONTEXT (decl);
5253
5254       *new_type_p = (current != context
5255                      && TREE_CODE (context) != TEMPLATE_TYPE_PARM
5256                      && TREE_CODE (context) != BOUND_TEMPLATE_TEMPLATE_PARM);
5257       if (*new_type_p)
5258         push_scope (context);
5259   
5260       if (!xrefd_p && PROCESSING_REAL_TEMPLATE_DECL_P ())
5261         decl = push_template_decl (decl);
5262     }
5263
5264   return decl;
5265 }
5266
5267 /* Initialize decl2.c.  */
5268
5269 void
5270 init_decl2 ()
5271 {
5272   ggc_add_tree_varray_root (&deferred_fns, 1);
5273   ggc_add_tree_varray_root (&pending_statics, 1);
5274   ggc_add_tree_varray_root (&ssdf_decls, 1);
5275   ggc_add_tree_root (&ssdf_decl, 1);
5276   ggc_add_tree_root (&priority_decl, 1);
5277   ggc_add_tree_root (&initialize_p_decl, 1);
5278 }