OSDN Git Service

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