OSDN Git Service

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