OSDN Git Service

2009-08-16 Richard Guenther <rguenther@suse.de>
[pf3gnuchains/gcc-fork.git] / gcc / cp / decl.c
1 /* Process declarations and variables for C++ compiler.
2    Copyright (C) 1988, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
4    Free Software Foundation, Inc.
5    Contributed by Michael Tiemann (tiemann@cygnus.com)
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23
24 /* Process declarations and symbol lookup for C++ front end.
25    Also constructs types; the standard scalar types at initialization,
26    and structure, union, array and enum types when they are declared.  */
27
28 /* ??? not all decl nodes are given the most useful possible
29    line numbers.  For example, the CONST_DECLs for enum values.  */
30
31 #include "config.h"
32 #include "system.h"
33 #include "coretypes.h"
34 #include "tm.h"
35 #include "tree.h"
36 #include "rtl.h"
37 #include "expr.h"
38 #include "flags.h"
39 #include "cp-tree.h"
40 #include "tree-inline.h"
41 #include "decl.h"
42 #include "output.h"
43 #include "except.h"
44 #include "toplev.h"
45 #include "hashtab.h"
46 #include "tm_p.h"
47 #include "target.h"
48 #include "c-common.h"
49 #include "c-pragma.h"
50 #include "diagnostic.h"
51 #include "intl.h"
52 #include "debug.h"
53 #include "timevar.h"
54 #include "tree-flow.h"
55 #include "pointer-set.h"
56 #include "plugin.h"
57
58 static tree grokparms (tree parmlist, tree *);
59 static const char *redeclaration_error_message (tree, tree);
60
61 static int decl_jump_unsafe (tree);
62 static void require_complete_types_for_parms (tree);
63 static int ambi_op_p (enum tree_code);
64 static int unary_op_p (enum tree_code);
65 static void push_local_name (tree);
66 static tree grok_reference_init (tree, tree, tree, tree *);
67 static tree grokvardecl (tree, tree, const cp_decl_specifier_seq *,
68                          int, int, tree);
69 static void record_unknown_type (tree, const char *);
70 static tree builtin_function_1 (tree, tree, bool);
71 static tree build_library_fn_1 (tree, enum tree_code, tree);
72 static int member_function_or_else (tree, tree, enum overload_flags);
73 static void bad_specifiers (tree, const char *, int, int, int, int,
74                             int);
75 static void check_for_uninitialized_const_var (tree);
76 static hashval_t typename_hash (const void *);
77 static int typename_compare (const void *, const void *);
78 static tree local_variable_p_walkfn (tree *, int *, void *);
79 static tree record_builtin_java_type (const char *, int);
80 static const char *tag_name (enum tag_types);
81 static tree lookup_and_check_tag (enum tag_types, tree, tag_scope, bool);
82 static int walk_namespaces_r (tree, walk_namespaces_fn, void *);
83 static void maybe_deduce_size_from_array_init (tree, tree);
84 static void layout_var_decl (tree);
85 static tree check_initializer (tree, tree, int, tree *);
86 static void make_rtl_for_nonlocal_decl (tree, tree, const char *);
87 static void save_function_data (tree);
88 static void check_function_type (tree, tree);
89 static void finish_constructor_body (void);
90 static void begin_destructor_body (void);
91 static void finish_destructor_body (void);
92 static tree create_array_type_for_decl (tree, tree, tree);
93 static tree get_atexit_node (void);
94 static tree get_dso_handle_node (void);
95 static tree start_cleanup_fn (void);
96 static void end_cleanup_fn (void);
97 static tree cp_make_fname_decl (location_t, tree, int);
98 static void initialize_predefined_identifiers (void);
99 static tree check_special_function_return_type
100         (special_function_kind, tree, tree);
101 static tree push_cp_library_fn (enum tree_code, tree);
102 static tree build_cp_library_fn (tree, enum tree_code, tree);
103 static void store_parm_decls (tree);
104 static void initialize_local_var (tree, tree);
105 static void expand_static_init (tree, tree);
106 static tree next_initializable_field (tree);
107
108 /* The following symbols are subsumed in the cp_global_trees array, and
109    listed here individually for documentation purposes.
110
111    C++ extensions
112         tree wchar_decl_node;
113
114         tree vtable_entry_type;
115         tree delta_type_node;
116         tree __t_desc_type_node;
117
118         tree class_type_node;
119         tree unknown_type_node;
120
121    Array type `vtable_entry_type[]'
122
123         tree vtbl_type_node;
124         tree vtbl_ptr_type_node;
125
126    Namespaces,
127
128         tree std_node;
129         tree abi_node;
130
131    A FUNCTION_DECL which can call `abort'.  Not necessarily the
132    one that the user will declare, but sufficient to be called
133    by routines that want to abort the program.
134
135         tree abort_fndecl;
136
137    The FUNCTION_DECL for the default `::operator delete'.
138
139         tree global_delete_fndecl;
140
141    Used by RTTI
142         tree type_info_type_node, tinfo_decl_id, tinfo_decl_type;
143         tree tinfo_var_id;  */
144
145 tree cp_global_trees[CPTI_MAX];
146
147 /* Indicates that there is a type value in some namespace, although
148    that is not necessarily in scope at the moment.  */
149
150 tree global_type_node;
151
152 /* The node that holds the "name" of the global scope.  */
153 tree global_scope_name;
154
155 #define local_names cp_function_chain->x_local_names
156
157 /* A list of objects which have constructors or destructors
158    which reside in the global scope.  The decl is stored in
159    the TREE_VALUE slot and the initializer is stored
160    in the TREE_PURPOSE slot.  */
161 tree static_aggregates;
162
163 /* -- end of C++ */
164
165 /* A node for the integer constants 2, and 3.  */
166
167 tree integer_two_node, integer_three_node;
168
169 /* Used only for jumps to as-yet undefined labels, since jumps to
170    defined labels can have their validity checked immediately.  */
171
172 struct GTY(()) named_label_use_entry {
173   struct named_label_use_entry *next;
174   /* The binding level to which this entry is *currently* attached.
175      This is initially the binding level in which the goto appeared,
176      but is modified as scopes are closed.  */
177   struct cp_binding_level *binding_level;
178   /* The head of the names list that was current when the goto appeared,
179      or the inner scope popped.  These are the decls that will *not* be
180      skipped when jumping to the label.  */
181   tree names_in_scope;
182   /* The location of the goto, for error reporting.  */
183   location_t o_goto_locus;
184   /* True if an OpenMP structured block scope has been closed since
185      the goto appeared.  This means that the branch from the label will
186      illegally exit an OpenMP scope.  */
187   bool in_omp_scope;
188 };
189
190 /* A list of all LABEL_DECLs in the function that have names.  Here so
191    we can clear out their names' definitions at the end of the
192    function, and so we can check the validity of jumps to these labels.  */
193
194 struct GTY(()) named_label_entry {
195   /* The decl itself.  */
196   tree label_decl;
197
198   /* The binding level to which the label is *currently* attached.
199      This is initially set to the binding level in which the label
200      is defined, but is modified as scopes are closed.  */
201   struct cp_binding_level *binding_level;
202   /* The head of the names list that was current when the label was
203      defined, or the inner scope popped.  These are the decls that will
204      be skipped when jumping to the label.  */
205   tree names_in_scope;
206   /* A tree list of all decls from all binding levels that would be
207      crossed by a backward branch to the label.  */
208   tree bad_decls;
209
210   /* A list of uses of the label, before the label is defined.  */
211   struct named_label_use_entry *uses;
212
213   /* The following bits are set after the label is defined, and are
214      updated as scopes are popped.  They indicate that a backward jump
215      to the label will illegally enter a scope of the given flavor.  */
216   bool in_try_scope;
217   bool in_catch_scope;
218   bool in_omp_scope;
219 };
220
221 #define named_labels cp_function_chain->x_named_labels
222 \f
223 /* The number of function bodies which we are currently processing.
224    (Zero if we are at namespace scope, one inside the body of a
225    function, two inside the body of a function in a local class, etc.)  */
226 int function_depth;
227
228 /* To avoid unwanted recursion, finish_function defers all mark_used calls
229    encountered during its execution until it finishes.  */
230 bool defer_mark_used_calls;
231 VEC(tree, gc) *deferred_mark_used_calls;
232
233 /* States indicating how grokdeclarator() should handle declspecs marked
234    with __attribute__((deprecated)).  An object declared as
235    __attribute__((deprecated)) suppresses warnings of uses of other
236    deprecated items.  */
237 enum deprecated_states deprecated_state = DEPRECATED_NORMAL;
238
239 \f
240 /* A TREE_LIST of VAR_DECLs.  The TREE_PURPOSE is a RECORD_TYPE or
241    UNION_TYPE; the TREE_VALUE is a VAR_DECL with that type.  At the
242    time the VAR_DECL was declared, the type was incomplete.  */
243
244 static GTY(()) tree incomplete_vars;
245 \f
246 /* Returns the kind of template specialization we are currently
247    processing, given that it's declaration contained N_CLASS_SCOPES
248    explicit scope qualifications.  */
249
250 tmpl_spec_kind
251 current_tmpl_spec_kind (int n_class_scopes)
252 {
253   int n_template_parm_scopes = 0;
254   int seen_specialization_p = 0;
255   int innermost_specialization_p = 0;
256   struct cp_binding_level *b;
257
258   /* Scan through the template parameter scopes.  */
259   for (b = current_binding_level;
260        b->kind == sk_template_parms;
261        b = b->level_chain)
262     {
263       /* If we see a specialization scope inside a parameter scope,
264          then something is wrong.  That corresponds to a declaration
265          like:
266
267             template <class T> template <> ...
268
269          which is always invalid since [temp.expl.spec] forbids the
270          specialization of a class member template if the enclosing
271          class templates are not explicitly specialized as well.  */
272       if (b->explicit_spec_p)
273         {
274           if (n_template_parm_scopes == 0)
275             innermost_specialization_p = 1;
276           else
277             seen_specialization_p = 1;
278         }
279       else if (seen_specialization_p == 1)
280         return tsk_invalid_member_spec;
281
282       ++n_template_parm_scopes;
283     }
284
285   /* Handle explicit instantiations.  */
286   if (processing_explicit_instantiation)
287     {
288       if (n_template_parm_scopes != 0)
289         /* We've seen a template parameter list during an explicit
290            instantiation.  For example:
291
292              template <class T> template void f(int);
293
294            This is erroneous.  */
295         return tsk_invalid_expl_inst;
296       else
297         return tsk_expl_inst;
298     }
299
300   if (n_template_parm_scopes < n_class_scopes)
301     /* We've not seen enough template headers to match all the
302        specialized classes present.  For example:
303
304          template <class T> void R<T>::S<T>::f(int);
305
306        This is invalid; there needs to be one set of template
307        parameters for each class.  */
308     return tsk_insufficient_parms;
309   else if (n_template_parm_scopes == n_class_scopes)
310     /* We're processing a non-template declaration (even though it may
311        be a member of a template class.)  For example:
312
313          template <class T> void S<T>::f(int);
314
315        The `class T' matches the `S<T>', leaving no template headers
316        corresponding to the `f'.  */
317     return tsk_none;
318   else if (n_template_parm_scopes > n_class_scopes + 1)
319     /* We've got too many template headers.  For example:
320
321          template <> template <class T> void f (T);
322
323        There need to be more enclosing classes.  */
324     return tsk_excessive_parms;
325   else
326     /* This must be a template.  It's of the form:
327
328          template <class T> template <class U> void S<T>::f(U);
329
330        This is a specialization if the innermost level was a
331        specialization; otherwise it's just a definition of the
332        template.  */
333     return innermost_specialization_p ? tsk_expl_spec : tsk_template;
334 }
335
336 /* Exit the current scope.  */
337
338 void
339 finish_scope (void)
340 {
341   poplevel (0, 0, 0);
342 }
343
344 /* When a label goes out of scope, check to see if that label was used
345    in a valid manner, and issue any appropriate warnings or errors.  */
346
347 static void
348 pop_label (tree label, tree old_value)
349 {
350   if (!processing_template_decl)
351     {
352       if (DECL_INITIAL (label) == NULL_TREE)
353         {
354           location_t location;
355
356           error ("label %q+D used but not defined", label);
357           location = input_location; /* FIXME want (input_filename, (line)0) */
358           /* Avoid crashing later.  */
359           define_label (location, DECL_NAME (label));
360         }
361       else 
362         warn_for_unused_label (label);
363     }
364
365   SET_IDENTIFIER_LABEL_VALUE (DECL_NAME (label), old_value);
366 }
367
368 /* At the end of a function, all labels declared within the function
369    go out of scope.  BLOCK is the top-level block for the
370    function.  */
371
372 static int
373 pop_labels_1 (void **slot, void *data)
374 {
375   struct named_label_entry *ent = (struct named_label_entry *) *slot;
376   tree block = (tree) data;
377
378   pop_label (ent->label_decl, NULL_TREE);
379
380   /* Put the labels into the "variables" of the top-level block,
381      so debugger can see them.  */
382   TREE_CHAIN (ent->label_decl) = BLOCK_VARS (block);
383   BLOCK_VARS (block) = ent->label_decl;
384
385   htab_clear_slot (named_labels, slot);
386
387   return 1;
388 }
389
390 static void
391 pop_labels (tree block)
392 {
393   if (named_labels)
394     {
395       htab_traverse (named_labels, pop_labels_1, block);
396       named_labels = NULL;
397     }
398 }
399
400 /* At the end of a block with local labels, restore the outer definition.  */
401
402 static void
403 pop_local_label (tree label, tree old_value)
404 {
405   struct named_label_entry dummy;
406   void **slot;
407
408   pop_label (label, old_value);
409
410   dummy.label_decl = label;
411   slot = htab_find_slot (named_labels, &dummy, NO_INSERT);
412   htab_clear_slot (named_labels, slot);
413 }
414
415 /* The following two routines are used to interface to Objective-C++.
416    The binding level is purposely treated as an opaque type.  */
417
418 void *
419 objc_get_current_scope (void)
420 {
421   return current_binding_level;
422 }
423
424 /* The following routine is used by the NeXT-style SJLJ exceptions;
425    variables get marked 'volatile' so as to not be clobbered by
426    _setjmp()/_longjmp() calls.  All variables in the current scope,
427    as well as parent scopes up to (but not including) ENCLOSING_BLK
428    shall be thusly marked.  */
429
430 void
431 objc_mark_locals_volatile (void *enclosing_blk)
432 {
433   struct cp_binding_level *scope;
434
435   for (scope = current_binding_level;
436        scope && scope != enclosing_blk;
437        scope = scope->level_chain)
438     {
439       tree decl;
440
441       for (decl = scope->names; decl; decl = TREE_CHAIN (decl))
442         objc_volatilize_decl (decl);
443
444       /* Do not climb up past the current function.  */
445       if (scope->kind == sk_function_parms)
446         break;
447     }
448 }
449
450 /* Update data for defined and undefined labels when leaving a scope.  */
451
452 static int
453 poplevel_named_label_1 (void **slot, void *data)
454 {
455   struct named_label_entry *ent = (struct named_label_entry *) *slot;
456   struct cp_binding_level *bl = (struct cp_binding_level *) data;
457   struct cp_binding_level *obl = bl->level_chain;
458
459   if (ent->binding_level == bl)
460     {
461       tree decl;
462
463       for (decl = ent->names_in_scope; decl; decl = TREE_CHAIN (decl))
464         if (decl_jump_unsafe (decl))
465           ent->bad_decls = tree_cons (NULL, decl, ent->bad_decls);
466
467       ent->binding_level = obl;
468       ent->names_in_scope = obl->names;
469       switch (bl->kind)
470         {
471         case sk_try:
472           ent->in_try_scope = true;
473           break;
474         case sk_catch:
475           ent->in_catch_scope = true;
476           break;
477         case sk_omp:
478           ent->in_omp_scope = true;
479           break;
480         default:
481           break;
482         }
483     }
484   else if (ent->uses)
485     {
486       struct named_label_use_entry *use;
487
488       for (use = ent->uses; use ; use = use->next)
489         if (use->binding_level == bl)
490           {
491             use->binding_level = obl;
492             use->names_in_scope = obl->names;
493             if (bl->kind == sk_omp)
494               use->in_omp_scope = true;
495           }
496     }
497
498   return 1;
499 }
500
501 /* Exit a binding level.
502    Pop the level off, and restore the state of the identifier-decl mappings
503    that were in effect when this level was entered.
504
505    If KEEP == 1, this level had explicit declarations, so
506    and create a "block" (a BLOCK node) for the level
507    to record its declarations and subblocks for symbol table output.
508
509    If FUNCTIONBODY is nonzero, this level is the body of a function,
510    so create a block as if KEEP were set and also clear out all
511    label names.
512
513    If REVERSE is nonzero, reverse the order of decls before putting
514    them into the BLOCK.  */
515
516 tree
517 poplevel (int keep, int reverse, int functionbody)
518 {
519   tree link;
520   /* The chain of decls was accumulated in reverse order.
521      Put it into forward order, just for cleanliness.  */
522   tree decls;
523   int tmp = functionbody;
524   int real_functionbody;
525   tree subblocks;
526   tree block;
527   tree decl;
528   int leaving_for_scope;
529   scope_kind kind;
530
531   timevar_push (TV_NAME_LOOKUP);
532  restart:
533
534   block = NULL_TREE;
535
536   gcc_assert (current_binding_level->kind != sk_class);
537
538   real_functionbody = (current_binding_level->kind == sk_cleanup
539                        ? ((functionbody = 0), tmp) : functionbody);
540   subblocks = functionbody >= 0 ? current_binding_level->blocks : 0;
541
542   gcc_assert (!VEC_length(cp_class_binding,
543                           current_binding_level->class_shadowed));
544
545   /* We used to use KEEP == 2 to indicate that the new block should go
546      at the beginning of the list of blocks at this binding level,
547      rather than the end.  This hack is no longer used.  */
548   gcc_assert (keep == 0 || keep == 1);
549
550   if (current_binding_level->keep)
551     keep = 1;
552
553   /* Any uses of undefined labels, and any defined labels, now operate
554      under constraints of next binding contour.  */
555   if (cfun && !functionbody && named_labels)
556     htab_traverse (named_labels, poplevel_named_label_1,
557                    current_binding_level);
558
559   /* Get the decls in the order they were written.
560      Usually current_binding_level->names is in reverse order.
561      But parameter decls were previously put in forward order.  */
562
563   if (reverse)
564     current_binding_level->names
565       = decls = nreverse (current_binding_level->names);
566   else
567     decls = current_binding_level->names;
568
569   /* If there were any declarations or structure tags in that level,
570      or if this level is a function body,
571      create a BLOCK to record them for the life of this function.  */
572   block = NULL_TREE;
573   if (keep == 1 || functionbody)
574     block = make_node (BLOCK);
575   if (block != NULL_TREE)
576     {
577       BLOCK_VARS (block) = decls;
578       BLOCK_SUBBLOCKS (block) = subblocks;
579     }
580
581   /* In each subblock, record that this is its superior.  */
582   if (keep >= 0)
583     for (link = subblocks; link; link = BLOCK_CHAIN (link))
584       BLOCK_SUPERCONTEXT (link) = block;
585
586   /* We still support the old for-scope rules, whereby the variables
587      in a for-init statement were in scope after the for-statement
588      ended.  We only use the new rules if flag_new_for_scope is
589      nonzero.  */
590   leaving_for_scope
591     = current_binding_level->kind == sk_for && flag_new_for_scope == 1;
592
593   /* Before we remove the declarations first check for unused variables.  */
594   if (warn_unused_variable
595       && !processing_template_decl)
596     for (decl = getdecls (); decl; decl = TREE_CHAIN (decl))
597       if (TREE_CODE (decl) == VAR_DECL
598           && ! TREE_USED (decl)
599           && ! DECL_IN_SYSTEM_HEADER (decl)
600           && DECL_NAME (decl) && ! DECL_ARTIFICIAL (decl))
601         warning (OPT_Wunused_variable, "unused variable %q+D", decl);
602
603   /* Remove declarations for all the DECLs in this level.  */
604   for (link = decls; link; link = TREE_CHAIN (link))
605     {
606       if (leaving_for_scope && TREE_CODE (link) == VAR_DECL
607           && DECL_NAME (link))
608         {
609           tree name = DECL_NAME (link);
610           cxx_binding *ob;
611           tree ns_binding;
612
613           ob = outer_binding (name,
614                               IDENTIFIER_BINDING (name),
615                               /*class_p=*/true);
616           if (!ob)
617             ns_binding = IDENTIFIER_NAMESPACE_VALUE (name);
618           else
619             ns_binding = NULL_TREE;
620
621           if (ob && ob->scope == current_binding_level->level_chain)
622             /* We have something like:
623
624                  int i;
625                  for (int i; ;);
626
627                and we are leaving the `for' scope.  There's no reason to
628                keep the binding of the inner `i' in this case.  */
629             pop_binding (name, link);
630           else if ((ob && (TREE_CODE (ob->value) == TYPE_DECL))
631                    || (ns_binding && TREE_CODE (ns_binding) == TYPE_DECL))
632             /* Here, we have something like:
633
634                  typedef int I;
635
636                  void f () {
637                    for (int I; ;);
638                  }
639
640                We must pop the for-scope binding so we know what's a
641                type and what isn't.  */
642             pop_binding (name, link);
643           else
644             {
645               /* Mark this VAR_DECL as dead so that we can tell we left it
646                  there only for backward compatibility.  */
647               DECL_DEAD_FOR_LOCAL (link) = 1;
648
649               /* Keep track of what should have happened when we
650                  popped the binding.  */
651               if (ob && ob->value)
652                 {
653                   SET_DECL_SHADOWED_FOR_VAR (link, ob->value);
654                   DECL_HAS_SHADOWED_FOR_VAR_P (link) = 1;
655                 }
656
657               /* Add it to the list of dead variables in the next
658                  outermost binding to that we can remove these when we
659                  leave that binding.  */
660               current_binding_level->level_chain->dead_vars_from_for
661                 = tree_cons (NULL_TREE, link,
662                              current_binding_level->level_chain->
663                              dead_vars_from_for);
664
665               /* Although we don't pop the cxx_binding, we do clear
666                  its SCOPE since the scope is going away now.  */
667               IDENTIFIER_BINDING (name)->scope
668                 = current_binding_level->level_chain;
669             }
670         }
671       else
672         {
673           tree name;
674
675           /* Remove the binding.  */
676           decl = link;
677
678           if (TREE_CODE (decl) == TREE_LIST)
679             decl = TREE_VALUE (decl);
680           name = decl;
681
682           if (TREE_CODE (name) == OVERLOAD)
683             name = OVL_FUNCTION (name);
684
685           gcc_assert (DECL_P (name));
686           pop_binding (DECL_NAME (name), decl);
687         }
688     }
689
690   /* Remove declarations for any `for' variables from inner scopes
691      that we kept around.  */
692   for (link = current_binding_level->dead_vars_from_for;
693        link; link = TREE_CHAIN (link))
694     pop_binding (DECL_NAME (TREE_VALUE (link)), TREE_VALUE (link));
695
696   /* Restore the IDENTIFIER_TYPE_VALUEs.  */
697   for (link = current_binding_level->type_shadowed;
698        link; link = TREE_CHAIN (link))
699     SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (link), TREE_VALUE (link));
700
701   /* Restore the IDENTIFIER_LABEL_VALUEs for local labels.  */
702   for (link = current_binding_level->shadowed_labels;
703        link;
704        link = TREE_CHAIN (link))
705     pop_local_label (TREE_VALUE (link), TREE_PURPOSE (link));
706
707   /* There may be OVERLOADs (wrapped in TREE_LISTs) on the BLOCK_VARs
708      list if a `using' declaration put them there.  The debugging
709      back ends won't understand OVERLOAD, so we remove them here.
710      Because the BLOCK_VARS are (temporarily) shared with
711      CURRENT_BINDING_LEVEL->NAMES we must do this fixup after we have
712      popped all the bindings.  */
713   if (block)
714     {
715       tree* d;
716
717       for (d = &BLOCK_VARS (block); *d; )
718         {
719           if (TREE_CODE (*d) == TREE_LIST)
720             *d = TREE_CHAIN (*d);
721           else
722             d = &TREE_CHAIN (*d);
723         }
724     }
725
726   /* If the level being exited is the top level of a function,
727      check over all the labels.  */
728   if (functionbody)
729     {
730       /* Since this is the top level block of a function, the vars are
731          the function's parameters.  Don't leave them in the BLOCK
732          because they are found in the FUNCTION_DECL instead.  */
733       BLOCK_VARS (block) = 0;
734       pop_labels (block);
735     }
736
737   kind = current_binding_level->kind;
738   if (kind == sk_cleanup)
739     {
740       tree stmt;
741
742       /* If this is a temporary binding created for a cleanup, then we'll
743          have pushed a statement list level.  Pop that, create a new
744          BIND_EXPR for the block, and insert it into the stream.  */
745       stmt = pop_stmt_list (current_binding_level->statement_list);
746       stmt = c_build_bind_expr (input_location, block, stmt);
747       add_stmt (stmt);
748     }
749
750   leave_scope ();
751   if (functionbody)
752     {
753       /* The current function is being defined, so its DECL_INITIAL
754          should be error_mark_node.  */
755       gcc_assert (DECL_INITIAL (current_function_decl) == error_mark_node);
756       DECL_INITIAL (current_function_decl) = block;
757     }
758   else if (block)
759     current_binding_level->blocks
760       = chainon (current_binding_level->blocks, block);
761
762   /* If we did not make a block for the level just exited,
763      any blocks made for inner levels
764      (since they cannot be recorded as subblocks in that level)
765      must be carried forward so they will later become subblocks
766      of something else.  */
767   else if (subblocks)
768     current_binding_level->blocks
769       = chainon (current_binding_level->blocks, subblocks);
770
771   /* Each and every BLOCK node created here in `poplevel' is important
772      (e.g. for proper debugging information) so if we created one
773      earlier, mark it as "used".  */
774   if (block)
775     TREE_USED (block) = 1;
776
777   /* All temporary bindings created for cleanups are popped silently.  */
778   if (kind == sk_cleanup)
779     goto restart;
780
781   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, block);
782 }
783
784 /* Walk all the namespaces contained NAMESPACE, including NAMESPACE
785    itself, calling F for each.  The DATA is passed to F as well.  */
786
787 static int
788 walk_namespaces_r (tree name_space, walk_namespaces_fn f, void* data)
789 {
790   int result = 0;
791   tree current = NAMESPACE_LEVEL (name_space)->namespaces;
792
793   result |= (*f) (name_space, data);
794
795   for (; current; current = TREE_CHAIN (current))
796     result |= walk_namespaces_r (current, f, data);
797
798   return result;
799 }
800
801 /* Walk all the namespaces, calling F for each.  The DATA is passed to
802    F as well.  */
803
804 int
805 walk_namespaces (walk_namespaces_fn f, void* data)
806 {
807   return walk_namespaces_r (global_namespace, f, data);
808 }
809
810 /* Call wrapup_globals_declarations for the globals in NAMESPACE.  If
811    DATA is non-NULL, this is the last time we will call
812    wrapup_global_declarations for this NAMESPACE.  */
813
814 int
815 wrapup_globals_for_namespace (tree name_space, void* data)
816 {
817   struct cp_binding_level *level = NAMESPACE_LEVEL (name_space);
818   VEC(tree,gc) *statics = level->static_decls;
819   tree *vec = VEC_address (tree, statics);
820   int len = VEC_length (tree, statics);
821   int last_time = (data != 0);
822
823   if (last_time)
824     {
825       check_global_declarations (vec, len);
826       emit_debug_global_declarations (vec, len);
827       return 0;
828     }
829
830   /* Write out any globals that need to be output.  */
831   return wrapup_global_declarations (vec, len);
832 }
833
834 \f
835 /* In C++, you don't have to write `struct S' to refer to `S'; you
836    can just use `S'.  We accomplish this by creating a TYPE_DECL as
837    if the user had written `typedef struct S S'.  Create and return
838    the TYPE_DECL for TYPE.  */
839
840 tree
841 create_implicit_typedef (tree name, tree type)
842 {
843   tree decl;
844
845   decl = build_decl (input_location, TYPE_DECL, name, type);
846   DECL_ARTIFICIAL (decl) = 1;
847   /* There are other implicit type declarations, like the one *within*
848      a class that allows you to write `S::S'.  We must distinguish
849      amongst these.  */
850   SET_DECL_IMPLICIT_TYPEDEF_P (decl);
851   TYPE_NAME (type) = decl;
852
853   return decl;
854 }
855
856 /* Remember a local name for name-mangling purposes.  */
857
858 static void
859 push_local_name (tree decl)
860 {
861   size_t i, nelts;
862   tree t, name;
863
864   timevar_push (TV_NAME_LOOKUP);
865
866   name = DECL_NAME (decl);
867
868   nelts = VEC_length (tree, local_names);
869   for (i = 0; i < nelts; i++)
870     {
871       t = VEC_index (tree, local_names, i);
872       if (DECL_NAME (t) == name)
873         {
874           if (!DECL_LANG_SPECIFIC (decl))
875             retrofit_lang_decl (decl);
876           DECL_LANG_SPECIFIC (decl)->u.base.u2sel = 1;
877           if (DECL_LANG_SPECIFIC (t))
878             DECL_DISCRIMINATOR (decl) = DECL_DISCRIMINATOR (t) + 1;
879           else
880             DECL_DISCRIMINATOR (decl) = 1;
881
882           VEC_replace (tree, local_names, i, decl);
883           timevar_pop (TV_NAME_LOOKUP);
884           return;
885         }
886     }
887
888   VEC_safe_push (tree, gc, local_names, decl);
889   timevar_pop (TV_NAME_LOOKUP);
890 }
891 \f
892 /* Subroutine of duplicate_decls: return truthvalue of whether
893    or not types of these decls match.
894
895    For C++, we must compare the parameter list so that `int' can match
896    `int&' in a parameter position, but `int&' is not confused with
897    `const int&'.  */
898
899 int
900 decls_match (tree newdecl, tree olddecl)
901 {
902   int types_match;
903
904   if (newdecl == olddecl)
905     return 1;
906
907   if (TREE_CODE (newdecl) != TREE_CODE (olddecl))
908     /* If the two DECLs are not even the same kind of thing, we're not
909        interested in their types.  */
910     return 0;
911
912   if (TREE_CODE (newdecl) == FUNCTION_DECL)
913     {
914       tree f1 = TREE_TYPE (newdecl);
915       tree f2 = TREE_TYPE (olddecl);
916       tree p1 = TYPE_ARG_TYPES (f1);
917       tree p2 = TYPE_ARG_TYPES (f2);
918
919       /* Specializations of different templates are different functions
920          even if they have the same type.  */
921       tree t1 = (DECL_USE_TEMPLATE (newdecl)
922                  ? DECL_TI_TEMPLATE (newdecl)
923                  : NULL_TREE);
924       tree t2 = (DECL_USE_TEMPLATE (olddecl)
925                  ? DECL_TI_TEMPLATE (olddecl)
926                  : NULL_TREE);
927       if (t1 != t2)
928         return 0;
929
930       if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
931           && ! (DECL_EXTERN_C_P (newdecl)
932                 && DECL_EXTERN_C_P (olddecl)))
933         return 0;
934
935 #ifdef NO_IMPLICIT_EXTERN_C
936       /* A new declaration doesn't match a built-in one unless it
937          is also extern "C".  */
938       if (DECL_BUILT_IN (olddecl)
939           && DECL_EXTERN_C_P (olddecl) && !DECL_EXTERN_C_P (newdecl))
940         return 0;
941 #endif
942
943       if (TREE_CODE (f1) != TREE_CODE (f2))
944         return 0;
945
946       if (same_type_p (TREE_TYPE (f1), TREE_TYPE (f2)))
947         {
948           if (p2 == NULL_TREE && DECL_EXTERN_C_P (olddecl)
949               && (DECL_BUILT_IN (olddecl)
950 #ifndef NO_IMPLICIT_EXTERN_C
951                   || (DECL_IN_SYSTEM_HEADER (newdecl) && !DECL_CLASS_SCOPE_P (newdecl))
952                   || (DECL_IN_SYSTEM_HEADER (olddecl) && !DECL_CLASS_SCOPE_P (olddecl))
953 #endif
954               ))
955             {
956               types_match = self_promoting_args_p (p1);
957               if (p1 == void_list_node)
958                 TREE_TYPE (newdecl) = TREE_TYPE (olddecl);
959             }
960 #ifndef NO_IMPLICIT_EXTERN_C
961           else if (p1 == NULL_TREE
962                    && (DECL_EXTERN_C_P (olddecl)
963                        && DECL_IN_SYSTEM_HEADER (olddecl)
964                        && !DECL_CLASS_SCOPE_P (olddecl))
965                    && (DECL_EXTERN_C_P (newdecl)
966                        && DECL_IN_SYSTEM_HEADER (newdecl)
967                        && !DECL_CLASS_SCOPE_P (newdecl)))
968             {
969               types_match = self_promoting_args_p (p2);
970               TREE_TYPE (newdecl) = TREE_TYPE (olddecl);
971             }
972 #endif
973           else
974             types_match = compparms (p1, p2);
975         }
976       else
977         types_match = 0;
978     }
979   else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
980     {
981       if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl))
982           != TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)))
983         return 0;
984
985       if (!comp_template_parms (DECL_TEMPLATE_PARMS (newdecl),
986                                 DECL_TEMPLATE_PARMS (olddecl)))
987         return 0;
988
989       if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == TYPE_DECL)
990         types_match = same_type_p (TREE_TYPE (DECL_TEMPLATE_RESULT (olddecl)),
991                                    TREE_TYPE (DECL_TEMPLATE_RESULT (newdecl)));
992       else
993         types_match = decls_match (DECL_TEMPLATE_RESULT (olddecl),
994                                    DECL_TEMPLATE_RESULT (newdecl));
995     }
996   else
997     {
998       /* Need to check scope for variable declaration (VAR_DECL).
999          For typedef (TYPE_DECL), scope is ignored.  */
1000       if (TREE_CODE (newdecl) == VAR_DECL
1001           && CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1002           /* [dcl.link]
1003              Two declarations for an object with C language linkage
1004              with the same name (ignoring the namespace that qualify
1005              it) that appear in different namespace scopes refer to
1006              the same object.  */
1007           && !(DECL_EXTERN_C_P (olddecl) && DECL_EXTERN_C_P (newdecl)))
1008         return 0;
1009
1010       if (TREE_TYPE (newdecl) == error_mark_node)
1011         types_match = TREE_TYPE (olddecl) == error_mark_node;
1012       else if (TREE_TYPE (olddecl) == NULL_TREE)
1013         types_match = TREE_TYPE (newdecl) == NULL_TREE;
1014       else if (TREE_TYPE (newdecl) == NULL_TREE)
1015         types_match = 0;
1016       else
1017         types_match = comptypes (TREE_TYPE (newdecl),
1018                                  TREE_TYPE (olddecl),
1019                                  COMPARE_REDECLARATION);
1020     }
1021
1022   return types_match;
1023 }
1024
1025 /* If NEWDECL is `static' and an `extern' was seen previously,
1026    warn about it.  OLDDECL is the previous declaration.
1027
1028    Note that this does not apply to the C++ case of declaring
1029    a variable `extern const' and then later `const'.
1030
1031    Don't complain about built-in functions, since they are beyond
1032    the user's control.  */
1033
1034 void
1035 warn_extern_redeclared_static (tree newdecl, tree olddecl)
1036 {
1037   tree name;
1038
1039   if (TREE_CODE (newdecl) == TYPE_DECL
1040       || TREE_CODE (newdecl) == TEMPLATE_DECL
1041       || TREE_CODE (newdecl) == CONST_DECL
1042       || TREE_CODE (newdecl) == NAMESPACE_DECL)
1043     return;
1044
1045   /* Don't get confused by static member functions; that's a different
1046      use of `static'.  */
1047   if (TREE_CODE (newdecl) == FUNCTION_DECL
1048       && DECL_STATIC_FUNCTION_P (newdecl))
1049     return;
1050
1051   /* If the old declaration was `static', or the new one isn't, then
1052      then everything is OK.  */
1053   if (DECL_THIS_STATIC (olddecl) || !DECL_THIS_STATIC (newdecl))
1054     return;
1055
1056   /* It's OK to declare a builtin function as `static'.  */
1057   if (TREE_CODE (olddecl) == FUNCTION_DECL
1058       && DECL_ARTIFICIAL (olddecl))
1059     return;
1060
1061   name = DECL_ASSEMBLER_NAME (newdecl);
1062   permerror (input_location, "%qD was declared %<extern%> and later %<static%>", newdecl);
1063   permerror (input_location, "previous declaration of %q+D", olddecl);
1064 }
1065
1066 /* NEW_DECL is a redeclaration of OLD_DECL; both are functions or
1067    function templates.  If their exception specifications do not
1068    match, issue a diagnostic.  */
1069
1070 static void
1071 check_redeclaration_exception_specification (tree new_decl,
1072                                              tree old_decl)
1073 {
1074   tree new_type;
1075   tree old_type;
1076   tree new_exceptions;
1077   tree old_exceptions;
1078
1079   new_type = TREE_TYPE (new_decl);
1080   new_exceptions = TYPE_RAISES_EXCEPTIONS (new_type);
1081   old_type = TREE_TYPE (old_decl);
1082   old_exceptions = TYPE_RAISES_EXCEPTIONS (old_type);
1083
1084   /* [except.spec]
1085
1086      If any declaration of a function has an exception-specification,
1087      all declarations, including the definition and an explicit
1088      specialization, of that function shall have an
1089      exception-specification with the same set of type-ids.  */
1090   if ((pedantic || ! DECL_IN_SYSTEM_HEADER (old_decl))
1091       && ! DECL_IS_BUILTIN (old_decl)
1092       && flag_exceptions
1093       && !comp_except_specs (new_exceptions, old_exceptions,
1094                              /*exact=*/true))
1095     {
1096       error ("declaration of %qF throws different exceptions", new_decl);
1097       error ("from previous declaration %q+F", old_decl);
1098     }
1099 }
1100
1101 #define GNU_INLINE_P(fn) (DECL_DECLARED_INLINE_P (fn)                   \
1102                           && lookup_attribute ("gnu_inline",            \
1103                                                DECL_ATTRIBUTES (fn)))
1104
1105 /* If NEWDECL is a redeclaration of OLDDECL, merge the declarations.
1106    If the redeclaration is invalid, a diagnostic is issued, and the
1107    error_mark_node is returned.  Otherwise, OLDDECL is returned.
1108
1109    If NEWDECL is not a redeclaration of OLDDECL, NULL_TREE is
1110    returned.
1111
1112    NEWDECL_IS_FRIEND is true if NEWDECL was declared as a friend.  */
1113
1114 tree
1115 duplicate_decls (tree newdecl, tree olddecl, bool newdecl_is_friend)
1116 {
1117   unsigned olddecl_uid = DECL_UID (olddecl);
1118   int olddecl_friend = 0, types_match = 0, hidden_friend = 0;
1119   int new_defines_function = 0;
1120   tree new_template_info;
1121
1122   if (newdecl == olddecl)
1123     return olddecl;
1124
1125   types_match = decls_match (newdecl, olddecl);
1126
1127   /* If either the type of the new decl or the type of the old decl is an
1128      error_mark_node, then that implies that we have already issued an
1129      error (earlier) for some bogus type specification, and in that case,
1130      it is rather pointless to harass the user with yet more error message
1131      about the same declaration, so just pretend the types match here.  */
1132   if (TREE_TYPE (newdecl) == error_mark_node
1133       || TREE_TYPE (olddecl) == error_mark_node)
1134     return error_mark_node;
1135
1136   if (DECL_P (olddecl)
1137       && TREE_CODE (newdecl) == FUNCTION_DECL
1138       && TREE_CODE (olddecl) == FUNCTION_DECL
1139       && (DECL_UNINLINABLE (newdecl) || DECL_UNINLINABLE (olddecl)))
1140     {
1141       if (DECL_DECLARED_INLINE_P (newdecl)
1142           && DECL_UNINLINABLE (newdecl)
1143           && lookup_attribute ("noinline", DECL_ATTRIBUTES (newdecl)))
1144         /* Already warned elsewhere.  */;
1145       else if (DECL_DECLARED_INLINE_P (olddecl)
1146                && DECL_UNINLINABLE (olddecl)
1147                && lookup_attribute ("noinline", DECL_ATTRIBUTES (olddecl)))
1148         /* Already warned.  */;
1149       else if (DECL_DECLARED_INLINE_P (newdecl)
1150                && DECL_UNINLINABLE (olddecl)
1151                && lookup_attribute ("noinline", DECL_ATTRIBUTES (olddecl)))
1152         {
1153           warning (OPT_Wattributes, "function %q+D redeclared as inline",
1154                    newdecl);
1155           warning (OPT_Wattributes, "previous declaration of %q+D "
1156                    "with attribute noinline", olddecl);
1157         }
1158       else if (DECL_DECLARED_INLINE_P (olddecl)
1159                && DECL_UNINLINABLE (newdecl)
1160                && lookup_attribute ("noinline", DECL_ATTRIBUTES (newdecl)))
1161         {
1162           warning (OPT_Wattributes, "function %q+D redeclared with "
1163                    "attribute noinline", newdecl);
1164           warning (OPT_Wattributes, "previous declaration of %q+D was inline",
1165                    olddecl);
1166         }
1167     }
1168
1169   /* Check for redeclaration and other discrepancies.  */
1170   if (TREE_CODE (olddecl) == FUNCTION_DECL
1171       && DECL_ARTIFICIAL (olddecl))
1172     {
1173       gcc_assert (!DECL_HIDDEN_FRIEND_P (olddecl));
1174       if (TREE_CODE (newdecl) != FUNCTION_DECL)
1175         {
1176           /* Avoid warnings redeclaring built-ins which have not been
1177              explicitly declared.  */
1178           if (DECL_ANTICIPATED (olddecl))
1179             return NULL_TREE;
1180
1181           /* If you declare a built-in or predefined function name as static,
1182              the old definition is overridden, but optionally warn this was a
1183              bad choice of name.  */
1184           if (! TREE_PUBLIC (newdecl))
1185             {
1186               warning (OPT_Wshadow, "shadowing %s function %q#D",
1187                        DECL_BUILT_IN (olddecl) ? "built-in" : "library",
1188                        olddecl);
1189               /* Discard the old built-in function.  */
1190               return NULL_TREE;
1191             }
1192           /* If the built-in is not ansi, then programs can override
1193              it even globally without an error.  */
1194           else if (! DECL_BUILT_IN (olddecl))
1195             warning (0, "library function %q#D redeclared as non-function %q#D",
1196                      olddecl, newdecl);
1197           else
1198             {
1199               error ("declaration of %q#D", newdecl);
1200               error ("conflicts with built-in declaration %q#D",
1201                      olddecl);
1202             }
1203           return NULL_TREE;
1204         }
1205       else if (!types_match)
1206         {
1207           /* Avoid warnings redeclaring built-ins which have not been
1208              explicitly declared.  */
1209           if (DECL_ANTICIPATED (olddecl))
1210             {
1211               /* Deal with fileptr_type_node.  FILE type is not known
1212                  at the time we create the builtins.  */
1213               tree t1, t2;
1214
1215               for (t1 = TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1216                    t2 = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1217                    t1 || t2;
1218                    t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1219                 if (!t1 || !t2)
1220                   break;
1221                 else if (TREE_VALUE (t2) == fileptr_type_node)
1222                   {
1223                     tree t = TREE_VALUE (t1);
1224
1225                     if (TREE_CODE (t) == POINTER_TYPE
1226                         && TYPE_NAME (TREE_TYPE (t))
1227                         && DECL_NAME (TYPE_NAME (TREE_TYPE (t)))
1228                            == get_identifier ("FILE")
1229                         && compparms (TREE_CHAIN (t1), TREE_CHAIN (t2)))
1230                       {
1231                         tree oldargs = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1232
1233                         TYPE_ARG_TYPES (TREE_TYPE (olddecl))
1234                           = TYPE_ARG_TYPES (TREE_TYPE (newdecl));
1235                         types_match = decls_match (newdecl, olddecl);
1236                         if (types_match)
1237                           return duplicate_decls (newdecl, olddecl,
1238                                                   newdecl_is_friend);
1239                         TYPE_ARG_TYPES (TREE_TYPE (olddecl)) = oldargs;
1240                       }
1241                   }
1242                 else if (! same_type_p (TREE_VALUE (t1), TREE_VALUE (t2)))
1243                   break;
1244             }
1245           else if ((DECL_EXTERN_C_P (newdecl)
1246                     && DECL_EXTERN_C_P (olddecl))
1247                    || compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1248                                  TYPE_ARG_TYPES (TREE_TYPE (olddecl))))
1249             {
1250               /* A near match; override the builtin.  */
1251
1252               if (TREE_PUBLIC (newdecl))
1253                 {
1254                   warning (0, "new declaration %q#D", newdecl);
1255                   warning (0, "ambiguates built-in declaration %q#D",
1256                            olddecl);
1257                 }
1258               else
1259                 warning (OPT_Wshadow, "shadowing %s function %q#D",
1260                          DECL_BUILT_IN (olddecl) ? "built-in" : "library",
1261                          olddecl);
1262             }
1263           else
1264             /* Discard the old built-in function.  */
1265             return NULL_TREE;
1266
1267           /* Replace the old RTL to avoid problems with inlining.  */
1268           COPY_DECL_RTL (newdecl, olddecl);
1269         }
1270       /* Even if the types match, prefer the new declarations type for
1271          built-ins which have not been explicitly declared, for
1272          exception lists, etc...  */
1273       else if (DECL_ANTICIPATED (olddecl))
1274         {
1275           tree type = TREE_TYPE (newdecl);
1276           tree attribs = (*targetm.merge_type_attributes)
1277             (TREE_TYPE (olddecl), type);
1278
1279           type = cp_build_type_attribute_variant (type, attribs);
1280           TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = type;
1281         }
1282
1283       /* If a function is explicitly declared "throw ()", propagate that to
1284          the corresponding builtin.  */
1285       if (DECL_BUILT_IN_CLASS (olddecl) == BUILT_IN_NORMAL
1286           && DECL_ANTICIPATED (olddecl)
1287           && TREE_NOTHROW (newdecl)
1288           && !TREE_NOTHROW (olddecl)
1289           && built_in_decls [DECL_FUNCTION_CODE (olddecl)] != NULL_TREE
1290           && built_in_decls [DECL_FUNCTION_CODE (olddecl)] != olddecl
1291           && types_match)
1292         TREE_NOTHROW (built_in_decls [DECL_FUNCTION_CODE (olddecl)]) = 1;
1293
1294       /* Whether or not the builtin can throw exceptions has no
1295          bearing on this declarator.  */
1296       TREE_NOTHROW (olddecl) = 0;
1297
1298       if (DECL_THIS_STATIC (newdecl) && !DECL_THIS_STATIC (olddecl))
1299         {
1300           /* If a builtin function is redeclared as `static', merge
1301              the declarations, but make the original one static.  */
1302           DECL_THIS_STATIC (olddecl) = 1;
1303           TREE_PUBLIC (olddecl) = 0;
1304
1305           /* Make the old declaration consistent with the new one so
1306              that all remnants of the builtin-ness of this function
1307              will be banished.  */
1308           SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
1309           COPY_DECL_RTL (newdecl, olddecl);
1310         }
1311     }
1312   else if (TREE_CODE (olddecl) != TREE_CODE (newdecl))
1313     {
1314       /* C++ Standard, 3.3, clause 4:
1315          "[Note: a namespace name or a class template name must be unique
1316          in its declarative region (7.3.2, clause 14). ]"  */
1317       if (TREE_CODE (olddecl) != NAMESPACE_DECL
1318           && TREE_CODE (newdecl) != NAMESPACE_DECL
1319           && (TREE_CODE (olddecl) != TEMPLATE_DECL
1320               || TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)) != TYPE_DECL)
1321           && (TREE_CODE (newdecl) != TEMPLATE_DECL
1322               || TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) != TYPE_DECL))
1323         {
1324           if ((TREE_CODE (olddecl) == TYPE_DECL && DECL_ARTIFICIAL (olddecl)
1325                && TREE_CODE (newdecl) != TYPE_DECL)
1326               || (TREE_CODE (newdecl) == TYPE_DECL && DECL_ARTIFICIAL (newdecl)
1327                   && TREE_CODE (olddecl) != TYPE_DECL))
1328             {
1329               /* We do nothing special here, because C++ does such nasty
1330                  things with TYPE_DECLs.  Instead, just let the TYPE_DECL
1331                  get shadowed, and know that if we need to find a TYPE_DECL
1332                  for a given name, we can look in the IDENTIFIER_TYPE_VALUE
1333                  slot of the identifier.  */
1334               return NULL_TREE;
1335             }
1336             
1337             if ((TREE_CODE (newdecl) == FUNCTION_DECL
1338                  && DECL_FUNCTION_TEMPLATE_P (olddecl))
1339                 || (TREE_CODE (olddecl) == FUNCTION_DECL
1340                     && DECL_FUNCTION_TEMPLATE_P (newdecl)))
1341               return NULL_TREE;
1342         }
1343
1344       error ("%q#D redeclared as different kind of symbol", newdecl);
1345       if (TREE_CODE (olddecl) == TREE_LIST)
1346         olddecl = TREE_VALUE (olddecl);
1347       error ("previous declaration of %q+#D", olddecl);
1348
1349       return error_mark_node;
1350     }
1351   else if (!types_match)
1352     {
1353       if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl))
1354         /* These are certainly not duplicate declarations; they're
1355            from different scopes.  */
1356         return NULL_TREE;
1357
1358       if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1359         {
1360           /* The name of a class template may not be declared to refer to
1361              any other template, class, function, object, namespace, value,
1362              or type in the same scope.  */
1363           if (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)) == TYPE_DECL
1364               || TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == TYPE_DECL)
1365             {
1366               error ("declaration of template %q#D", newdecl);
1367               error ("conflicts with previous declaration %q+#D", olddecl);
1368             }
1369           else if (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)) == FUNCTION_DECL
1370                    && TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == FUNCTION_DECL
1371                    && compparms (TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (olddecl))),
1372                                  TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (newdecl))))
1373                    && comp_template_parms (DECL_TEMPLATE_PARMS (newdecl),
1374                                            DECL_TEMPLATE_PARMS (olddecl))
1375                    /* Template functions can be disambiguated by
1376                       return type.  */
1377                    && same_type_p (TREE_TYPE (TREE_TYPE (newdecl)),
1378                                    TREE_TYPE (TREE_TYPE (olddecl))))
1379             {
1380               error ("new declaration %q#D", newdecl);
1381               error ("ambiguates old declaration %q+#D", olddecl);
1382             }
1383           return NULL_TREE;
1384         }
1385       if (TREE_CODE (newdecl) == FUNCTION_DECL)
1386         {
1387           if (DECL_EXTERN_C_P (newdecl) && DECL_EXTERN_C_P (olddecl))
1388             {
1389               error ("declaration of C function %q#D conflicts with",
1390                      newdecl);
1391               error ("previous declaration %q+#D here", olddecl);
1392             }
1393           else if (compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1394                               TYPE_ARG_TYPES (TREE_TYPE (olddecl))))
1395             {
1396               error ("new declaration %q#D", newdecl);
1397               error ("ambiguates old declaration %q+#D", olddecl);
1398               return error_mark_node;
1399             }
1400           else
1401             return NULL_TREE;
1402         }
1403       else
1404         {
1405           error ("conflicting declaration %q#D", newdecl);
1406           error ("%q+D has a previous declaration as %q#D", olddecl, olddecl);
1407           return error_mark_node;
1408         }
1409     }
1410   else if (TREE_CODE (newdecl) == FUNCTION_DECL
1411             && ((DECL_TEMPLATE_SPECIALIZATION (olddecl)
1412                  && (!DECL_TEMPLATE_INFO (newdecl)
1413                      || (DECL_TI_TEMPLATE (newdecl)
1414                          != DECL_TI_TEMPLATE (olddecl))))
1415                 || (DECL_TEMPLATE_SPECIALIZATION (newdecl)
1416                     && (!DECL_TEMPLATE_INFO (olddecl)
1417                         || (DECL_TI_TEMPLATE (olddecl)
1418                             != DECL_TI_TEMPLATE (newdecl))))))
1419     /* It's OK to have a template specialization and a non-template
1420        with the same type, or to have specializations of two
1421        different templates with the same type.  Note that if one is a
1422        specialization, and the other is an instantiation of the same
1423        template, that we do not exit at this point.  That situation
1424        can occur if we instantiate a template class, and then
1425        specialize one of its methods.  This situation is valid, but
1426        the declarations must be merged in the usual way.  */
1427     return NULL_TREE;
1428   else if (TREE_CODE (newdecl) == FUNCTION_DECL
1429            && ((DECL_TEMPLATE_INSTANTIATION (olddecl)
1430                 && !DECL_USE_TEMPLATE (newdecl))
1431                || (DECL_TEMPLATE_INSTANTIATION (newdecl)
1432                    && !DECL_USE_TEMPLATE (olddecl))))
1433     /* One of the declarations is a template instantiation, and the
1434        other is not a template at all.  That's OK.  */
1435     return NULL_TREE;
1436   else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
1437     {
1438       /* In [namespace.alias] we have:
1439
1440            In a declarative region, a namespace-alias-definition can be
1441            used to redefine a namespace-alias declared in that declarative
1442            region to refer only to the namespace to which it already
1443            refers.
1444
1445          Therefore, if we encounter a second alias directive for the same
1446          alias, we can just ignore the second directive.  */
1447       if (DECL_NAMESPACE_ALIAS (newdecl)
1448           && (DECL_NAMESPACE_ALIAS (newdecl)
1449               == DECL_NAMESPACE_ALIAS (olddecl)))
1450         return olddecl;
1451       /* [namespace.alias]
1452
1453          A namespace-name or namespace-alias shall not be declared as
1454          the name of any other entity in the same declarative region.
1455          A namespace-name defined at global scope shall not be
1456          declared as the name of any other entity in any global scope
1457          of the program.  */
1458       error ("declaration of namespace %qD conflicts with", newdecl);
1459       error ("previous declaration of namespace %q+D here", olddecl);
1460       return error_mark_node;
1461     }
1462   else
1463     {
1464       const char *errmsg = redeclaration_error_message (newdecl, olddecl);
1465       if (errmsg)
1466         {
1467           error_at (DECL_SOURCE_LOCATION (newdecl), errmsg, newdecl);
1468           if (DECL_NAME (olddecl) != NULL_TREE)
1469             error ((DECL_INITIAL (olddecl) && namespace_bindings_p ())
1470                          ? "%q+#D previously defined here"
1471                          : "%q+#D previously declared here", olddecl);
1472           return error_mark_node;
1473         }
1474       else if (TREE_CODE (olddecl) == FUNCTION_DECL
1475                && DECL_INITIAL (olddecl) != NULL_TREE
1476                && TYPE_ARG_TYPES (TREE_TYPE (olddecl)) == NULL_TREE
1477                && TYPE_ARG_TYPES (TREE_TYPE (newdecl)) != NULL_TREE)
1478         {
1479           /* Prototype decl follows defn w/o prototype.  */
1480           warning_at (input_location, 0, "prototype for %q+#D", newdecl);
1481           warning_at (DECL_SOURCE_LOCATION (olddecl), 0,
1482                       "follows non-prototype definition here");
1483         }
1484       else if ((TREE_CODE (olddecl) == FUNCTION_DECL
1485                 || TREE_CODE (olddecl) == VAR_DECL)
1486                && DECL_LANGUAGE (newdecl) != DECL_LANGUAGE (olddecl))
1487         {
1488           /* [dcl.link]
1489              If two declarations of the same function or object
1490              specify different linkage-specifications ..., the program
1491              is ill-formed.... Except for functions with C++ linkage,
1492              a function declaration without a linkage specification
1493              shall not precede the first linkage specification for
1494              that function.  A function can be declared without a
1495              linkage specification after an explicit linkage
1496              specification has been seen; the linkage explicitly
1497              specified in the earlier declaration is not affected by
1498              such a function declaration.
1499
1500              DR 563 raises the question why the restrictions on
1501              functions should not also apply to objects.  Older
1502              versions of G++ silently ignore the linkage-specification
1503              for this example:
1504
1505                namespace N { 
1506                  extern int i;
1507                  extern "C" int i;
1508                }
1509
1510              which is clearly wrong.  Therefore, we now treat objects
1511              like functions.  */
1512           if (current_lang_depth () == 0)
1513             {
1514               /* There is no explicit linkage-specification, so we use
1515                  the linkage from the previous declaration.  */
1516               if (!DECL_LANG_SPECIFIC (newdecl))
1517                 retrofit_lang_decl (newdecl);
1518               SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
1519             }
1520           else
1521             {
1522               error ("previous declaration of %q+#D with %qL linkage",
1523                      olddecl, DECL_LANGUAGE (olddecl));
1524               error ("conflicts with new declaration with %qL linkage",
1525                      DECL_LANGUAGE (newdecl));
1526             }
1527         }
1528
1529       if (DECL_LANG_SPECIFIC (olddecl) && DECL_USE_TEMPLATE (olddecl))
1530         ;
1531       else if (TREE_CODE (olddecl) == FUNCTION_DECL)
1532         {
1533           tree t1 = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1534           tree t2 = TYPE_ARG_TYPES (TREE_TYPE (newdecl));
1535           int i = 1;
1536
1537           if (TREE_CODE (TREE_TYPE (newdecl)) == METHOD_TYPE)
1538             t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2);
1539
1540           for (; t1 && t1 != void_list_node;
1541                t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2), i++)
1542             if (TREE_PURPOSE (t1) && TREE_PURPOSE (t2))
1543               {
1544                 if (1 == simple_cst_equal (TREE_PURPOSE (t1),
1545                                            TREE_PURPOSE (t2)))
1546                   {
1547                     permerror (input_location, "default argument given for parameter %d of %q#D",
1548                                i, newdecl);
1549                     permerror (input_location, "after previous specification in %q+#D", olddecl);
1550                   }
1551                 else
1552                   {
1553                     error ("default argument given for parameter %d of %q#D",
1554                            i, newdecl);
1555                     error ("after previous specification in %q+#D",
1556                                  olddecl);
1557                   }
1558               }
1559         }
1560     }
1561
1562   /* Do not merge an implicit typedef with an explicit one.  In:
1563
1564        class A;
1565        ...
1566        typedef class A A __attribute__ ((foo));
1567
1568      the attribute should apply only to the typedef.  */
1569   if (TREE_CODE (olddecl) == TYPE_DECL
1570       && (DECL_IMPLICIT_TYPEDEF_P (olddecl)
1571           || DECL_IMPLICIT_TYPEDEF_P (newdecl)))
1572     return NULL_TREE;
1573
1574   /* If new decl is `static' and an `extern' was seen previously,
1575      warn about it.  */
1576   warn_extern_redeclared_static (newdecl, olddecl);
1577
1578   /* We have committed to returning 1 at this point.  */
1579   if (TREE_CODE (newdecl) == FUNCTION_DECL)
1580     {
1581       /* Now that functions must hold information normally held
1582          by field decls, there is extra work to do so that
1583          declaration information does not get destroyed during
1584          definition.  */
1585       if (DECL_VINDEX (olddecl))
1586         DECL_VINDEX (newdecl) = DECL_VINDEX (olddecl);
1587       if (DECL_CONTEXT (olddecl))
1588         DECL_CONTEXT (newdecl) = DECL_CONTEXT (olddecl);
1589       DECL_STATIC_CONSTRUCTOR (newdecl) |= DECL_STATIC_CONSTRUCTOR (olddecl);
1590       DECL_STATIC_DESTRUCTOR (newdecl) |= DECL_STATIC_DESTRUCTOR (olddecl);
1591       DECL_PURE_VIRTUAL_P (newdecl) |= DECL_PURE_VIRTUAL_P (olddecl);
1592       DECL_VIRTUAL_P (newdecl) |= DECL_VIRTUAL_P (olddecl);
1593       DECL_INVALID_OVERRIDER_P (newdecl) |= DECL_INVALID_OVERRIDER_P (olddecl);
1594       DECL_THIS_STATIC (newdecl) |= DECL_THIS_STATIC (olddecl);
1595       if (DECL_OVERLOADED_OPERATOR_P (olddecl) != ERROR_MARK)
1596         SET_OVERLOADED_OPERATOR_CODE
1597           (newdecl, DECL_OVERLOADED_OPERATOR_P (olddecl));
1598       new_defines_function = DECL_INITIAL (newdecl) != NULL_TREE;
1599
1600       /* Optionally warn about more than one declaration for the same
1601          name, but don't warn about a function declaration followed by a
1602          definition.  */
1603       if (warn_redundant_decls && ! DECL_ARTIFICIAL (olddecl)
1604           && !(new_defines_function && DECL_INITIAL (olddecl) == NULL_TREE)
1605           /* Don't warn about extern decl followed by definition.  */
1606           && !(DECL_EXTERNAL (olddecl) && ! DECL_EXTERNAL (newdecl))
1607           /* Don't warn about friends, let add_friend take care of it.  */
1608           && ! (newdecl_is_friend || DECL_FRIEND_P (olddecl)))
1609         {
1610           warning (OPT_Wredundant_decls, "redundant redeclaration of %qD in same scope", newdecl);
1611           warning (OPT_Wredundant_decls, "previous declaration of %q+D", olddecl);
1612         }
1613
1614       if (DECL_DELETED_FN (newdecl))
1615         {
1616           error ("deleted definition of %qD", newdecl);
1617           error ("after previous declaration %q+D", olddecl);
1618         }
1619     }
1620
1621   /* Deal with C++: must preserve virtual function table size.  */
1622   if (TREE_CODE (olddecl) == TYPE_DECL)
1623     {
1624       tree newtype = TREE_TYPE (newdecl);
1625       tree oldtype = TREE_TYPE (olddecl);
1626
1627       if (newtype != error_mark_node && oldtype != error_mark_node
1628           && TYPE_LANG_SPECIFIC (newtype) && TYPE_LANG_SPECIFIC (oldtype))
1629         CLASSTYPE_FRIEND_CLASSES (newtype)
1630           = CLASSTYPE_FRIEND_CLASSES (oldtype);
1631
1632       DECL_ORIGINAL_TYPE (newdecl) = DECL_ORIGINAL_TYPE (olddecl);
1633     }
1634
1635   /* Copy all the DECL_... slots specified in the new decl
1636      except for any that we copy here from the old type.  */
1637   DECL_ATTRIBUTES (newdecl)
1638     = (*targetm.merge_decl_attributes) (olddecl, newdecl);
1639
1640   if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1641     {
1642       tree old_result;
1643       tree new_result;
1644       old_result = DECL_TEMPLATE_RESULT (olddecl);
1645       new_result = DECL_TEMPLATE_RESULT (newdecl);
1646       TREE_TYPE (olddecl) = TREE_TYPE (old_result);
1647       DECL_TEMPLATE_SPECIALIZATIONS (olddecl)
1648         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (olddecl),
1649                    DECL_TEMPLATE_SPECIALIZATIONS (newdecl));
1650
1651       DECL_ATTRIBUTES (old_result)
1652         = (*targetm.merge_decl_attributes) (old_result, new_result);
1653
1654       if (DECL_FUNCTION_TEMPLATE_P (newdecl))
1655         {
1656           if (GNU_INLINE_P (old_result) != GNU_INLINE_P (new_result)
1657               && DECL_INITIAL (new_result))
1658             {
1659               if (DECL_INITIAL (old_result))
1660                 DECL_UNINLINABLE (old_result) = 1;
1661               else
1662                 DECL_UNINLINABLE (old_result) = DECL_UNINLINABLE (new_result);
1663               DECL_EXTERNAL (old_result) = DECL_EXTERNAL (new_result);
1664               DECL_NOT_REALLY_EXTERN (old_result)
1665                 = DECL_NOT_REALLY_EXTERN (new_result);
1666               DECL_INTERFACE_KNOWN (old_result)
1667                 = DECL_INTERFACE_KNOWN (new_result);
1668               DECL_DECLARED_INLINE_P (old_result)
1669                 = DECL_DECLARED_INLINE_P (new_result);
1670               DECL_DISREGARD_INLINE_LIMITS (old_result)
1671                 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
1672
1673             }
1674           else
1675             {
1676               DECL_DECLARED_INLINE_P (old_result)
1677                 |= DECL_DECLARED_INLINE_P (new_result);
1678               DECL_DISREGARD_INLINE_LIMITS (old_result)
1679                 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
1680               check_redeclaration_exception_specification (newdecl, olddecl);
1681             }
1682         }
1683
1684       /* If the new declaration is a definition, update the file and
1685          line information on the declaration, and also make
1686          the old declaration the same definition.  */
1687       if (DECL_INITIAL (new_result) != NULL_TREE)
1688         {
1689           DECL_SOURCE_LOCATION (olddecl)
1690             = DECL_SOURCE_LOCATION (old_result)
1691             = DECL_SOURCE_LOCATION (newdecl);
1692           DECL_INITIAL (old_result) = DECL_INITIAL (new_result);
1693           if (DECL_FUNCTION_TEMPLATE_P (newdecl))
1694             {
1695               tree parm;
1696               DECL_ARGUMENTS (old_result)
1697                 = DECL_ARGUMENTS (new_result);
1698               for (parm = DECL_ARGUMENTS (old_result); parm;
1699                    parm = TREE_CHAIN (parm))
1700                 DECL_CONTEXT (parm) = old_result;
1701             }
1702         }
1703
1704       return olddecl;
1705     }
1706
1707   if (types_match)
1708     {
1709       /* Automatically handles default parameters.  */
1710       tree oldtype = TREE_TYPE (olddecl);
1711       tree newtype;
1712
1713       /* Merge the data types specified in the two decls.  */
1714       newtype = merge_types (TREE_TYPE (newdecl), TREE_TYPE (olddecl));
1715
1716       /* If merge_types produces a non-typedef type, just use the old type.  */
1717       if (TREE_CODE (newdecl) == TYPE_DECL
1718           && newtype == DECL_ORIGINAL_TYPE (newdecl))
1719         newtype = oldtype;
1720
1721       if (TREE_CODE (newdecl) == VAR_DECL)
1722         {
1723           DECL_THIS_EXTERN (newdecl) |= DECL_THIS_EXTERN (olddecl);
1724           DECL_INITIALIZED_P (newdecl) |= DECL_INITIALIZED_P (olddecl);
1725           DECL_NONTRIVIALLY_INITIALIZED_P (newdecl)
1726             |= DECL_NONTRIVIALLY_INITIALIZED_P (olddecl);
1727           DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (newdecl)
1728             |= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (olddecl);
1729
1730           /* Merge the threadprivate attribute from OLDDECL into NEWDECL.  */
1731           if (DECL_LANG_SPECIFIC (olddecl)
1732               && CP_DECL_THREADPRIVATE_P (olddecl))
1733             {
1734               /* Allocate a LANG_SPECIFIC structure for NEWDECL, if needed.  */
1735               if (!DECL_LANG_SPECIFIC (newdecl))
1736                 retrofit_lang_decl (newdecl);
1737
1738               DECL_TLS_MODEL (newdecl) = DECL_TLS_MODEL (olddecl);
1739               CP_DECL_THREADPRIVATE_P (newdecl) = 1;
1740             }
1741         }
1742
1743       /* Do this after calling `merge_types' so that default
1744          parameters don't confuse us.  */
1745       else if (TREE_CODE (newdecl) == FUNCTION_DECL)
1746         check_redeclaration_exception_specification (newdecl, olddecl);
1747       TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = newtype;
1748
1749       if (TREE_CODE (newdecl) == FUNCTION_DECL)
1750         check_default_args (newdecl);
1751
1752       /* Lay the type out, unless already done.  */
1753       if (! same_type_p (newtype, oldtype)
1754           && TREE_TYPE (newdecl) != error_mark_node
1755           && !(processing_template_decl && uses_template_parms (newdecl)))
1756         layout_type (TREE_TYPE (newdecl));
1757
1758       if ((TREE_CODE (newdecl) == VAR_DECL
1759            || TREE_CODE (newdecl) == PARM_DECL
1760            || TREE_CODE (newdecl) == RESULT_DECL
1761            || TREE_CODE (newdecl) == FIELD_DECL
1762            || TREE_CODE (newdecl) == TYPE_DECL)
1763           && !(processing_template_decl && uses_template_parms (newdecl)))
1764         layout_decl (newdecl, 0);
1765
1766       /* Merge the type qualifiers.  */
1767       if (TREE_READONLY (newdecl))
1768         TREE_READONLY (olddecl) = 1;
1769       if (TREE_THIS_VOLATILE (newdecl))
1770         TREE_THIS_VOLATILE (olddecl) = 1;
1771       if (TREE_NOTHROW (newdecl))
1772         TREE_NOTHROW (olddecl) = 1;
1773
1774       /* Merge deprecatedness.  */
1775       if (TREE_DEPRECATED (newdecl))
1776         TREE_DEPRECATED (olddecl) = 1;
1777
1778       /* Preserve function specific target and optimization options */
1779       if (TREE_CODE (newdecl) == FUNCTION_DECL)
1780         {
1781           if (DECL_FUNCTION_SPECIFIC_TARGET (olddecl)
1782               && !DECL_FUNCTION_SPECIFIC_TARGET (newdecl))
1783             DECL_FUNCTION_SPECIFIC_TARGET (newdecl)
1784               = DECL_FUNCTION_SPECIFIC_TARGET (olddecl);
1785
1786           if (DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl)
1787               && !DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl))
1788             DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl)
1789               = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl);
1790         }
1791
1792       /* Merge the initialization information.  */
1793       if (DECL_INITIAL (newdecl) == NULL_TREE
1794           && DECL_INITIAL (olddecl) != NULL_TREE)
1795         {
1796           DECL_INITIAL (newdecl) = DECL_INITIAL (olddecl);
1797           DECL_SOURCE_LOCATION (newdecl) = DECL_SOURCE_LOCATION (olddecl);
1798           if (TREE_CODE (newdecl) == FUNCTION_DECL)
1799             {
1800               DECL_SAVED_TREE (newdecl) = DECL_SAVED_TREE (olddecl);
1801               DECL_STRUCT_FUNCTION (newdecl) = DECL_STRUCT_FUNCTION (olddecl);
1802             }
1803         }
1804
1805       /* Merge the section attribute.
1806          We want to issue an error if the sections conflict but that must be
1807          done later in decl_attributes since we are called before attributes
1808          are assigned.  */
1809       if (DECL_SECTION_NAME (newdecl) == NULL_TREE)
1810         DECL_SECTION_NAME (newdecl) = DECL_SECTION_NAME (olddecl);
1811
1812       if (TREE_CODE (newdecl) == FUNCTION_DECL)
1813         {
1814           DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (newdecl)
1815             |= DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (olddecl);
1816           DECL_NO_LIMIT_STACK (newdecl) |= DECL_NO_LIMIT_STACK (olddecl);
1817           TREE_THIS_VOLATILE (newdecl) |= TREE_THIS_VOLATILE (olddecl);
1818           TREE_NOTHROW (newdecl) |= TREE_NOTHROW (olddecl);
1819           DECL_IS_MALLOC (newdecl) |= DECL_IS_MALLOC (olddecl);
1820           DECL_IS_OPERATOR_NEW (newdecl) |= DECL_IS_OPERATOR_NEW (olddecl);
1821           DECL_PURE_P (newdecl) |= DECL_PURE_P (olddecl);
1822           TREE_READONLY (newdecl) |= TREE_READONLY (olddecl);
1823           DECL_LOOPING_CONST_OR_PURE_P (newdecl) 
1824             |= DECL_LOOPING_CONST_OR_PURE_P (olddecl);
1825           /* Keep the old RTL.  */
1826           COPY_DECL_RTL (olddecl, newdecl);
1827         }
1828       else if (TREE_CODE (newdecl) == VAR_DECL
1829                && (DECL_SIZE (olddecl) || !DECL_SIZE (newdecl)))
1830         {
1831           /* Keep the old RTL.  We cannot keep the old RTL if the old
1832              declaration was for an incomplete object and the new
1833              declaration is not since many attributes of the RTL will
1834              change.  */
1835           COPY_DECL_RTL (olddecl, newdecl);
1836         }
1837     }
1838   /* If cannot merge, then use the new type and qualifiers,
1839      and don't preserve the old rtl.  */
1840   else
1841     {
1842       /* Clean out any memory we had of the old declaration.  */
1843       tree oldstatic = value_member (olddecl, static_aggregates);
1844       if (oldstatic)
1845         TREE_VALUE (oldstatic) = error_mark_node;
1846
1847       TREE_TYPE (olddecl) = TREE_TYPE (newdecl);
1848       TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
1849       TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
1850       TREE_SIDE_EFFECTS (olddecl) = TREE_SIDE_EFFECTS (newdecl);
1851     }
1852
1853   /* Merge the storage class information.  */
1854   merge_weak (newdecl, olddecl);
1855
1856   if (DECL_ONE_ONLY (olddecl))
1857     DECL_COMDAT_GROUP (newdecl) = DECL_COMDAT_GROUP (olddecl);
1858
1859   DECL_DEFER_OUTPUT (newdecl) |= DECL_DEFER_OUTPUT (olddecl);
1860   TREE_PUBLIC (newdecl) = TREE_PUBLIC (olddecl);
1861   TREE_STATIC (olddecl) = TREE_STATIC (newdecl) |= TREE_STATIC (olddecl);
1862   if (! DECL_EXTERNAL (olddecl))
1863     DECL_EXTERNAL (newdecl) = 0;
1864
1865   new_template_info = NULL_TREE;
1866   if (DECL_LANG_SPECIFIC (newdecl) && DECL_LANG_SPECIFIC (olddecl))
1867     {
1868       bool new_redefines_gnu_inline = false;
1869
1870       if (new_defines_function
1871           && ((DECL_INTERFACE_KNOWN (olddecl)
1872                && TREE_CODE (olddecl) == FUNCTION_DECL)
1873               || (TREE_CODE (olddecl) == TEMPLATE_DECL
1874                   && (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl))
1875                       == FUNCTION_DECL))))
1876         {
1877           tree fn = olddecl;
1878
1879           if (TREE_CODE (fn) == TEMPLATE_DECL)
1880             fn = DECL_TEMPLATE_RESULT (olddecl);
1881
1882           new_redefines_gnu_inline = GNU_INLINE_P (fn) && DECL_INITIAL (fn);
1883         }
1884
1885       if (!new_redefines_gnu_inline)
1886         {
1887           DECL_INTERFACE_KNOWN (newdecl) |= DECL_INTERFACE_KNOWN (olddecl);
1888           DECL_NOT_REALLY_EXTERN (newdecl) |= DECL_NOT_REALLY_EXTERN (olddecl);
1889           DECL_COMDAT (newdecl) |= DECL_COMDAT (olddecl);
1890         }
1891       DECL_TEMPLATE_INSTANTIATED (newdecl)
1892         |= DECL_TEMPLATE_INSTANTIATED (olddecl);
1893
1894       /* If the OLDDECL is an instantiation and/or specialization,
1895          then the NEWDECL must be too.  But, it may not yet be marked
1896          as such if the caller has created NEWDECL, but has not yet
1897          figured out that it is a redeclaration.  */
1898       if (!DECL_USE_TEMPLATE (newdecl))
1899         DECL_USE_TEMPLATE (newdecl) = DECL_USE_TEMPLATE (olddecl);
1900
1901       /* Don't really know how much of the language-specific
1902          values we should copy from old to new.  */
1903       DECL_IN_AGGR_P (newdecl) = DECL_IN_AGGR_P (olddecl);
1904       DECL_REPO_AVAILABLE_P (newdecl) = DECL_REPO_AVAILABLE_P (olddecl);
1905       DECL_INITIALIZED_IN_CLASS_P (newdecl)
1906         |= DECL_INITIALIZED_IN_CLASS_P (olddecl);
1907
1908       if (LANG_DECL_HAS_MIN (newdecl))
1909         {
1910           DECL_LANG_SPECIFIC (newdecl)->u.min.u2 =
1911             DECL_LANG_SPECIFIC (olddecl)->u.min.u2;
1912           if (DECL_TEMPLATE_INFO (newdecl))
1913             new_template_info = DECL_TEMPLATE_INFO (newdecl);
1914           DECL_TEMPLATE_INFO (newdecl) = DECL_TEMPLATE_INFO (olddecl);
1915         }
1916       /* Only functions have these fields.  */
1917       if (TREE_CODE (newdecl) == FUNCTION_DECL
1918           || DECL_FUNCTION_TEMPLATE_P (newdecl))
1919         {
1920           DECL_NONCONVERTING_P (newdecl) = DECL_NONCONVERTING_P (olddecl);
1921           olddecl_friend = DECL_FRIEND_P (olddecl);
1922           hidden_friend = (DECL_ANTICIPATED (olddecl)
1923                            && DECL_HIDDEN_FRIEND_P (olddecl)
1924                            && newdecl_is_friend);
1925           DECL_BEFRIENDING_CLASSES (newdecl)
1926             = chainon (DECL_BEFRIENDING_CLASSES (newdecl),
1927                        DECL_BEFRIENDING_CLASSES (olddecl));
1928           /* DECL_THUNKS is only valid for virtual functions,
1929              otherwise it is a DECL_FRIEND_CONTEXT.  */
1930           if (DECL_VIRTUAL_P (newdecl))
1931             DECL_THUNKS (newdecl) = DECL_THUNKS (olddecl);
1932         }
1933     }
1934
1935   if (TREE_CODE (newdecl) == FUNCTION_DECL)
1936     {
1937       tree parm;
1938
1939       /* Merge parameter attributes. */
1940       tree oldarg, newarg;
1941       for (oldarg = DECL_ARGUMENTS(olddecl), 
1942                newarg = DECL_ARGUMENTS(newdecl);
1943            oldarg && newarg;
1944            oldarg = TREE_CHAIN(oldarg), newarg = TREE_CHAIN(newarg)) {
1945           DECL_ATTRIBUTES (newarg)
1946               = (*targetm.merge_decl_attributes) (oldarg, newarg);
1947           DECL_ATTRIBUTES (oldarg) = DECL_ATTRIBUTES (newarg);
1948       }
1949       
1950       if (DECL_TEMPLATE_INSTANTIATION (olddecl)
1951           && !DECL_TEMPLATE_INSTANTIATION (newdecl))
1952         {
1953           /* If newdecl is not a specialization, then it is not a
1954              template-related function at all.  And that means that we
1955              should have exited above, returning 0.  */
1956           gcc_assert (DECL_TEMPLATE_SPECIALIZATION (newdecl));
1957
1958           if (TREE_USED (olddecl))
1959             /* From [temp.expl.spec]:
1960
1961                If a template, a member template or the member of a class
1962                template is explicitly specialized then that
1963                specialization shall be declared before the first use of
1964                that specialization that would cause an implicit
1965                instantiation to take place, in every translation unit in
1966                which such a use occurs.  */
1967             error ("explicit specialization of %qD after first use",
1968                       olddecl);
1969
1970           SET_DECL_TEMPLATE_SPECIALIZATION (olddecl);
1971
1972           /* Don't propagate visibility from the template to the
1973              specialization here.  We'll do that in determine_visibility if
1974              appropriate.  */
1975           DECL_VISIBILITY_SPECIFIED (olddecl) = 0;
1976
1977           /* [temp.expl.spec/14] We don't inline explicit specialization
1978              just because the primary template says so.  */
1979         }
1980       else if (new_defines_function && DECL_INITIAL (olddecl))
1981         {
1982           /* Never inline re-defined extern inline functions.
1983              FIXME: this could be better handled by keeping both
1984              function as separate declarations.  */
1985           DECL_UNINLINABLE (newdecl) = 1;
1986         }
1987       else
1988         {
1989           if (DECL_PENDING_INLINE_INFO (newdecl) == 0)
1990             DECL_PENDING_INLINE_INFO (newdecl) = DECL_PENDING_INLINE_INFO (olddecl);
1991
1992           DECL_DECLARED_INLINE_P (newdecl) |= DECL_DECLARED_INLINE_P (olddecl);
1993
1994           DECL_UNINLINABLE (newdecl) = DECL_UNINLINABLE (olddecl)
1995             = (DECL_UNINLINABLE (newdecl) || DECL_UNINLINABLE (olddecl));
1996
1997           DECL_DISREGARD_INLINE_LIMITS (newdecl)
1998             = DECL_DISREGARD_INLINE_LIMITS (olddecl)
1999             = (DECL_DISREGARD_INLINE_LIMITS (newdecl)
2000                || DECL_DISREGARD_INLINE_LIMITS (olddecl));
2001         }
2002
2003       /* Preserve abstractness on cloned [cd]tors.  */
2004       DECL_ABSTRACT (newdecl) = DECL_ABSTRACT (olddecl);
2005
2006       /* Update newdecl's parms to point at olddecl.  */
2007       for (parm = DECL_ARGUMENTS (newdecl); parm;
2008            parm = TREE_CHAIN (parm))
2009         DECL_CONTEXT (parm) = olddecl;
2010
2011       if (! types_match)
2012         {
2013           SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
2014           COPY_DECL_ASSEMBLER_NAME (newdecl, olddecl);
2015           COPY_DECL_RTL (newdecl, olddecl);
2016         }
2017       if (! types_match || new_defines_function)
2018         {
2019           /* These need to be copied so that the names are available.
2020              Note that if the types do match, we'll preserve inline
2021              info and other bits, but if not, we won't.  */
2022           DECL_ARGUMENTS (olddecl) = DECL_ARGUMENTS (newdecl);
2023           DECL_RESULT (olddecl) = DECL_RESULT (newdecl);
2024         }
2025       if (new_defines_function)
2026         /* If defining a function declared with other language
2027            linkage, use the previously declared language linkage.  */
2028         SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
2029       else if (types_match)
2030         {
2031           /* If redeclaring a builtin function, and not a definition,
2032              it stays built in.  */
2033           if (DECL_BUILT_IN (olddecl))
2034             {
2035               DECL_BUILT_IN_CLASS (newdecl) = DECL_BUILT_IN_CLASS (olddecl);
2036               DECL_FUNCTION_CODE (newdecl) = DECL_FUNCTION_CODE (olddecl);
2037               /* If we're keeping the built-in definition, keep the rtl,
2038                  regardless of declaration matches.  */
2039               COPY_DECL_RTL (olddecl, newdecl);
2040             }
2041
2042           DECL_RESULT (newdecl) = DECL_RESULT (olddecl);
2043           /* Don't clear out the arguments if we're just redeclaring a
2044              function.  */
2045           if (DECL_ARGUMENTS (olddecl))
2046             DECL_ARGUMENTS (newdecl) = DECL_ARGUMENTS (olddecl);
2047         }
2048     }
2049   else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
2050     NAMESPACE_LEVEL (newdecl) = NAMESPACE_LEVEL (olddecl);
2051
2052   /* Now preserve various other info from the definition.  */
2053   TREE_ADDRESSABLE (newdecl) = TREE_ADDRESSABLE (olddecl);
2054   TREE_ASM_WRITTEN (newdecl) = TREE_ASM_WRITTEN (olddecl);
2055   DECL_COMMON (newdecl) = DECL_COMMON (olddecl);
2056   COPY_DECL_ASSEMBLER_NAME (olddecl, newdecl);
2057
2058   /* Warn about conflicting visibility specifications.  */
2059   if (DECL_VISIBILITY_SPECIFIED (olddecl)
2060       && DECL_VISIBILITY_SPECIFIED (newdecl)
2061       && DECL_VISIBILITY (newdecl) != DECL_VISIBILITY (olddecl))
2062     {
2063       warning_at (input_location, OPT_Wattributes,
2064                   "%q+D: visibility attribute ignored because it", newdecl);
2065       warning_at (DECL_SOURCE_LOCATION (olddecl), OPT_Wattributes,
2066                   "conflicts with previous declaration here");
2067     }
2068   /* Choose the declaration which specified visibility.  */
2069   if (DECL_VISIBILITY_SPECIFIED (olddecl))
2070     {
2071       DECL_VISIBILITY (newdecl) = DECL_VISIBILITY (olddecl);
2072       DECL_VISIBILITY_SPECIFIED (newdecl) = 1;
2073     }
2074   /* Init priority used to be merged from newdecl to olddecl by the memcpy,
2075      so keep this behavior.  */
2076   if (TREE_CODE (newdecl) == VAR_DECL && DECL_HAS_INIT_PRIORITY_P (newdecl))
2077     {
2078       SET_DECL_INIT_PRIORITY (olddecl, DECL_INIT_PRIORITY (newdecl));
2079       DECL_HAS_INIT_PRIORITY_P (olddecl) = 1;
2080     }
2081
2082   /* The DECL_LANG_SPECIFIC information in OLDDECL will be replaced
2083      with that from NEWDECL below.  */
2084   if (DECL_LANG_SPECIFIC (olddecl))
2085     {
2086       gcc_assert (DECL_LANG_SPECIFIC (olddecl)
2087                   != DECL_LANG_SPECIFIC (newdecl));
2088       ggc_free (DECL_LANG_SPECIFIC (olddecl));
2089     }
2090
2091   /* Merge the USED information.  */
2092   if (TREE_USED (olddecl))
2093     TREE_USED (newdecl) = 1;
2094   else if (TREE_USED (newdecl))
2095     TREE_USED (olddecl) = 1;
2096
2097   if (TREE_CODE (newdecl) == FUNCTION_DECL)
2098     {
2099       int function_size;
2100
2101       function_size = sizeof (struct tree_decl_common);
2102
2103       memcpy ((char *) olddecl + sizeof (struct tree_common),
2104               (char *) newdecl + sizeof (struct tree_common),
2105               function_size - sizeof (struct tree_common));
2106
2107       memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2108               (char *) newdecl + sizeof (struct tree_decl_common),
2109               sizeof (struct tree_function_decl) - sizeof (struct tree_decl_common));
2110       if (new_template_info)
2111         /* If newdecl is a template instantiation, it is possible that
2112            the following sequence of events has occurred:
2113
2114            o A friend function was declared in a class template.  The
2115            class template was instantiated.
2116
2117            o The instantiation of the friend declaration was
2118            recorded on the instantiation list, and is newdecl.
2119
2120            o Later, however, instantiate_class_template called pushdecl
2121            on the newdecl to perform name injection.  But, pushdecl in
2122            turn called duplicate_decls when it discovered that another
2123            declaration of a global function with the same name already
2124            existed.
2125
2126            o Here, in duplicate_decls, we decided to clobber newdecl.
2127
2128            If we're going to do that, we'd better make sure that
2129            olddecl, and not newdecl, is on the list of
2130            instantiations so that if we try to do the instantiation
2131            again we won't get the clobbered declaration.  */
2132         reregister_specialization (newdecl,
2133                                    new_template_info,
2134                                    olddecl);
2135     }
2136   else
2137     {
2138       size_t size = tree_code_size (TREE_CODE (olddecl));
2139       memcpy ((char *) olddecl + sizeof (struct tree_common),
2140               (char *) newdecl + sizeof (struct tree_common),
2141               sizeof (struct tree_decl_common) - sizeof (struct tree_common));
2142       switch (TREE_CODE (olddecl))
2143         {
2144         case LABEL_DECL:
2145         case VAR_DECL:
2146         case RESULT_DECL:
2147         case PARM_DECL:
2148         case FIELD_DECL:
2149         case TYPE_DECL:
2150         case CONST_DECL:
2151           {
2152             memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2153                     (char *) newdecl + sizeof (struct tree_decl_common),
2154                     size - sizeof (struct tree_decl_common)
2155                     + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
2156           }
2157           break;
2158         default:
2159           memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2160                   (char *) newdecl + sizeof (struct tree_decl_common),
2161                   sizeof (struct tree_decl_non_common) - sizeof (struct tree_decl_common)
2162                   + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
2163           break;
2164         }
2165     }
2166   DECL_UID (olddecl) = olddecl_uid;
2167   if (olddecl_friend)
2168     DECL_FRIEND_P (olddecl) = 1;
2169   if (hidden_friend)
2170     {
2171       DECL_ANTICIPATED (olddecl) = 1;
2172       DECL_HIDDEN_FRIEND_P (olddecl) = 1;
2173     }
2174
2175   /* NEWDECL contains the merged attribute lists.
2176      Update OLDDECL to be the same.  */
2177   DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
2178
2179   /* If OLDDECL had its DECL_RTL instantiated, re-invoke make_decl_rtl
2180     so that encode_section_info has a chance to look at the new decl
2181     flags and attributes.  */
2182   if (DECL_RTL_SET_P (olddecl)
2183       && (TREE_CODE (olddecl) == FUNCTION_DECL
2184           || (TREE_CODE (olddecl) == VAR_DECL
2185               && TREE_STATIC (olddecl))))
2186     make_decl_rtl (olddecl);
2187
2188   /* The NEWDECL will no longer be needed.  Because every out-of-class
2189      declaration of a member results in a call to duplicate_decls,
2190      freeing these nodes represents in a significant savings.  */
2191   ggc_free (newdecl);
2192
2193   return olddecl;
2194 }
2195 \f
2196 /* Return zero if the declaration NEWDECL is valid
2197    when the declaration OLDDECL (assumed to be for the same name)
2198    has already been seen.
2199    Otherwise return an error message format string with a %s
2200    where the identifier should go.  */
2201
2202 static const char *
2203 redeclaration_error_message (tree newdecl, tree olddecl)
2204 {
2205   if (TREE_CODE (newdecl) == TYPE_DECL)
2206     {
2207       /* Because C++ can put things into name space for free,
2208          constructs like "typedef struct foo { ... } foo"
2209          would look like an erroneous redeclaration.  */
2210       if (same_type_p (TREE_TYPE (newdecl), TREE_TYPE (olddecl)))
2211         return NULL;
2212       else
2213         return "redefinition of %q#D";
2214     }
2215   else if (TREE_CODE (newdecl) == FUNCTION_DECL)
2216     {
2217       /* If this is a pure function, its olddecl will actually be
2218          the original initialization to `0' (which we force to call
2219          abort()).  Don't complain about redefinition in this case.  */
2220       if (DECL_LANG_SPECIFIC (olddecl) && DECL_PURE_VIRTUAL_P (olddecl)
2221           && DECL_INITIAL (olddecl) == NULL_TREE)
2222         return NULL;
2223
2224       /* If both functions come from different namespaces, this is not
2225          a redeclaration - this is a conflict with a used function.  */
2226       if (DECL_NAMESPACE_SCOPE_P (olddecl)
2227           && DECL_CONTEXT (olddecl) != DECL_CONTEXT (newdecl)
2228           && ! decls_match (olddecl, newdecl))
2229         return "%qD conflicts with used function";
2230
2231       /* We'll complain about linkage mismatches in
2232          warn_extern_redeclared_static.  */
2233
2234       /* Defining the same name twice is no good.  */
2235       if (DECL_INITIAL (olddecl) != NULL_TREE
2236           && DECL_INITIAL (newdecl) != NULL_TREE)
2237         {
2238           if (DECL_NAME (olddecl) == NULL_TREE)
2239             return "%q#D not declared in class";
2240           else if (!GNU_INLINE_P (olddecl)
2241                    || GNU_INLINE_P (newdecl))
2242             return "redefinition of %q#D";
2243         }
2244
2245       if (DECL_DECLARED_INLINE_P (olddecl) && DECL_DECLARED_INLINE_P (newdecl))
2246         {
2247           bool olda = GNU_INLINE_P (olddecl);
2248           bool newa = GNU_INLINE_P (newdecl);
2249
2250           if (olda != newa)
2251             {
2252               if (newa)
2253                 return "%q+D redeclared inline with %<gnu_inline%> attribute";
2254               else
2255                 return "%q+D redeclared inline without %<gnu_inline%> attribute";
2256             }
2257         }
2258
2259       return NULL;
2260     }
2261   else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
2262     {
2263       tree nt, ot;
2264
2265       if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == TYPE_DECL)
2266         {
2267           if (COMPLETE_TYPE_P (TREE_TYPE (newdecl))
2268               && COMPLETE_TYPE_P (TREE_TYPE (olddecl)))
2269             return "redefinition of %q#D";
2270           return NULL;
2271         }
2272
2273       if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) != FUNCTION_DECL
2274           || (DECL_TEMPLATE_RESULT (newdecl)
2275               == DECL_TEMPLATE_RESULT (olddecl)))
2276         return NULL;
2277
2278       nt = DECL_TEMPLATE_RESULT (newdecl);
2279       if (DECL_TEMPLATE_INFO (nt))
2280         nt = DECL_TEMPLATE_RESULT (template_for_substitution (nt));
2281       ot = DECL_TEMPLATE_RESULT (olddecl);
2282       if (DECL_TEMPLATE_INFO (ot))
2283         ot = DECL_TEMPLATE_RESULT (template_for_substitution (ot));
2284       if (DECL_INITIAL (nt) && DECL_INITIAL (ot)
2285           && (!GNU_INLINE_P (ot) || GNU_INLINE_P (nt)))
2286         return "redefinition of %q#D";
2287
2288       if (DECL_DECLARED_INLINE_P (ot) && DECL_DECLARED_INLINE_P (nt))
2289         {
2290           bool olda = GNU_INLINE_P (ot);
2291           bool newa = GNU_INLINE_P (nt);
2292
2293           if (olda != newa)
2294             {
2295               if (newa)
2296                 return "%q+D redeclared inline with %<gnu_inline%> attribute";
2297               else
2298                 return "%q+D redeclared inline without %<gnu_inline%> attribute";
2299             }
2300         }
2301
2302       /* Core issue #226 (C++0x): 
2303            
2304            If a friend function template declaration specifies a
2305            default template-argument, that declaration shall be a
2306            definition and shall be the only declaration of the
2307            function template in the translation unit.  */
2308       if ((cxx_dialect != cxx98) 
2309           && TREE_CODE (ot) == FUNCTION_DECL && DECL_FRIEND_P (ot)
2310           && !check_default_tmpl_args (nt, DECL_TEMPLATE_PARMS (newdecl), 
2311                                        /*is_primary=*/1, /*is_partial=*/0,
2312                                        /*is_friend_decl=*/2))
2313         return "redeclaration of friend %q#D may not have default template arguments";
2314
2315       return NULL;
2316     }
2317   else if (TREE_CODE (newdecl) == VAR_DECL
2318            && DECL_THREAD_LOCAL_P (newdecl) != DECL_THREAD_LOCAL_P (olddecl)
2319            && (! DECL_LANG_SPECIFIC (olddecl)
2320                || ! CP_DECL_THREADPRIVATE_P (olddecl)
2321                || DECL_THREAD_LOCAL_P (newdecl)))
2322     {
2323       /* Only variables can be thread-local, and all declarations must
2324          agree on this property.  */
2325       if (DECL_THREAD_LOCAL_P (newdecl))
2326         return "thread-local declaration of %q#D follows "
2327                "non-thread-local declaration";
2328       else
2329         return "non-thread-local declaration of %q#D follows "
2330                "thread-local declaration";
2331     }
2332   else if (toplevel_bindings_p () || DECL_NAMESPACE_SCOPE_P (newdecl))
2333     {
2334       /* The objects have been declared at namespace scope.  If either
2335          is a member of an anonymous union, then this is an invalid
2336          redeclaration.  For example:
2337
2338            int i;
2339            union { int i; };
2340
2341            is invalid.  */
2342       if ((TREE_CODE (newdecl) == VAR_DECL && DECL_ANON_UNION_VAR_P (newdecl))
2343           || (TREE_CODE (olddecl) == VAR_DECL && DECL_ANON_UNION_VAR_P (olddecl)))
2344         return "redeclaration of %q#D";
2345       /* If at least one declaration is a reference, there is no
2346          conflict.  For example:
2347
2348            int i = 3;
2349            extern int i;
2350
2351          is valid.  */
2352       if (DECL_EXTERNAL (newdecl) || DECL_EXTERNAL (olddecl))
2353         return NULL;
2354       /* Reject two definitions.  */
2355       return "redefinition of %q#D";
2356     }
2357   else
2358     {
2359       /* Objects declared with block scope:  */
2360       /* Reject two definitions, and reject a definition
2361          together with an external reference.  */
2362       if (!(DECL_EXTERNAL (newdecl) && DECL_EXTERNAL (olddecl)))
2363         return "redeclaration of %q#D";
2364       return NULL;
2365     }
2366 }
2367 \f
2368 /* Hash and equality functions for the named_label table.  */
2369
2370 static hashval_t
2371 named_label_entry_hash (const void *data)
2372 {
2373   const struct named_label_entry *ent = (const struct named_label_entry *) data;
2374   return DECL_UID (ent->label_decl);
2375 }
2376
2377 static int
2378 named_label_entry_eq (const void *a, const void *b)
2379 {
2380   const struct named_label_entry *ent_a = (const struct named_label_entry *) a;
2381   const struct named_label_entry *ent_b = (const struct named_label_entry *) b;
2382   return ent_a->label_decl == ent_b->label_decl;
2383 }
2384
2385 /* Create a new label, named ID.  */
2386
2387 static tree
2388 make_label_decl (tree id, int local_p)
2389 {
2390   struct named_label_entry *ent;
2391   void **slot;
2392   tree decl;
2393
2394   decl = build_decl (input_location, LABEL_DECL, id, void_type_node);
2395
2396   DECL_CONTEXT (decl) = current_function_decl;
2397   DECL_MODE (decl) = VOIDmode;
2398   C_DECLARED_LABEL_FLAG (decl) = local_p;
2399
2400   /* Say where one reference is to the label, for the sake of the
2401      error if it is not defined.  */
2402   DECL_SOURCE_LOCATION (decl) = input_location;
2403
2404   /* Record the fact that this identifier is bound to this label.  */
2405   SET_IDENTIFIER_LABEL_VALUE (id, decl);
2406
2407   /* Create the label htab for the function on demand.  */
2408   if (!named_labels)
2409     named_labels = htab_create_ggc (13, named_label_entry_hash,
2410                                     named_label_entry_eq, NULL);
2411
2412   /* Record this label on the list of labels used in this function.
2413      We do this before calling make_label_decl so that we get the
2414      IDENTIFIER_LABEL_VALUE before the new label is declared.  */
2415   ent = GGC_CNEW (struct named_label_entry);
2416   ent->label_decl = decl;
2417
2418   slot = htab_find_slot (named_labels, ent, INSERT);
2419   gcc_assert (*slot == NULL);
2420   *slot = ent;
2421
2422   return decl;
2423 }
2424
2425 /* Look for a label named ID in the current function.  If one cannot
2426    be found, create one.  (We keep track of used, but undefined,
2427    labels, and complain about them at the end of a function.)  */
2428
2429 tree
2430 lookup_label (tree id)
2431 {
2432   tree decl;
2433
2434   timevar_push (TV_NAME_LOOKUP);
2435   /* You can't use labels at global scope.  */
2436   if (current_function_decl == NULL_TREE)
2437     {
2438       error ("label %qE referenced outside of any function", id);
2439       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, NULL_TREE);
2440     }
2441
2442   /* See if we've already got this label.  */
2443   decl = IDENTIFIER_LABEL_VALUE (id);
2444   if (decl != NULL_TREE && DECL_CONTEXT (decl) == current_function_decl)
2445     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, decl);
2446
2447   decl = make_label_decl (id, /*local_p=*/0);
2448   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, decl);
2449 }
2450
2451 /* Declare a local label named ID.  */
2452
2453 tree
2454 declare_local_label (tree id)
2455 {
2456   tree decl, shadow;
2457
2458   /* Add a new entry to the SHADOWED_LABELS list so that when we leave
2459      this scope we can restore the old value of IDENTIFIER_TYPE_VALUE.  */
2460   shadow = tree_cons (IDENTIFIER_LABEL_VALUE (id), NULL_TREE,
2461                       current_binding_level->shadowed_labels);
2462   current_binding_level->shadowed_labels = shadow;
2463
2464   decl = make_label_decl (id, /*local_p=*/1);
2465   TREE_VALUE (shadow) = decl;
2466
2467   return decl;
2468 }
2469
2470 /* Returns nonzero if it is ill-formed to jump past the declaration of
2471    DECL.  Returns 2 if it's also a real problem.  */
2472
2473 static int
2474 decl_jump_unsafe (tree decl)
2475 {
2476   /* [stmt.dcl]/3: A program that jumps from a point where a local variable
2477      with automatic storage duration is not in scope to a point where it is
2478      in scope is ill-formed unless the variable has scalar type, class type
2479      with a trivial default constructor and a trivial destructor, a
2480      cv-qualified version of one of these types, or an array of one of the
2481      preceding types and is declared without an initializer (8.5).  */
2482   tree type = TREE_TYPE (decl);
2483
2484   if (TREE_CODE (decl) != VAR_DECL || TREE_STATIC (decl)
2485       || type == error_mark_node)
2486     return 0;
2487
2488   type = strip_array_types (type);
2489
2490   if (type_has_nontrivial_default_init (TREE_TYPE (decl))
2491       || DECL_NONTRIVIALLY_INITIALIZED_P (decl))
2492     return 2;
2493
2494   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
2495     return 1;
2496
2497   return 0;
2498 }
2499
2500 /* A subroutine of check_previous_goto_1 to identify a branch to the user.  */
2501
2502 static void
2503 identify_goto (tree decl, const location_t *locus)
2504 {
2505   if (decl)
2506     permerror (input_location, "jump to label %qD", decl);
2507   else
2508     permerror (input_location, "jump to case label");
2509   if (locus)
2510     permerror (*locus, "  from here");
2511 }
2512
2513 /* Check that a single previously seen jump to a newly defined label
2514    is OK.  DECL is the LABEL_DECL or 0; LEVEL is the binding_level for
2515    the jump context; NAMES are the names in scope in LEVEL at the jump
2516    context; LOCUS is the source position of the jump or 0.  Returns
2517    true if all is well.  */
2518
2519 static bool
2520 check_previous_goto_1 (tree decl, struct cp_binding_level* level, tree names,
2521                        bool exited_omp, const location_t *locus)
2522 {
2523   struct cp_binding_level *b;
2524   bool identified = false, saw_eh = false, saw_omp = false;
2525
2526   if (exited_omp)
2527     {
2528       identify_goto (decl, locus);
2529       error ("  exits OpenMP structured block");
2530       identified = saw_omp = true;
2531     }
2532
2533   for (b = current_binding_level; b ; b = b->level_chain)
2534     {
2535       tree new_decls, old_decls = (b == level ? names : NULL_TREE);
2536
2537       for (new_decls = b->names; new_decls != old_decls;
2538            new_decls = TREE_CHAIN (new_decls))
2539         {
2540           int problem = decl_jump_unsafe (new_decls);
2541           if (! problem)
2542             continue;
2543
2544           if (!identified)
2545             {
2546               identify_goto (decl, locus);
2547               identified = true;
2548             }
2549           if (problem > 1)
2550             error ("  crosses initialization of %q+#D", new_decls);
2551           else
2552             permerror (input_location, "  enters scope of %q+#D which has "
2553                        "non-trivial destructor", new_decls);
2554         }
2555
2556       if (b == level)
2557         break;
2558       if ((b->kind == sk_try || b->kind == sk_catch) && !saw_eh)
2559         {
2560           if (!identified)
2561             {
2562               identify_goto (decl, locus);
2563               identified = true;
2564             }
2565           if (b->kind == sk_try)
2566             error ("  enters try block");
2567           else
2568             error ("  enters catch block");
2569           saw_eh = true;
2570         }
2571       if (b->kind == sk_omp && !saw_omp)
2572         {
2573           if (!identified)
2574             {
2575               identify_goto (decl, locus);
2576               identified = true;
2577             }
2578           error ("  enters OpenMP structured block");
2579           saw_omp = true;
2580         }
2581     }
2582
2583   return !identified;
2584 }
2585
2586 static void
2587 check_previous_goto (tree decl, struct named_label_use_entry *use)
2588 {
2589   check_previous_goto_1 (decl, use->binding_level,
2590                          use->names_in_scope, use->in_omp_scope,
2591                          &use->o_goto_locus);
2592 }
2593
2594 static bool
2595 check_switch_goto (struct cp_binding_level* level)
2596 {
2597   return check_previous_goto_1 (NULL_TREE, level, level->names, false, NULL);
2598 }
2599
2600 /* Check that a new jump to a label DECL is OK.  Called by
2601    finish_goto_stmt.  */
2602
2603 void
2604 check_goto (tree decl)
2605 {
2606   struct named_label_entry *ent, dummy;
2607   bool saw_catch = false, identified = false;
2608   tree bad;
2609
2610   /* We can't know where a computed goto is jumping.
2611      So we assume that it's OK.  */
2612   if (TREE_CODE (decl) != LABEL_DECL)
2613     return;
2614
2615   /* We didn't record any information about this label when we created it,
2616      and there's not much point since it's trivial to analyze as a return.  */
2617   if (decl == cdtor_label)
2618     return;
2619
2620   dummy.label_decl = decl;
2621   ent = (struct named_label_entry *) htab_find (named_labels, &dummy);
2622   gcc_assert (ent != NULL);
2623
2624   /* If the label hasn't been defined yet, defer checking.  */
2625   if (! DECL_INITIAL (decl))
2626     {
2627       struct named_label_use_entry *new_use;
2628
2629       /* Don't bother creating another use if the last goto had the
2630          same data, and will therefore create the same set of errors.  */
2631       if (ent->uses
2632           && ent->uses->names_in_scope == current_binding_level->names)
2633         return;
2634
2635       new_use = GGC_NEW (struct named_label_use_entry);
2636       new_use->binding_level = current_binding_level;
2637       new_use->names_in_scope = current_binding_level->names;
2638       new_use->o_goto_locus = input_location;
2639       new_use->in_omp_scope = false;
2640
2641       new_use->next = ent->uses;
2642       ent->uses = new_use;
2643       return;
2644     }
2645
2646   if (ent->in_try_scope || ent->in_catch_scope
2647       || ent->in_omp_scope || ent->bad_decls)
2648     {
2649       permerror (input_location, "jump to label %q+D", decl);
2650       permerror (input_location, "  from here");
2651       identified = true;
2652     }
2653
2654   for (bad = ent->bad_decls; bad; bad = TREE_CHAIN (bad))
2655     {
2656       tree b = TREE_VALUE (bad);
2657       int u = decl_jump_unsafe (b);
2658
2659       if (u > 1 && DECL_ARTIFICIAL (b))
2660         {
2661           /* Can't skip init of __exception_info.  */
2662           error_at (DECL_SOURCE_LOCATION (b), "  enters catch block");
2663           saw_catch = true;
2664         }
2665       else if (u > 1)
2666         error ("  skips initialization of %q+#D", b);
2667       else
2668         permerror (input_location, "  enters scope of %q+#D which has "
2669                    "non-trivial destructor", b);
2670     }
2671
2672   if (ent->in_try_scope)
2673     error ("  enters try block");
2674   else if (ent->in_catch_scope && !saw_catch)
2675     error ("  enters catch block");
2676
2677   if (ent->in_omp_scope)
2678     error ("  enters OpenMP structured block");
2679   else if (flag_openmp)
2680     {
2681       struct cp_binding_level *b;
2682       for (b = current_binding_level; b ; b = b->level_chain)
2683         {
2684           if (b == ent->binding_level)
2685             break;
2686           if (b->kind == sk_omp)
2687             {
2688               if (!identified)
2689                 {
2690                   permerror (input_location, "jump to label %q+D", decl);
2691                   permerror (input_location, "  from here");
2692                   identified = true;
2693                 }
2694               error ("  exits OpenMP structured block");
2695               break;
2696             }
2697         }
2698     }
2699 }
2700
2701 /* Check that a return is ok wrt OpenMP structured blocks.
2702    Called by finish_return_stmt.  Returns true if all is well.  */
2703
2704 bool
2705 check_omp_return (void)
2706 {
2707   struct cp_binding_level *b;
2708   for (b = current_binding_level; b ; b = b->level_chain)
2709     if (b->kind == sk_omp)
2710       {
2711         error ("invalid exit from OpenMP structured block");
2712         return false;
2713       }
2714   return true;
2715 }
2716
2717 /* Define a label, specifying the location in the source file.
2718    Return the LABEL_DECL node for the label.  */
2719
2720 tree
2721 define_label (location_t location, tree name)
2722 {
2723   struct named_label_entry *ent, dummy;
2724   struct cp_binding_level *p;
2725   tree decl;
2726
2727   timevar_push (TV_NAME_LOOKUP);
2728
2729   decl = lookup_label (name);
2730
2731   dummy.label_decl = decl;
2732   ent = (struct named_label_entry *) htab_find (named_labels, &dummy);
2733   gcc_assert (ent != NULL);
2734
2735   /* After labels, make any new cleanups in the function go into their
2736      own new (temporary) binding contour.  */
2737   for (p = current_binding_level;
2738        p->kind != sk_function_parms;
2739        p = p->level_chain)
2740     p->more_cleanups_ok = 0;
2741
2742   if (name == get_identifier ("wchar_t"))
2743     permerror (input_location, "label named wchar_t");
2744
2745   if (DECL_INITIAL (decl) != NULL_TREE)
2746     {
2747       error ("duplicate label %qD", decl);
2748       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
2749     }
2750   else
2751     {
2752       struct named_label_use_entry *use;
2753
2754       /* Mark label as having been defined.  */
2755       DECL_INITIAL (decl) = error_mark_node;
2756       /* Say where in the source.  */
2757       DECL_SOURCE_LOCATION (decl) = location;
2758
2759       ent->binding_level = current_binding_level;
2760       ent->names_in_scope = current_binding_level->names;
2761
2762       for (use = ent->uses; use ; use = use->next)
2763         check_previous_goto (decl, use);
2764       ent->uses = NULL;
2765     }
2766
2767   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, decl);
2768 }
2769
2770 struct cp_switch
2771 {
2772   struct cp_binding_level *level;
2773   struct cp_switch *next;
2774   /* The SWITCH_STMT being built.  */
2775   tree switch_stmt;
2776   /* A splay-tree mapping the low element of a case range to the high
2777      element, or NULL_TREE if there is no high element.  Used to
2778      determine whether or not a new case label duplicates an old case
2779      label.  We need a tree, rather than simply a hash table, because
2780      of the GNU case range extension.  */
2781   splay_tree cases;
2782 };
2783
2784 /* A stack of the currently active switch statements.  The innermost
2785    switch statement is on the top of the stack.  There is no need to
2786    mark the stack for garbage collection because it is only active
2787    during the processing of the body of a function, and we never
2788    collect at that point.  */
2789
2790 static struct cp_switch *switch_stack;
2791
2792 /* Called right after a switch-statement condition is parsed.
2793    SWITCH_STMT is the switch statement being parsed.  */
2794
2795 void
2796 push_switch (tree switch_stmt)
2797 {
2798   struct cp_switch *p = XNEW (struct cp_switch);
2799   p->level = current_binding_level;
2800   p->next = switch_stack;
2801   p->switch_stmt = switch_stmt;
2802   p->cases = splay_tree_new (case_compare, NULL, NULL);
2803   switch_stack = p;
2804 }
2805
2806 void
2807 pop_switch (void)
2808 {
2809   struct cp_switch *cs = switch_stack;
2810   location_t switch_location;
2811
2812   /* Emit warnings as needed.  */
2813   if (EXPR_HAS_LOCATION (cs->switch_stmt))
2814     switch_location = EXPR_LOCATION (cs->switch_stmt);
2815   else
2816     switch_location = input_location;
2817   if (!processing_template_decl)
2818     c_do_switch_warnings (cs->cases, switch_location,
2819                           SWITCH_STMT_TYPE (cs->switch_stmt),
2820                           SWITCH_STMT_COND (cs->switch_stmt));
2821
2822   splay_tree_delete (cs->cases);
2823   switch_stack = switch_stack->next;
2824   free (cs);
2825 }
2826
2827 /* Note that we've seen a definition of a case label, and complain if this
2828    is a bad place for one.  */
2829
2830 tree
2831 finish_case_label (location_t loc, tree low_value, tree high_value)
2832 {
2833   tree cond, r;
2834   struct cp_binding_level *p;
2835
2836   if (processing_template_decl)
2837     {
2838       tree label;
2839
2840       /* For templates, just add the case label; we'll do semantic
2841          analysis at instantiation-time.  */
2842       label = build_decl (loc, LABEL_DECL, NULL_TREE, NULL_TREE);
2843       return add_stmt (build_case_label (loc, low_value, high_value, label));
2844     }
2845
2846   /* Find the condition on which this switch statement depends.  */
2847   cond = SWITCH_STMT_COND (switch_stack->switch_stmt);
2848   if (cond && TREE_CODE (cond) == TREE_LIST)
2849     cond = TREE_VALUE (cond);
2850
2851   if (!check_switch_goto (switch_stack->level))
2852     return error_mark_node;
2853
2854   r = c_add_case_label (loc, switch_stack->cases, cond,
2855                         SWITCH_STMT_TYPE (switch_stack->switch_stmt),
2856                         low_value, high_value);
2857
2858   /* After labels, make any new cleanups in the function go into their
2859      own new (temporary) binding contour.  */
2860   for (p = current_binding_level;
2861        p->kind != sk_function_parms;
2862        p = p->level_chain)
2863     p->more_cleanups_ok = 0;
2864
2865   return r;
2866 }
2867 \f
2868 /* Hash a TYPENAME_TYPE.  K is really of type `tree'.  */
2869
2870 static hashval_t
2871 typename_hash (const void* k)
2872 {
2873   hashval_t hash;
2874   const_tree const t = (const_tree) k;
2875
2876   hash = (htab_hash_pointer (TYPE_CONTEXT (t))
2877           ^ htab_hash_pointer (DECL_NAME (TYPE_NAME (t))));
2878
2879   return hash;
2880 }
2881
2882 typedef struct typename_info {
2883   tree scope;
2884   tree name;
2885   tree template_id;
2886   bool enum_p;
2887   bool class_p;
2888 } typename_info;
2889
2890 /* Compare two TYPENAME_TYPEs.  K1 is really of type `tree', K2 is
2891    really of type `typename_info*'  */
2892
2893 static int
2894 typename_compare (const void * k1, const void * k2)
2895 {
2896   const_tree const t1 = (const_tree) k1;
2897   const typename_info *const t2 = (const typename_info *) k2;
2898
2899   return (DECL_NAME (TYPE_NAME (t1)) == t2->name
2900           && TYPE_CONTEXT (t1) == t2->scope
2901           && TYPENAME_TYPE_FULLNAME (t1) == t2->template_id
2902           && TYPENAME_IS_ENUM_P (t1) == t2->enum_p
2903           && TYPENAME_IS_CLASS_P (t1) == t2->class_p);
2904 }
2905
2906 /* Build a TYPENAME_TYPE.  If the type is `typename T::t', CONTEXT is
2907    the type of `T', NAME is the IDENTIFIER_NODE for `t'.
2908
2909    Returns the new TYPENAME_TYPE.  */
2910
2911 static GTY ((param_is (union tree_node))) htab_t typename_htab;
2912
2913 static tree
2914 build_typename_type (tree context, tree name, tree fullname,
2915                      enum tag_types tag_type)
2916 {
2917   tree t;
2918   tree d;
2919   typename_info ti;
2920   void **e;
2921   hashval_t hash;
2922
2923   if (typename_htab == NULL)
2924     typename_htab = htab_create_ggc (61, &typename_hash,
2925                                      &typename_compare, NULL);
2926
2927   ti.scope = FROB_CONTEXT (context);
2928   ti.name = name;
2929   ti.template_id = fullname;
2930   ti.enum_p = tag_type == enum_type;
2931   ti.class_p = (tag_type == class_type
2932                 || tag_type == record_type
2933                 || tag_type == union_type);
2934   hash =  (htab_hash_pointer (ti.scope)
2935            ^ htab_hash_pointer (ti.name));
2936
2937   /* See if we already have this type.  */
2938   e = htab_find_slot_with_hash (typename_htab, &ti, hash, INSERT);
2939   if (*e)
2940     t = (tree) *e;
2941   else
2942     {
2943       /* Build the TYPENAME_TYPE.  */
2944       t = cxx_make_type (TYPENAME_TYPE);
2945       TYPE_CONTEXT (t) = ti.scope;
2946       TYPENAME_TYPE_FULLNAME (t) = ti.template_id;
2947       TYPENAME_IS_ENUM_P (t) = ti.enum_p;
2948       TYPENAME_IS_CLASS_P (t) = ti.class_p;
2949
2950       /* Build the corresponding TYPE_DECL.  */
2951       d = build_decl (input_location, TYPE_DECL, name, t);
2952       TYPE_NAME (TREE_TYPE (d)) = d;
2953       TYPE_STUB_DECL (TREE_TYPE (d)) = d;
2954       DECL_CONTEXT (d) = FROB_CONTEXT (context);
2955       DECL_ARTIFICIAL (d) = 1;
2956
2957       /* Store it in the hash table.  */
2958       *e = t;
2959
2960       /* TYPENAME_TYPEs must always be compared structurally, because
2961          they may or may not resolve down to another type depending on
2962          the currently open classes. */
2963       SET_TYPE_STRUCTURAL_EQUALITY (t);
2964     }
2965
2966   return t;
2967 }
2968
2969 /* Resolve `typename CONTEXT::NAME'.  TAG_TYPE indicates the tag
2970    provided to name the type.  Returns an appropriate type, unless an
2971    error occurs, in which case error_mark_node is returned.  If we
2972    locate a non-artificial TYPE_DECL and TF_KEEP_TYPE_DECL is set, we
2973    return that, rather than the _TYPE it corresponds to, in other
2974    cases we look through the type decl.  If TF_ERROR is set, complain
2975    about errors, otherwise be quiet.  */
2976
2977 tree
2978 make_typename_type (tree context, tree name, enum tag_types tag_type,
2979                     tsubst_flags_t complain)
2980 {
2981   tree fullname;
2982   tree t;
2983   bool want_template;
2984
2985   if (name == error_mark_node
2986       || context == NULL_TREE
2987       || context == error_mark_node)
2988     return error_mark_node;
2989
2990   if (TYPE_P (name))
2991     {
2992       if (!(TYPE_LANG_SPECIFIC (name)
2993             && (CLASSTYPE_IS_TEMPLATE (name)
2994                 || CLASSTYPE_USE_TEMPLATE (name))))
2995         name = TYPE_IDENTIFIER (name);
2996       else
2997         /* Create a TEMPLATE_ID_EXPR for the type.  */
2998         name = build_nt (TEMPLATE_ID_EXPR,
2999                          CLASSTYPE_TI_TEMPLATE (name),
3000                          CLASSTYPE_TI_ARGS (name));
3001     }
3002   else if (TREE_CODE (name) == TYPE_DECL)
3003     name = DECL_NAME (name);
3004
3005   fullname = name;
3006
3007   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
3008     {
3009       name = TREE_OPERAND (name, 0);
3010       if (TREE_CODE (name) == TEMPLATE_DECL)
3011         name = TREE_OPERAND (fullname, 0) = DECL_NAME (name);
3012       else if (TREE_CODE (name) == OVERLOAD)
3013         {
3014           error ("%qD is not a type", name);
3015           return error_mark_node;
3016         }
3017     }
3018   if (TREE_CODE (name) == TEMPLATE_DECL)
3019     {
3020       error ("%qD used without template parameters", name);
3021       return error_mark_node;
3022     }
3023   gcc_assert (TREE_CODE (name) == IDENTIFIER_NODE);
3024   gcc_assert (TYPE_P (context));
3025
3026   if (!MAYBE_CLASS_TYPE_P (context))
3027     {
3028       if (complain & tf_error)
3029         error ("%q#T is not a class", context);
3030       return error_mark_node;
3031     }
3032   
3033   /* When the CONTEXT is a dependent type,  NAME could refer to a
3034      dependent base class of CONTEXT.  But look inside it anyway
3035      if CONTEXT is a currently open scope, in case it refers to a
3036      member of the current instantiation or a non-dependent base;
3037      lookup will stop when we hit a dependent base.  */
3038   if (!dependent_scope_p (context))
3039     /* We should only set WANT_TYPE when we're a nested typename type.
3040        Then we can give better diagnostics if we find a non-type.  */
3041     t = lookup_field (context, name, 0, /*want_type=*/true);
3042   else
3043     t = NULL_TREE;
3044
3045   if (!t && dependent_type_p (context)) 
3046     return build_typename_type (context, name, fullname, tag_type);
3047
3048   want_template = TREE_CODE (fullname) == TEMPLATE_ID_EXPR;
3049   
3050   if (!t)
3051     {
3052       if (complain & tf_error)
3053         error (want_template ? "no class template named %q#T in %q#T"
3054                : "no type named %q#T in %q#T", name, context);
3055       return error_mark_node;
3056     }
3057   
3058   if (want_template && !DECL_CLASS_TEMPLATE_P (t))
3059     {
3060       if (complain & tf_error)
3061         error ("%<typename %T::%D%> names %q#T, which is not a class template",
3062                context, name, t);
3063       return error_mark_node;
3064     }
3065   if (!want_template && TREE_CODE (t) != TYPE_DECL)
3066     {
3067       if (complain & tf_error)
3068         error ("%<typename %T::%D%> names %q#T, which is not a type",
3069                context, name, t);
3070       return error_mark_node;
3071     }
3072   
3073   if (complain & tf_error)
3074     perform_or_defer_access_check (TYPE_BINFO (context), t, t);
3075
3076   if (want_template)
3077     return lookup_template_class (t, TREE_OPERAND (fullname, 1),
3078                                   NULL_TREE, context,
3079                                   /*entering_scope=*/0,
3080                                   tf_warning_or_error | tf_user);
3081   
3082   if (DECL_ARTIFICIAL (t) || !(complain & tf_keep_type_decl))
3083     t = TREE_TYPE (t);
3084   
3085   return t;
3086 }
3087
3088 /* Resolve `CONTEXT::template NAME'.  Returns a TEMPLATE_DECL if the name
3089    can be resolved or an UNBOUND_CLASS_TEMPLATE, unless an error occurs,
3090    in which case error_mark_node is returned.
3091
3092    If PARM_LIST is non-NULL, also make sure that the template parameter
3093    list of TEMPLATE_DECL matches.
3094
3095    If COMPLAIN zero, don't complain about any errors that occur.  */
3096
3097 tree
3098 make_unbound_class_template (tree context, tree name, tree parm_list,
3099                              tsubst_flags_t complain)
3100 {
3101   tree t;
3102   tree d;
3103
3104   if (TYPE_P (name))
3105     name = TYPE_IDENTIFIER (name);
3106   else if (DECL_P (name))
3107     name = DECL_NAME (name);
3108   gcc_assert (TREE_CODE (name) == IDENTIFIER_NODE);
3109
3110   if (!dependent_type_p (context)
3111       || currently_open_class (context))
3112     {
3113       tree tmpl = NULL_TREE;
3114
3115       if (MAYBE_CLASS_TYPE_P (context))
3116         tmpl = lookup_field (context, name, 0, false);
3117
3118       if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
3119         {
3120           if (complain & tf_error)
3121             error ("no class template named %q#T in %q#T", name, context);
3122           return error_mark_node;
3123         }
3124
3125       if (parm_list
3126           && !comp_template_parms (DECL_TEMPLATE_PARMS (tmpl), parm_list))
3127         {
3128           if (complain & tf_error)
3129             {
3130               error ("template parameters do not match template");
3131               error ("%q+D declared here", tmpl);
3132             }
3133           return error_mark_node;
3134         }
3135
3136       if (complain & tf_error)
3137         perform_or_defer_access_check (TYPE_BINFO (context), tmpl, tmpl);
3138
3139       return tmpl;
3140     }
3141
3142   /* Build the UNBOUND_CLASS_TEMPLATE.  */
3143   t = cxx_make_type (UNBOUND_CLASS_TEMPLATE);
3144   TYPE_CONTEXT (t) = FROB_CONTEXT (context);
3145   TREE_TYPE (t) = NULL_TREE;
3146   SET_TYPE_STRUCTURAL_EQUALITY (t);
3147
3148   /* Build the corresponding TEMPLATE_DECL.  */
3149   d = build_decl (input_location, TEMPLATE_DECL, name, t);
3150   TYPE_NAME (TREE_TYPE (d)) = d;
3151   TYPE_STUB_DECL (TREE_TYPE (d)) = d;
3152   DECL_CONTEXT (d) = FROB_CONTEXT (context);
3153   DECL_ARTIFICIAL (d) = 1;
3154   DECL_TEMPLATE_PARMS (d) = parm_list;
3155
3156   return t;
3157 }
3158
3159 \f
3160
3161 /* Push the declarations of builtin types into the namespace.
3162    RID_INDEX is the index of the builtin type in the array
3163    RID_POINTERS.  NAME is the name used when looking up the builtin
3164    type.  TYPE is the _TYPE node for the builtin type.  */
3165
3166 void
3167 record_builtin_type (enum rid rid_index,
3168                      const char* name,
3169                      tree type)
3170 {
3171   tree rname = NULL_TREE, tname = NULL_TREE;
3172   tree tdecl = NULL_TREE;
3173
3174   if ((int) rid_index < (int) RID_MAX)
3175     rname = ridpointers[(int) rid_index];
3176   if (name)
3177     tname = get_identifier (name);
3178
3179   /* The calls to SET_IDENTIFIER_GLOBAL_VALUE below should be
3180      eliminated.  Built-in types should not be looked up name; their
3181      names are keywords that the parser can recognize.  However, there
3182      is code in c-common.c that uses identifier_global_value to look
3183      up built-in types by name.  */
3184   if (tname)
3185     {
3186       tdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, tname, type);
3187       DECL_ARTIFICIAL (tdecl) = 1;
3188       SET_IDENTIFIER_GLOBAL_VALUE (tname, tdecl);
3189     }
3190   if (rname)
3191     {
3192       if (!tdecl)
3193         {
3194           tdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, rname, type);
3195           DECL_ARTIFICIAL (tdecl) = 1;
3196         }
3197       SET_IDENTIFIER_GLOBAL_VALUE (rname, tdecl);
3198     }
3199
3200   if (!TYPE_NAME (type))
3201     TYPE_NAME (type) = tdecl;
3202
3203   if (tdecl)
3204     debug_hooks->type_decl (tdecl, 0);
3205 }
3206
3207 /* Record one of the standard Java types.
3208  * Declare it as having the given NAME.
3209  * If SIZE > 0, it is the size of one of the integral types;
3210  * otherwise it is the negative of the size of one of the other types.  */
3211
3212 static tree
3213 record_builtin_java_type (const char* name, int size)
3214 {
3215   tree type, decl;
3216   if (size > 0)
3217     type = build_nonstandard_integer_type (size, 0);
3218   else if (size > -32)
3219     {
3220       tree stype;
3221       /* "__java_char" or ""__java_boolean".  */
3222       type = build_nonstandard_integer_type (-size, 1);
3223       /* Get the signed type cached and attached to the unsigned type,
3224          so it doesn't get garbage-collected at "random" times,
3225          causing potential codegen differences out of different UIDs
3226          and different alias set numbers.  */
3227       stype = build_nonstandard_integer_type (-size, 0);
3228       TREE_CHAIN (type) = stype;
3229       /*if (size == -1) TREE_SET_CODE (type, BOOLEAN_TYPE);*/
3230     }
3231   else
3232     { /* "__java_float" or ""__java_double".  */
3233       type = make_node (REAL_TYPE);
3234       TYPE_PRECISION (type) = - size;
3235       layout_type (type);
3236     }
3237   record_builtin_type (RID_MAX, name, type);
3238   decl = TYPE_NAME (type);
3239
3240   /* Suppress generate debug symbol entries for these types,
3241      since for normal C++ they are just clutter.
3242      However, push_lang_context undoes this if extern "Java" is seen.  */
3243   DECL_IGNORED_P (decl) = 1;
3244
3245   TYPE_FOR_JAVA (type) = 1;
3246   return type;
3247 }
3248
3249 /* Push a type into the namespace so that the back ends ignore it.  */
3250
3251 static void
3252 record_unknown_type (tree type, const char* name)
3253 {
3254   tree decl = pushdecl (build_decl (UNKNOWN_LOCATION,
3255                                     TYPE_DECL, get_identifier (name), type));
3256   /* Make sure the "unknown type" typedecl gets ignored for debug info.  */
3257   DECL_IGNORED_P (decl) = 1;
3258   TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
3259   TYPE_SIZE (type) = TYPE_SIZE (void_type_node);
3260   TYPE_ALIGN (type) = 1;
3261   TYPE_USER_ALIGN (type) = 0;
3262   SET_TYPE_MODE (type, TYPE_MODE (void_type_node));
3263 }
3264
3265 /* A string for which we should create an IDENTIFIER_NODE at
3266    startup.  */
3267
3268 typedef struct predefined_identifier
3269 {
3270   /* The name of the identifier.  */
3271   const char *const name;
3272   /* The place where the IDENTIFIER_NODE should be stored.  */
3273   tree *const node;
3274   /* Nonzero if this is the name of a constructor or destructor.  */
3275   const int ctor_or_dtor_p;
3276 } predefined_identifier;
3277
3278 /* Create all the predefined identifiers.  */
3279
3280 static void
3281 initialize_predefined_identifiers (void)
3282 {
3283   const predefined_identifier *pid;
3284
3285   /* A table of identifiers to create at startup.  */
3286   static const predefined_identifier predefined_identifiers[] = {
3287     { "C++", &lang_name_cplusplus, 0 },
3288     { "C", &lang_name_c, 0 },
3289     { "Java", &lang_name_java, 0 },
3290     /* Some of these names have a trailing space so that it is
3291        impossible for them to conflict with names written by users.  */
3292     { "__ct ", &ctor_identifier, 1 },
3293     { "__base_ctor ", &base_ctor_identifier, 1 },
3294     { "__comp_ctor ", &complete_ctor_identifier, 1 },
3295     { "__dt ", &dtor_identifier, 1 },
3296     { "__comp_dtor ", &complete_dtor_identifier, 1 },
3297     { "__base_dtor ", &base_dtor_identifier, 1 },
3298     { "__deleting_dtor ", &deleting_dtor_identifier, 1 },
3299     { IN_CHARGE_NAME, &in_charge_identifier, 0 },
3300     { "nelts", &nelts_identifier, 0 },
3301     { THIS_NAME, &this_identifier, 0 },
3302     { VTABLE_DELTA_NAME, &delta_identifier, 0 },
3303     { VTABLE_PFN_NAME, &pfn_identifier, 0 },
3304     { "_vptr", &vptr_identifier, 0 },
3305     { "__vtt_parm", &vtt_parm_identifier, 0 },
3306     { "::", &global_scope_name, 0 },
3307     { "std", &std_identifier, 0 },
3308     { NULL, NULL, 0 }
3309   };
3310
3311   for (pid = predefined_identifiers; pid->name; ++pid)
3312     {
3313       *pid->node = get_identifier (pid->name);
3314       if (pid->ctor_or_dtor_p)
3315         IDENTIFIER_CTOR_OR_DTOR_P (*pid->node) = 1;
3316     }
3317 }
3318
3319 /* Create the predefined scalar types of C,
3320    and some nodes representing standard constants (0, 1, (void *)0).
3321    Initialize the global binding level.
3322    Make definitions for built-in primitive functions.  */
3323
3324 void
3325 cxx_init_decl_processing (void)
3326 {
3327   tree void_ftype;
3328   tree void_ftype_ptr;
3329
3330   build_common_tree_nodes (flag_signed_char, false);
3331
3332   /* Create all the identifiers we need.  */
3333   initialize_predefined_identifiers ();
3334
3335   /* Create the global variables.  */
3336   push_to_top_level ();
3337
3338   current_function_decl = NULL_TREE;
3339   current_binding_level = NULL;
3340   /* Enter the global namespace.  */
3341   gcc_assert (global_namespace == NULL_TREE);
3342   global_namespace = build_lang_decl (NAMESPACE_DECL, global_scope_name,
3343                                       void_type_node);
3344   TREE_PUBLIC (global_namespace) = 1;
3345   begin_scope (sk_namespace, global_namespace);
3346
3347   current_lang_name = NULL_TREE;
3348
3349   if (flag_visibility_ms_compat)
3350     default_visibility = VISIBILITY_HIDDEN;
3351
3352   /* Initially, C.  */
3353   current_lang_name = lang_name_c;
3354
3355   /* Create the `std' namespace.  */
3356   push_namespace (std_identifier);
3357   std_node = current_namespace;
3358   pop_namespace ();
3359
3360   c_common_nodes_and_builtins ();
3361
3362   java_byte_type_node = record_builtin_java_type ("__java_byte", 8);
3363   java_short_type_node = record_builtin_java_type ("__java_short", 16);
3364   java_int_type_node = record_builtin_java_type ("__java_int", 32);
3365   java_long_type_node = record_builtin_java_type ("__java_long", 64);
3366   java_float_type_node = record_builtin_java_type ("__java_float", -32);
3367   java_double_type_node = record_builtin_java_type ("__java_double", -64);
3368   java_char_type_node = record_builtin_java_type ("__java_char", -16);
3369   java_boolean_type_node = record_builtin_java_type ("__java_boolean", -1);
3370
3371   integer_two_node = build_int_cst (NULL_TREE, 2);
3372   integer_three_node = build_int_cst (NULL_TREE, 3);
3373
3374   record_builtin_type (RID_BOOL, "bool", boolean_type_node);
3375   truthvalue_type_node = boolean_type_node;
3376   truthvalue_false_node = boolean_false_node;
3377   truthvalue_true_node = boolean_true_node;
3378
3379   empty_except_spec = build_tree_list (NULL_TREE, NULL_TREE);
3380
3381 #if 0
3382   record_builtin_type (RID_MAX, NULL, string_type_node);
3383 #endif
3384
3385   delta_type_node = ptrdiff_type_node;
3386   vtable_index_type = ptrdiff_type_node;
3387
3388   vtt_parm_type = build_pointer_type (const_ptr_type_node);
3389   void_ftype = build_function_type (void_type_node, void_list_node);
3390   void_ftype_ptr = build_function_type (void_type_node,
3391                                         tree_cons (NULL_TREE,
3392                                                    ptr_type_node,
3393                                                    void_list_node));
3394   void_ftype_ptr
3395     = build_exception_variant (void_ftype_ptr, empty_except_spec);
3396
3397   /* C++ extensions */
3398
3399   unknown_type_node = make_node (UNKNOWN_TYPE);
3400   record_unknown_type (unknown_type_node, "unknown type");
3401
3402   /* Indirecting an UNKNOWN_TYPE node yields an UNKNOWN_TYPE node.  */
3403   TREE_TYPE (unknown_type_node) = unknown_type_node;
3404
3405   /* Looking up TYPE_POINTER_TO and TYPE_REFERENCE_TO yield the same
3406      result.  */
3407   TYPE_POINTER_TO (unknown_type_node) = unknown_type_node;
3408   TYPE_REFERENCE_TO (unknown_type_node) = unknown_type_node;
3409
3410   init_list_type_node = make_node (UNKNOWN_TYPE);
3411   record_unknown_type (init_list_type_node, "init list");
3412
3413   {
3414     /* Make sure we get a unique function type, so we can give
3415        its pointer type a name.  (This wins for gdb.) */
3416     tree vfunc_type = make_node (FUNCTION_TYPE);
3417     TREE_TYPE (vfunc_type) = integer_type_node;
3418     TYPE_ARG_TYPES (vfunc_type) = NULL_TREE;
3419     layout_type (vfunc_type);
3420
3421     vtable_entry_type = build_pointer_type (vfunc_type);
3422   }
3423   record_builtin_type (RID_MAX, VTBL_PTR_TYPE, vtable_entry_type);
3424
3425   vtbl_type_node
3426     = build_cplus_array_type (vtable_entry_type, NULL_TREE);
3427   layout_type (vtbl_type_node);
3428   vtbl_type_node = build_qualified_type (vtbl_type_node, TYPE_QUAL_CONST);
3429   record_builtin_type (RID_MAX, NULL, vtbl_type_node);
3430   vtbl_ptr_type_node = build_pointer_type (vtable_entry_type);
3431   layout_type (vtbl_ptr_type_node);
3432   record_builtin_type (RID_MAX, NULL, vtbl_ptr_type_node);
3433
3434   push_namespace (get_identifier ("__cxxabiv1"));
3435   abi_node = current_namespace;
3436   pop_namespace ();
3437
3438   global_type_node = make_node (LANG_TYPE);
3439   record_unknown_type (global_type_node, "global type");
3440
3441   /* Now, C++.  */
3442   current_lang_name = lang_name_cplusplus;
3443
3444   {
3445     tree bad_alloc_id;
3446     tree bad_alloc_type_node;
3447     tree bad_alloc_decl;
3448     tree newtype, deltype;
3449     tree ptr_ftype_sizetype;
3450
3451     push_namespace (std_identifier);
3452     bad_alloc_id = get_identifier ("bad_alloc");
3453     bad_alloc_type_node = make_class_type (RECORD_TYPE);
3454     TYPE_CONTEXT (bad_alloc_type_node) = current_namespace;
3455     bad_alloc_decl
3456       = create_implicit_typedef (bad_alloc_id, bad_alloc_type_node);
3457     DECL_CONTEXT (bad_alloc_decl) = current_namespace;
3458     TYPE_STUB_DECL (bad_alloc_type_node) = bad_alloc_decl;
3459     pop_namespace ();
3460
3461     ptr_ftype_sizetype
3462       = build_function_type (ptr_type_node,
3463                              tree_cons (NULL_TREE,
3464                                         size_type_node,
3465                                         void_list_node));
3466     newtype = build_exception_variant
3467       (ptr_ftype_sizetype, add_exception_specifier
3468        (NULL_TREE, bad_alloc_type_node, -1));
3469     deltype = build_exception_variant (void_ftype_ptr, empty_except_spec);
3470     push_cp_library_fn (NEW_EXPR, newtype);
3471     push_cp_library_fn (VEC_NEW_EXPR, newtype);
3472     global_delete_fndecl = push_cp_library_fn (DELETE_EXPR, deltype);
3473     push_cp_library_fn (VEC_DELETE_EXPR, deltype);
3474   }
3475
3476   abort_fndecl
3477     = build_library_fn_ptr ("__cxa_pure_virtual", void_ftype);
3478
3479   /* Perform other language dependent initializations.  */
3480   init_class_processing ();
3481   init_rtti_processing ();
3482   init_template_processing ();
3483
3484   if (flag_exceptions)
3485     init_exception_processing ();
3486
3487   if (! supports_one_only ())
3488     flag_weak = 0;
3489
3490   make_fname_decl = cp_make_fname_decl;
3491   start_fname_decls ();
3492
3493   /* Show we use EH for cleanups.  */
3494   if (flag_exceptions)
3495     using_eh_for_cleanups ();
3496 }
3497
3498 /* Generate an initializer for a function naming variable from
3499    NAME. NAME may be NULL, to indicate a dependent name.  TYPE_P is
3500    filled in with the type of the init.  */
3501
3502 tree
3503 cp_fname_init (const char* name, tree *type_p)
3504 {
3505   tree domain = NULL_TREE;
3506   tree type;
3507   tree init = NULL_TREE;
3508   size_t length = 0;
3509
3510   if (name)
3511     {
3512       length = strlen (name);
3513       domain = build_index_type (size_int (length));
3514       init = build_string (length + 1, name);
3515     }
3516
3517   type = build_qualified_type (char_type_node, TYPE_QUAL_CONST);
3518   type = build_cplus_array_type (type, domain);
3519
3520   *type_p = type;
3521
3522   if (init)
3523     TREE_TYPE (init) = type;
3524   else
3525     init = error_mark_node;
3526
3527   return init;
3528 }
3529
3530 /* Create the VAR_DECL for __FUNCTION__ etc. ID is the name to give
3531    the decl, LOC is the location to give the decl, NAME is the
3532    initialization string and TYPE_DEP indicates whether NAME depended
3533    on the type of the function. We make use of that to detect
3534    __PRETTY_FUNCTION__ inside a template fn. This is being done lazily
3535    at the point of first use, so we mustn't push the decl now.  */
3536
3537 static tree
3538 cp_make_fname_decl (location_t loc, tree id, int type_dep)
3539 {
3540   const char *const name = (type_dep && processing_template_decl
3541                             ? NULL : fname_as_string (type_dep));
3542   tree type;
3543   tree init = cp_fname_init (name, &type);
3544   tree decl = build_decl (loc, VAR_DECL, id, type);
3545
3546   if (name)
3547     free (CONST_CAST (char *, name));
3548
3549   /* As we're using pushdecl_with_scope, we must set the context.  */
3550   DECL_CONTEXT (decl) = current_function_decl;
3551   DECL_PRETTY_FUNCTION_P (decl) = type_dep;
3552
3553   TREE_STATIC (decl) = 1;
3554   TREE_READONLY (decl) = 1;
3555   DECL_ARTIFICIAL (decl) = 1;
3556
3557   TREE_USED (decl) = 1;
3558
3559   if (current_function_decl)
3560     {
3561       struct cp_binding_level *b = current_binding_level;
3562       while (b->level_chain->kind != sk_function_parms)
3563         b = b->level_chain;
3564       pushdecl_with_scope (decl, b, /*is_friend=*/false);
3565       cp_finish_decl (decl, init, /*init_const_expr_p=*/false, NULL_TREE,
3566                       LOOKUP_ONLYCONVERTING);
3567     }
3568   else
3569     pushdecl_top_level_and_finish (decl, init);
3570
3571   return decl;
3572 }
3573
3574 static tree
3575 builtin_function_1 (tree decl, tree context, bool is_global)
3576 {
3577   tree          id = DECL_NAME (decl);
3578   const char *name = IDENTIFIER_POINTER (id);
3579
3580   retrofit_lang_decl (decl);
3581
3582   /* All nesting of C++ functions is lexical; there is never a "static
3583      chain" in the sense of GNU C nested functions.  */
3584   DECL_NO_STATIC_CHAIN (decl) = 1;
3585
3586   DECL_ARTIFICIAL (decl) = 1;
3587   SET_OVERLOADED_OPERATOR_CODE (decl, ERROR_MARK);
3588   SET_DECL_LANGUAGE (decl, lang_c);
3589   /* Runtime library routines are, by definition, available in an
3590      external shared object.  */
3591   DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
3592   DECL_VISIBILITY_SPECIFIED (decl) = 1;
3593
3594   DECL_CONTEXT (decl) = context;
3595
3596   if (is_global)
3597     pushdecl_top_level (decl);
3598   else
3599     pushdecl (decl);
3600
3601   /* A function in the user's namespace should have an explicit
3602      declaration before it is used.  Mark the built-in function as
3603      anticipated but not actually declared.  */
3604   if (name[0] != '_' || name[1] != '_')
3605     DECL_ANTICIPATED (decl) = 1;
3606   else if (strncmp (name + 2, "builtin_", strlen ("builtin_")) != 0)
3607     {
3608       size_t len = strlen (name);
3609
3610       /* Treat __*_chk fortification functions as anticipated as well,
3611          unless they are __builtin_*.  */
3612       if (len > strlen ("___chk")
3613           && memcmp (name + len - strlen ("_chk"),
3614                      "_chk", strlen ("_chk") + 1) == 0)
3615         DECL_ANTICIPATED (decl) = 1;
3616     }
3617
3618   return decl;
3619 }
3620
3621 tree
3622 cxx_builtin_function (tree decl)
3623 {
3624   tree          id = DECL_NAME (decl);
3625   const char *name = IDENTIFIER_POINTER (id);
3626   /* All builtins that don't begin with an '_' should additionally
3627      go in the 'std' namespace.  */
3628   if (name[0] != '_')
3629     {
3630       tree decl2 = copy_node(decl);
3631       push_namespace (std_identifier);
3632       builtin_function_1 (decl2, std_node, false);
3633       pop_namespace ();
3634     }
3635
3636   return builtin_function_1 (decl, NULL_TREE, false);
3637 }
3638
3639 /* Like cxx_builtin_function, but guarantee the function is added to the global
3640    scope.  This is to allow function specific options to add new machine
3641    dependent builtins when the target ISA changes via attribute((target(...)))
3642    which saves space on program startup if the program does not use non-generic
3643    ISAs.  */
3644
3645 tree
3646 cxx_builtin_function_ext_scope (tree decl)
3647 {
3648
3649   tree          id = DECL_NAME (decl);
3650   const char *name = IDENTIFIER_POINTER (id);
3651   /* All builtins that don't begin with an '_' should additionally
3652      go in the 'std' namespace.  */
3653   if (name[0] != '_')
3654     {
3655       tree decl2 = copy_node(decl);
3656       push_namespace (std_identifier);
3657       builtin_function_1 (decl2, std_node, true);
3658       pop_namespace ();
3659     }
3660
3661   return builtin_function_1 (decl, NULL_TREE, true);
3662 }
3663
3664 /* Generate a FUNCTION_DECL with the typical flags for a runtime library
3665    function.  Not called directly.  */
3666
3667 static tree
3668 build_library_fn_1 (tree name, enum tree_code operator_code, tree type)
3669 {
3670   tree fn = build_lang_decl (FUNCTION_DECL, name, type);
3671   DECL_EXTERNAL (fn) = 1;
3672   TREE_PUBLIC (fn) = 1;
3673   DECL_ARTIFICIAL (fn) = 1;
3674   SET_OVERLOADED_OPERATOR_CODE (fn, operator_code);
3675   SET_DECL_LANGUAGE (fn, lang_c);
3676   /* Runtime library routines are, by definition, available in an
3677      external shared object.  */
3678   DECL_VISIBILITY (fn) = VISIBILITY_DEFAULT;
3679   DECL_VISIBILITY_SPECIFIED (fn) = 1;
3680   return fn;
3681 }
3682
3683 /* Returns the _DECL for a library function with C linkage.
3684    We assume that such functions never throw; if this is incorrect,
3685    callers should unset TREE_NOTHROW.  */
3686
3687 static tree
3688 build_library_fn (tree name, tree type)
3689 {
3690   tree fn = build_library_fn_1 (name, ERROR_MARK, type);
3691   TREE_NOTHROW (fn) = 1;
3692   return fn;
3693 }
3694
3695 /* Returns the _DECL for a library function with C++ linkage.  */
3696
3697 static tree
3698 build_cp_library_fn (tree name, enum tree_code operator_code, tree type)
3699 {
3700   tree fn = build_library_fn_1 (name, operator_code, type);
3701   TREE_NOTHROW (fn) = TYPE_NOTHROW_P (type);
3702   DECL_CONTEXT (fn) = FROB_CONTEXT (current_namespace);
3703   SET_DECL_LANGUAGE (fn, lang_cplusplus);
3704   return fn;
3705 }
3706
3707 /* Like build_library_fn, but takes a C string instead of an
3708    IDENTIFIER_NODE.  */
3709
3710 tree
3711 build_library_fn_ptr (const char* name, tree type)
3712 {
3713   return build_library_fn (get_identifier (name), type);
3714 }
3715
3716 /* Like build_cp_library_fn, but takes a C string instead of an
3717    IDENTIFIER_NODE.  */
3718
3719 tree
3720 build_cp_library_fn_ptr (const char* name, tree type)
3721 {
3722   return build_cp_library_fn (get_identifier (name), ERROR_MARK, type);
3723 }
3724
3725 /* Like build_library_fn, but also pushes the function so that we will
3726    be able to find it via IDENTIFIER_GLOBAL_VALUE.  Also, the function
3727    may throw exceptions listed in RAISES.  */
3728
3729 tree
3730 push_library_fn (tree name, tree type, tree raises)
3731 {
3732   tree fn;
3733
3734   if (raises)
3735     type = build_exception_variant (type, raises);
3736
3737   fn = build_library_fn (name, type);
3738   pushdecl_top_level (fn);
3739   return fn;
3740 }
3741
3742 /* Like build_cp_library_fn, but also pushes the function so that it
3743    will be found by normal lookup.  */
3744
3745 static tree
3746 push_cp_library_fn (enum tree_code operator_code, tree type)
3747 {
3748   tree fn = build_cp_library_fn (ansi_opname (operator_code),
3749                                  operator_code,
3750                                  type);
3751   pushdecl (fn);
3752   return fn;
3753 }
3754
3755 /* Like push_library_fn, but takes a TREE_LIST of parm types rather than
3756    a FUNCTION_TYPE.  */
3757
3758 tree
3759 push_void_library_fn (tree name, tree parmtypes)
3760 {
3761   tree type = build_function_type (void_type_node, parmtypes);
3762   return push_library_fn (name, type, NULL_TREE);
3763 }
3764
3765 /* Like push_library_fn, but also note that this function throws
3766    and does not return.  Used for __throw_foo and the like.  */
3767
3768 tree
3769 push_throw_library_fn (tree name, tree type)
3770 {
3771   tree fn = push_library_fn (name, type, NULL_TREE);
3772   TREE_THIS_VOLATILE (fn) = 1;
3773   TREE_NOTHROW (fn) = 0;
3774   return fn;
3775 }
3776 \f
3777 /* When we call finish_struct for an anonymous union, we create
3778    default copy constructors and such.  But, an anonymous union
3779    shouldn't have such things; this function undoes the damage to the
3780    anonymous union type T.
3781
3782    (The reason that we create the synthesized methods is that we don't
3783    distinguish `union { int i; }' from `typedef union { int i; } U'.
3784    The first is an anonymous union; the second is just an ordinary
3785    union type.)  */
3786
3787 void
3788 fixup_anonymous_aggr (tree t)
3789 {
3790   tree *q;
3791
3792   /* Wipe out memory of synthesized methods.  */
3793   TYPE_HAS_USER_CONSTRUCTOR (t) = 0;
3794   TYPE_HAS_DEFAULT_CONSTRUCTOR (t) = 0;
3795   TYPE_HAS_INIT_REF (t) = 0;
3796   TYPE_HAS_CONST_INIT_REF (t) = 0;
3797   TYPE_HAS_ASSIGN_REF (t) = 0;
3798   TYPE_HAS_CONST_ASSIGN_REF (t) = 0;
3799
3800   /* Splice the implicitly generated functions out of the TYPE_METHODS
3801      list.  */
3802   q = &TYPE_METHODS (t);
3803   while (*q)
3804     {
3805       if (DECL_ARTIFICIAL (*q))
3806         *q = TREE_CHAIN (*q);
3807       else
3808         q = &TREE_CHAIN (*q);
3809     }
3810
3811   /* ISO C++ 9.5.3.  Anonymous unions may not have function members.  */
3812   if (TYPE_METHODS (t))
3813     {
3814       tree decl = TYPE_MAIN_DECL (t);
3815
3816       if (TREE_CODE (t) != UNION_TYPE)
3817         error_at (DECL_SOURCE_LOCATION (decl), 
3818                   "an anonymous struct cannot have function members");
3819       else
3820         error_at (DECL_SOURCE_LOCATION (decl),
3821                   "an anonymous union cannot have function members");
3822     }
3823
3824   /* Anonymous aggregates cannot have fields with ctors, dtors or complex
3825      assignment operators (because they cannot have these methods themselves).
3826      For anonymous unions this is already checked because they are not allowed
3827      in any union, otherwise we have to check it.  */
3828   if (TREE_CODE (t) != UNION_TYPE)
3829     {
3830       tree field, type;
3831
3832       for (field = TYPE_FIELDS (t); field; field = TREE_CHAIN (field))
3833         if (TREE_CODE (field) == FIELD_DECL)
3834           {
3835             type = TREE_TYPE (field);
3836             if (CLASS_TYPE_P (type))
3837               {
3838                 if (TYPE_NEEDS_CONSTRUCTING (type))
3839                   error ("member %q+#D with constructor not allowed "
3840                          "in anonymous aggregate", field);
3841                 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
3842                   error ("member %q+#D with destructor not allowed "
3843                          "in anonymous aggregate", field);
3844                 if (TYPE_HAS_COMPLEX_ASSIGN_REF (type))
3845                   error ("member %q+#D with copy assignment operator "
3846                          "not allowed in anonymous aggregate", field);
3847               }
3848           }
3849     }
3850 }
3851
3852 /* Make sure that a declaration with no declarator is well-formed, i.e.
3853    just declares a tagged type or anonymous union.
3854
3855    Returns the type declared; or NULL_TREE if none.  */
3856
3857 tree
3858 check_tag_decl (cp_decl_specifier_seq *declspecs)
3859 {
3860   int saw_friend = declspecs->specs[(int)ds_friend] != 0;
3861   int saw_typedef = declspecs->specs[(int)ds_typedef] != 0;
3862   /* If a class, struct, or enum type is declared by the DECLSPECS
3863      (i.e, if a class-specifier, enum-specifier, or non-typename
3864      elaborated-type-specifier appears in the DECLSPECS),
3865      DECLARED_TYPE is set to the corresponding type.  */
3866   tree declared_type = NULL_TREE;
3867   bool error_p = false;
3868
3869   if (declspecs->multiple_types_p)
3870     error ("multiple types in one declaration");
3871   else if (declspecs->redefined_builtin_type)
3872     {
3873       if (!in_system_header)
3874         permerror (input_location, "redeclaration of C++ built-in type %qT",
3875                    declspecs->redefined_builtin_type);
3876       return NULL_TREE;
3877     }
3878
3879   if (declspecs->type
3880       && TYPE_P (declspecs->type)
3881       && ((TREE_CODE (declspecs->type) != TYPENAME_TYPE
3882            && MAYBE_CLASS_TYPE_P (declspecs->type))
3883           || TREE_CODE (declspecs->type) == ENUMERAL_TYPE))
3884     declared_type = declspecs->type;
3885   else if (declspecs->type == error_mark_node)
3886     error_p = true;
3887   if (declared_type == NULL_TREE && ! saw_friend && !error_p)
3888     permerror (input_location, "declaration does not declare anything");
3889   /* Check for an anonymous union.  */
3890   else if (declared_type && RECORD_OR_UNION_CODE_P (TREE_CODE (declared_type))
3891            && TYPE_ANONYMOUS_P (declared_type))
3892     {
3893       /* 7/3 In a simple-declaration, the optional init-declarator-list
3894          can be omitted only when declaring a class (clause 9) or
3895          enumeration (7.2), that is, when the decl-specifier-seq contains
3896          either a class-specifier, an elaborated-type-specifier with
3897          a class-key (9.1), or an enum-specifier.  In these cases and
3898          whenever a class-specifier or enum-specifier is present in the
3899          decl-specifier-seq, the identifiers in these specifiers are among
3900          the names being declared by the declaration (as class-name,
3901          enum-names, or enumerators, depending on the syntax).  In such
3902          cases, and except for the declaration of an unnamed bit-field (9.6),
3903          the decl-specifier-seq shall introduce one or more names into the
3904          program, or shall redeclare a name introduced by a previous
3905          declaration.  [Example:
3906              enum { };                  // ill-formed
3907              typedef class { };         // ill-formed
3908          --end example]  */
3909       if (saw_typedef)
3910         {
3911           error ("missing type-name in typedef-declaration");
3912           return NULL_TREE;
3913         }
3914       /* Anonymous unions are objects, so they can have specifiers.  */;
3915       SET_ANON_AGGR_TYPE_P (declared_type);
3916
3917       if (TREE_CODE (declared_type) != UNION_TYPE && !in_system_header)
3918         pedwarn (input_location, OPT_pedantic, "ISO C++ prohibits anonymous structs");
3919     }
3920
3921   else
3922     {
3923       if (declspecs->specs[(int)ds_inline]
3924           || declspecs->specs[(int)ds_virtual])
3925         error ("%qs can only be specified for functions",
3926                declspecs->specs[(int)ds_inline]
3927                ? "inline" : "virtual");
3928       else if (saw_friend
3929                && (!current_class_type
3930                    || current_scope () != current_class_type))
3931         error ("%<friend%> can only be specified inside a class");
3932       else if (declspecs->specs[(int)ds_explicit])
3933         error ("%<explicit%> can only be specified for constructors");
3934       else if (declspecs->storage_class)
3935         error ("a storage class can only be specified for objects "
3936                "and functions");
3937       else if (declspecs->specs[(int)ds_const]
3938                || declspecs->specs[(int)ds_volatile]
3939                || declspecs->specs[(int)ds_restrict]
3940                || declspecs->specs[(int)ds_thread])
3941         error ("qualifiers can only be specified for objects "
3942                "and functions");
3943       else if (saw_typedef)
3944         warning (0, "%<typedef%> was ignored in this declaration");
3945     }
3946
3947   return declared_type;
3948 }
3949
3950 /* Called when a declaration is seen that contains no names to declare.
3951    If its type is a reference to a structure, union or enum inherited
3952    from a containing scope, shadow that tag name for the current scope
3953    with a forward reference.
3954    If its type defines a new named structure or union
3955    or defines an enum, it is valid but we need not do anything here.
3956    Otherwise, it is an error.
3957
3958    C++: may have to grok the declspecs to learn about static,
3959    complain for anonymous unions.
3960
3961    Returns the TYPE declared -- or NULL_TREE if none.  */
3962
3963 tree
3964 shadow_tag (cp_decl_specifier_seq *declspecs)
3965 {
3966   tree t = check_tag_decl (declspecs);
3967
3968   if (!t)
3969     return NULL_TREE;
3970
3971   if (declspecs->attributes)
3972     {
3973       warning (0, "attribute ignored in declaration of %q+#T", t);
3974       warning (0, "attribute for %q+#T must follow the %qs keyword",
3975                t, class_key_or_enum_as_string (t));
3976
3977     }
3978
3979   if (maybe_process_partial_specialization (t) == error_mark_node)
3980     return NULL_TREE;
3981
3982   /* This is where the variables in an anonymous union are
3983      declared.  An anonymous union declaration looks like:
3984      union { ... } ;
3985      because there is no declarator after the union, the parser
3986      sends that declaration here.  */
3987   if (ANON_AGGR_TYPE_P (t))
3988     {
3989       fixup_anonymous_aggr (t);
3990
3991       if (TYPE_FIELDS (t))
3992         {
3993           tree decl = grokdeclarator (/*declarator=*/NULL,
3994                                       declspecs, NORMAL, 0, NULL);
3995           finish_anon_union (decl);
3996         }
3997     }
3998
3999   return t;
4000 }
4001 \f
4002 /* Decode a "typename", such as "int **", returning a ..._TYPE node.  */
4003
4004 tree
4005 groktypename (cp_decl_specifier_seq *type_specifiers,
4006               const cp_declarator *declarator,
4007               bool is_template_arg)
4008 {
4009   tree attrs;
4010   tree type;
4011   enum decl_context context
4012     = is_template_arg ? TEMPLATE_TYPE_ARG : TYPENAME;
4013   attrs = type_specifiers->attributes;
4014   type_specifiers->attributes = NULL_TREE;
4015   type = grokdeclarator (declarator, type_specifiers, context, 0, &attrs);
4016   if (attrs && type != error_mark_node)
4017     {
4018       if (CLASS_TYPE_P (type))
4019         warning (OPT_Wattributes, "ignoring attributes applied to class type %qT "
4020                  "outside of definition", type);
4021       else if (MAYBE_CLASS_TYPE_P (type))
4022         /* A template type parameter or other dependent type.  */
4023         warning (OPT_Wattributes, "ignoring attributes applied to dependent "
4024                  "type %qT without an associated declaration", type);
4025       else
4026         cplus_decl_attributes (&type, attrs, 0);
4027     }
4028   return type;
4029 }
4030
4031 /* Process a DECLARATOR for a function-scope variable declaration,
4032    namespace-scope variable declaration, or function declaration.
4033    (Function definitions go through start_function; class member
4034    declarations appearing in the body of the class go through
4035    grokfield.)  The DECL corresponding to the DECLARATOR is returned.
4036    If an error occurs, the error_mark_node is returned instead.
4037    
4038    DECLSPECS are the decl-specifiers for the declaration.  INITIALIZED is
4039    SD_INITIALIZED if an explicit initializer is present, or SD_DEFAULTED
4040    for an explicitly defaulted function, or SD_DELETED for an explicitly
4041    deleted function, but 0 (SD_UNINITIALIZED) if this is a variable
4042    implicitly initialized via a default constructor.  ATTRIBUTES and
4043    PREFIX_ATTRIBUTES are GNU attributes associated with this declaration.
4044    *PUSHED_SCOPE_P is set to the scope entered in this function, if any; if
4045    set, the caller is responsible for calling pop_scope.  */
4046
4047 tree
4048 start_decl (const cp_declarator *declarator,
4049             cp_decl_specifier_seq *declspecs,
4050             int initialized,
4051             tree attributes,
4052             tree prefix_attributes,
4053             tree *pushed_scope_p)
4054 {
4055   tree decl;
4056   tree type;
4057   tree context;
4058   bool was_public;
4059   int flags;
4060
4061   *pushed_scope_p = NULL_TREE;
4062
4063   /* An object declared as __attribute__((deprecated)) suppresses
4064      warnings of uses of other deprecated items.  */
4065   if (lookup_attribute ("deprecated", attributes))
4066     deprecated_state = DEPRECATED_SUPPRESS;
4067
4068   attributes = chainon (attributes, prefix_attributes);
4069
4070   decl = grokdeclarator (declarator, declspecs, NORMAL, initialized,
4071                          &attributes);
4072
4073   deprecated_state = DEPRECATED_NORMAL;
4074
4075   if (decl == NULL_TREE || TREE_CODE (decl) == VOID_TYPE
4076       || decl == error_mark_node)
4077     return error_mark_node;
4078
4079   type = TREE_TYPE (decl);
4080
4081   context = DECL_CONTEXT (decl);
4082
4083   if (context)
4084     {
4085       *pushed_scope_p = push_scope (context);
4086
4087       /* We are only interested in class contexts, later.  */
4088       if (TREE_CODE (context) == NAMESPACE_DECL)
4089         context = NULL_TREE;
4090     }
4091
4092   if (initialized)
4093     /* Is it valid for this decl to have an initializer at all?
4094        If not, set INITIALIZED to zero, which will indirectly
4095        tell `cp_finish_decl' to ignore the initializer once it is parsed.  */
4096     switch (TREE_CODE (decl))
4097       {
4098       case TYPE_DECL:
4099         error ("typedef %qD is initialized (use decltype instead)", decl);
4100         return error_mark_node;
4101
4102       case FUNCTION_DECL:
4103         if (initialized == SD_DELETED)
4104           /* We'll handle the rest of the semantics later, but we need to
4105              set this now so it's visible to duplicate_decls.  */
4106           DECL_DELETED_FN (decl) = 1;
4107         break;
4108
4109       default:
4110         break;
4111       }
4112
4113   if (initialized)
4114     {
4115       if (! toplevel_bindings_p ()
4116           && DECL_EXTERNAL (decl))
4117         warning (0, "declaration of %q#D has %<extern%> and is initialized",
4118                  decl);
4119       DECL_EXTERNAL (decl) = 0;
4120       if (toplevel_bindings_p ())
4121         TREE_STATIC (decl) = 1;
4122     }
4123
4124   /* If this is a typedef that names the class for linkage purposes
4125      (7.1.3p8), apply any attributes directly to the type.  */
4126   if (TREE_CODE (decl) == TYPE_DECL
4127       && TAGGED_TYPE_P (TREE_TYPE (decl))
4128       && decl == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (decl))))
4129     flags = ATTR_FLAG_TYPE_IN_PLACE;
4130   else
4131     flags = 0;
4132
4133   /* Set attributes here so if duplicate decl, will have proper attributes.  */
4134   cplus_decl_attributes (&decl, attributes, flags);
4135
4136   /* Dllimported symbols cannot be defined.  Static data members (which
4137      can be initialized in-class and dllimported) go through grokfield,
4138      not here, so we don't need to exclude those decls when checking for
4139      a definition.  */
4140   if (initialized && DECL_DLLIMPORT_P (decl))
4141     {
4142       error ("definition of %q#D is marked %<dllimport%>", decl);
4143       DECL_DLLIMPORT_P (decl) = 0;
4144     }
4145
4146   /* If #pragma weak was used, mark the decl weak now.  */
4147   maybe_apply_pragma_weak (decl);
4148
4149   if (TREE_CODE (decl) == FUNCTION_DECL
4150       && DECL_DECLARED_INLINE_P (decl)
4151       && DECL_UNINLINABLE (decl)
4152       && lookup_attribute ("noinline", DECL_ATTRIBUTES (decl)))
4153     warning (0, "inline function %q+D given attribute noinline", decl);
4154
4155   if (context && COMPLETE_TYPE_P (complete_type (context)))
4156     {
4157       if (TREE_CODE (decl) == VAR_DECL)
4158         {
4159           tree field = lookup_field (context, DECL_NAME (decl), 0, false);
4160           if (field == NULL_TREE || TREE_CODE (field) != VAR_DECL)
4161             error ("%q#D is not a static member of %q#T", decl, context);
4162           else
4163             {
4164               if (DECL_CONTEXT (field) != context)
4165                 {
4166                   if (!same_type_p (DECL_CONTEXT (field), context))
4167                     permerror (input_location, "ISO C++ does not permit %<%T::%D%> "
4168                                "to be defined as %<%T::%D%>",
4169                                DECL_CONTEXT (field), DECL_NAME (decl),
4170                                context, DECL_NAME (decl));
4171                   DECL_CONTEXT (decl) = DECL_CONTEXT (field);
4172                 }
4173               if (processing_specialization
4174                   && template_class_depth (context) == 0
4175                   && CLASSTYPE_TEMPLATE_SPECIALIZATION (context))
4176                 error ("template header not allowed in member definition "
4177                        "of explicitly specialized class");
4178               /* Static data member are tricky; an in-class initialization
4179                  still doesn't provide a definition, so the in-class
4180                  declaration will have DECL_EXTERNAL set, but will have an
4181                  initialization.  Thus, duplicate_decls won't warn
4182                  about this situation, and so we check here.  */
4183               if (initialized && DECL_INITIALIZED_IN_CLASS_P (field))
4184                 error ("duplicate initialization of %qD", decl);
4185               if (duplicate_decls (decl, field, /*newdecl_is_friend=*/false))
4186                 decl = field;
4187             }
4188         }
4189       else
4190         {
4191           tree field = check_classfn (context, decl,
4192                                       (processing_template_decl
4193                                        > template_class_depth (context))
4194                                       ? current_template_parms
4195                                       : NULL_TREE);
4196           if (field && field != error_mark_node
4197               && duplicate_decls (decl, field,
4198                                  /*newdecl_is_friend=*/false))
4199             decl = field;
4200         }
4201
4202       /* cp_finish_decl sets DECL_EXTERNAL if DECL_IN_AGGR_P is set.  */
4203       DECL_IN_AGGR_P (decl) = 0;
4204       /* Do not mark DECL as an explicit specialization if it was not
4205          already marked as an instantiation; a declaration should
4206          never be marked as a specialization unless we know what
4207          template is being specialized.  */
4208       if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
4209         {
4210           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
4211
4212           /* [temp.expl.spec] An explicit specialization of a static data
4213              member of a template is a definition if the declaration
4214              includes an initializer; otherwise, it is a declaration.
4215
4216              We check for processing_specialization so this only applies
4217              to the new specialization syntax.  */
4218           if (!initialized && processing_specialization)
4219             DECL_EXTERNAL (decl) = 1;
4220         }
4221
4222       if (DECL_EXTERNAL (decl) && ! DECL_TEMPLATE_SPECIALIZATION (decl))
4223         permerror (input_location, "declaration of %q#D outside of class is not definition",
4224                    decl);
4225     }
4226
4227   was_public = TREE_PUBLIC (decl);
4228
4229   /* Enter this declaration into the symbol table.  */
4230   decl = maybe_push_decl (decl);
4231
4232   if (processing_template_decl)
4233     decl = push_template_decl (decl);
4234   if (decl == error_mark_node)
4235     return error_mark_node;
4236
4237   /* Tell the back end to use or not use .common as appropriate.  If we say
4238      -fconserve-space, we want this to save .data space, at the expense of
4239      wrong semantics.  If we say -fno-conserve-space, we want this to
4240      produce errors about redefs; to do this we force variables into the
4241      data segment.  */
4242   if (flag_conserve_space
4243       && TREE_CODE (decl) == VAR_DECL
4244       && TREE_PUBLIC (decl)
4245       && !DECL_THREAD_LOCAL_P (decl)
4246       && !have_global_bss_p ())
4247     DECL_COMMON (decl) = 1;
4248
4249   if (TREE_CODE (decl) == VAR_DECL
4250       && DECL_NAMESPACE_SCOPE_P (decl) && !TREE_PUBLIC (decl) && !was_public
4251       && !DECL_THIS_STATIC (decl) && !DECL_ARTIFICIAL (decl))
4252     {
4253       /* This is a const variable with implicit 'static'.  Set
4254          DECL_THIS_STATIC so we can tell it from variables that are
4255          !TREE_PUBLIC because of the anonymous namespace.  */
4256       gcc_assert (cp_type_readonly (TREE_TYPE (decl)));
4257       DECL_THIS_STATIC (decl) = 1;
4258     }
4259
4260   if (!processing_template_decl && TREE_CODE (decl) == VAR_DECL)
4261     start_decl_1 (decl, initialized);
4262
4263   return decl;
4264 }
4265
4266 /* Process the declaration of a variable DECL.  INITIALIZED is true
4267    iff DECL is explicitly initialized.  (INITIALIZED is false if the
4268    variable is initialized via an implicitly-called constructor.)
4269    This function must be called for ordinary variables (including, for
4270    example, implicit instantiations of templates), but must not be
4271    called for template declarations.  */
4272
4273 void
4274 start_decl_1 (tree decl, bool initialized)
4275 {
4276   tree type;
4277   bool complete_p;
4278   bool aggregate_definition_p;
4279
4280   gcc_assert (!processing_template_decl);
4281
4282   if (error_operand_p (decl))
4283     return;
4284
4285   gcc_assert (TREE_CODE (decl) == VAR_DECL);
4286
4287   type = TREE_TYPE (decl);
4288   complete_p = COMPLETE_TYPE_P (type);
4289   aggregate_definition_p = MAYBE_CLASS_TYPE_P (type) && !DECL_EXTERNAL (decl);
4290
4291   /* If an explicit initializer is present, or if this is a definition
4292      of an aggregate, then we need a complete type at this point.
4293      (Scalars are always complete types, so there is nothing to
4294      check.)  This code just sets COMPLETE_P; errors (if necessary)
4295      are issued below.  */
4296   if ((initialized || aggregate_definition_p) 
4297       && !complete_p
4298       && COMPLETE_TYPE_P (complete_type (type)))
4299     {
4300       complete_p = true;
4301       /* We will not yet have set TREE_READONLY on DECL if the type
4302          was "const", but incomplete, before this point.  But, now, we
4303          have a complete type, so we can try again.  */
4304       cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
4305     }
4306
4307   if (initialized)
4308     /* Is it valid for this decl to have an initializer at all?  */
4309     {
4310       /* Don't allow initializations for incomplete types except for
4311          arrays which might be completed by the initialization.  */
4312       if (complete_p)
4313         ;                       /* A complete type is ok.  */
4314       else if (type_uses_auto (type))
4315         ;                       /* An auto type is ok.  */
4316       else if (TREE_CODE (type) != ARRAY_TYPE)
4317         {
4318           error ("variable %q#D has initializer but incomplete type", decl);
4319           type = TREE_TYPE (decl) = error_mark_node;
4320         }
4321       else if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (type))))
4322         {
4323           if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
4324             error ("elements of array %q#D have incomplete type", decl);
4325           /* else we already gave an error in start_decl.  */
4326         }
4327     }
4328   else if (aggregate_definition_p && !complete_p)
4329     {
4330       if (type_uses_auto (type))
4331         error ("declaration of %q#D has no initializer", decl);
4332       else
4333         error ("aggregate %q#D has incomplete type and cannot be defined",
4334                decl);
4335       /* Change the type so that assemble_variable will give
4336          DECL an rtl we can live with: (mem (const_int 0)).  */
4337       type = TREE_TYPE (decl) = error_mark_node;
4338     }
4339
4340   /* Create a new scope to hold this declaration if necessary.
4341      Whether or not a new scope is necessary cannot be determined
4342      until after the type has been completed; if the type is a
4343      specialization of a class template it is not until after
4344      instantiation has occurred that TYPE_HAS_NONTRIVIAL_DESTRUCTOR
4345      will be set correctly.  */
4346   maybe_push_cleanup_level (type);
4347 }
4348
4349 /* Handle initialization of references.  DECL, TYPE, and INIT have the
4350    same meaning as in cp_finish_decl.  *CLEANUP must be NULL on entry,
4351    but will be set to a new CLEANUP_STMT if a temporary is created
4352    that must be destroyed subsequently.
4353
4354    Returns an initializer expression to use to initialize DECL, or
4355    NULL if the initialization can be performed statically.
4356
4357    Quotes on semantics can be found in ARM 8.4.3.  */
4358
4359 static tree
4360 grok_reference_init (tree decl, tree type, tree init, tree *cleanup)
4361 {
4362   tree tmp;
4363
4364   if (init == NULL_TREE)
4365     {
4366       if ((DECL_LANG_SPECIFIC (decl) == 0
4367            || DECL_IN_AGGR_P (decl) == 0)
4368           && ! DECL_THIS_EXTERN (decl))
4369         error ("%qD declared as reference but not initialized", decl);
4370       return NULL_TREE;
4371     }
4372
4373   if (TREE_CODE (init) == TREE_LIST)
4374     init = build_x_compound_expr_from_list (init, "initializer");
4375
4376   if (TREE_CODE (TREE_TYPE (type)) != ARRAY_TYPE
4377       && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
4378     /* Note: default conversion is only called in very special cases.  */
4379     init = decay_conversion (init);
4380
4381   /* Convert INIT to the reference type TYPE.  This may involve the
4382      creation of a temporary, whose lifetime must be the same as that
4383      of the reference.  If so, a DECL_EXPR for the temporary will be
4384      added just after the DECL_EXPR for DECL.  That's why we don't set
4385      DECL_INITIAL for local references (instead assigning to them
4386      explicitly); we need to allow the temporary to be initialized
4387      first.  */
4388   tmp = initialize_reference (type, init, decl, cleanup);
4389
4390   if (tmp == error_mark_node)
4391     return NULL_TREE;
4392   else if (tmp == NULL_TREE)
4393     {
4394       error ("cannot initialize %qT from %qT", type, TREE_TYPE (init));
4395       return NULL_TREE;
4396     }
4397
4398   if (TREE_STATIC (decl) && !TREE_CONSTANT (tmp))
4399     return tmp;
4400
4401   DECL_INITIAL (decl) = tmp;
4402
4403   return NULL_TREE;
4404 }
4405
4406 /* Subroutine of check_initializer.  We're initializing a DECL of
4407    std::initializer_list<T> TYPE from a braced-init-list INIT, and need to
4408    extend the lifetime of the underlying array to match that of the decl,
4409    just like for reference initialization.  CLEANUP is as for
4410    grok_reference_init.  */
4411
4412 static tree
4413 build_init_list_var_init (tree decl, tree type, tree init, tree *cleanup)
4414 {
4415   tree aggr_init, array, arrtype;
4416   init = perform_implicit_conversion (type, init, tf_warning_or_error);
4417   aggr_init = TARGET_EXPR_INITIAL (init);
4418   init = build2 (INIT_EXPR, type, decl, init);
4419
4420   array = AGGR_INIT_EXPR_ARG (aggr_init, 1);
4421   arrtype = TREE_TYPE (array);
4422   STRIP_NOPS (array);
4423   gcc_assert (TREE_CODE (array) == ADDR_EXPR);
4424   array = TREE_OPERAND (array, 0);
4425   /* If the array is constant, finish_compound_literal already made it a
4426      static variable and we don't need to do anything here.  */
4427   if (decl && TREE_CODE (array) == TARGET_EXPR)
4428     {
4429       tree subinit;
4430       tree var = set_up_extended_ref_temp (decl, array, cleanup, &subinit);
4431       var = build_address (var);
4432       var = convert (arrtype, var);
4433       AGGR_INIT_EXPR_ARG (aggr_init, 1) = var;
4434       init = build2 (COMPOUND_EXPR, TREE_TYPE (init), subinit, init);
4435     }
4436   return init;
4437 }
4438
4439 /* Designated initializers in arrays are not supported in GNU C++.
4440    The parser cannot detect this error since it does not know whether
4441    a given brace-enclosed initializer is for a class type or for an
4442    array.  This function checks that CE does not use a designated
4443    initializer.  If it does, an error is issued.  Returns true if CE
4444    is valid, i.e., does not have a designated initializer.  */
4445
4446 static bool
4447 check_array_designated_initializer (const constructor_elt *ce)
4448 {
4449   /* Designated initializers for array elements are not supported.  */
4450   if (ce->index)
4451     {
4452       /* The parser only allows identifiers as designated
4453          initializers.  */
4454       if (ce->index == error_mark_node)
4455         error ("name used in a GNU-style designated "
4456                "initializer for an array");
4457       else
4458         {
4459           gcc_assert (TREE_CODE (ce->index) == IDENTIFIER_NODE);
4460           error ("name %qD used in a GNU-style designated "
4461                  "initializer for an array", ce->index);
4462         }
4463       return false;
4464     }
4465
4466   return true;
4467 }
4468
4469 /* When parsing `int a[] = {1, 2};' we don't know the size of the
4470    array until we finish parsing the initializer.  If that's the
4471    situation we're in, update DECL accordingly.  */
4472
4473 static void
4474 maybe_deduce_size_from_array_init (tree decl, tree init)
4475 {
4476   tree type = TREE_TYPE (decl);
4477
4478   if (TREE_CODE (type) == ARRAY_TYPE
4479       && TYPE_DOMAIN (type) == NULL_TREE
4480       && TREE_CODE (decl) != TYPE_DECL)
4481     {
4482       /* do_default is really a C-ism to deal with tentative definitions.
4483          But let's leave it here to ease the eventual merge.  */
4484       int do_default = !DECL_EXTERNAL (decl);
4485       tree initializer = init ? init : DECL_INITIAL (decl);
4486       int failure = 0;
4487
4488       /* Check that there are no designated initializers in INIT, as
4489          those are not supported in GNU C++, and as the middle-end
4490          will crash if presented with a non-numeric designated
4491          initializer.  */
4492       if (initializer && TREE_CODE (initializer) == CONSTRUCTOR)
4493         {
4494           VEC(constructor_elt,gc) *v = CONSTRUCTOR_ELTS (initializer);
4495           constructor_elt *ce;
4496           HOST_WIDE_INT i;
4497           for (i = 0; 
4498                VEC_iterate (constructor_elt, v, i, ce);
4499                ++i) 
4500             if (!check_array_designated_initializer (ce))
4501               failure = 1;
4502         }
4503
4504       if (!failure)
4505         {
4506           failure = cp_complete_array_type (&TREE_TYPE (decl), initializer,
4507                                             do_default);
4508           if (failure == 1)
4509             {
4510               error ("initializer fails to determine size of %qD", decl);
4511               TREE_TYPE (decl) = error_mark_node;
4512             }
4513           else if (failure == 2)
4514             {
4515               if (do_default)
4516                 {
4517                   error ("array size missing in %qD", decl);
4518                   TREE_TYPE (decl) = error_mark_node;
4519                 }
4520               /* If a `static' var's size isn't known, make it extern as
4521                  well as static, so it does not get allocated.  If it's not
4522                  `static', then don't mark it extern; finish_incomplete_decl
4523                  will give it a default size and it will get allocated.  */
4524               else if (!pedantic && TREE_STATIC (decl) && !TREE_PUBLIC (decl))
4525                 DECL_EXTERNAL (decl) = 1;
4526             }
4527           else if (failure == 3)
4528             {
4529               error ("zero-size array %qD", decl);
4530               TREE_TYPE (decl) = error_mark_node;
4531             }
4532         }
4533
4534       cp_apply_type_quals_to_decl (cp_type_quals (TREE_TYPE (decl)), decl);
4535
4536       relayout_decl (decl);
4537     }
4538 }
4539
4540 /* Set DECL_SIZE, DECL_ALIGN, etc. for DECL (a VAR_DECL), and issue
4541    any appropriate error messages regarding the layout.  */
4542
4543 static void
4544 layout_var_decl (tree decl)
4545 {
4546   tree type;
4547
4548   type = TREE_TYPE (decl);
4549   if (type == error_mark_node)
4550     return;
4551
4552   /* If we haven't already layed out this declaration, do so now.
4553      Note that we must not call complete type for an external object
4554      because it's type might involve templates that we are not
4555      supposed to instantiate yet.  (And it's perfectly valid to say
4556      `extern X x' for some incomplete type `X'.)  */
4557   if (!DECL_EXTERNAL (decl))
4558     complete_type (type);
4559   if (!DECL_SIZE (decl)
4560       && TREE_TYPE (decl) != error_mark_node
4561       && (COMPLETE_TYPE_P (type)
4562           || (TREE_CODE (type) == ARRAY_TYPE
4563               && !TYPE_DOMAIN (type)
4564               && COMPLETE_TYPE_P (TREE_TYPE (type)))))
4565     layout_decl (decl, 0);
4566
4567   if (!DECL_EXTERNAL (decl) && DECL_SIZE (decl) == NULL_TREE)
4568     {
4569       /* An automatic variable with an incomplete type: that is an error.
4570          Don't talk about array types here, since we took care of that
4571          message in grokdeclarator.  */
4572       error ("storage size of %qD isn't known", decl);
4573       TREE_TYPE (decl) = error_mark_node;
4574     }
4575 #if 0
4576   /* Keep this code around in case we later want to control debug info
4577      based on whether a type is "used".  (jason 1999-11-11) */
4578
4579   else if (!DECL_EXTERNAL (decl) && MAYBE_CLASS_TYPE_P (ttype))
4580     /* Let debugger know it should output info for this type.  */
4581     note_debug_info_needed (ttype);
4582
4583   if (TREE_STATIC (decl) && DECL_CLASS_SCOPE_P (decl))
4584     note_debug_info_needed (DECL_CONTEXT (decl));
4585 #endif
4586
4587   if ((DECL_EXTERNAL (decl) || TREE_STATIC (decl))
4588       && DECL_SIZE (decl) != NULL_TREE
4589       && ! TREE_CONSTANT (DECL_SIZE (decl)))
4590     {
4591       if (TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST)
4592         constant_expression_warning (DECL_SIZE (decl));
4593       else
4594         {
4595           error ("storage size of %qD isn't constant", decl);
4596           TREE_TYPE (decl) = error_mark_node;
4597         }
4598     }
4599 }
4600
4601 /* If a local static variable is declared in an inline function, or if
4602    we have a weak definition, we must endeavor to create only one
4603    instance of the variable at link-time.  */
4604
4605 void
4606 maybe_commonize_var (tree decl)
4607 {
4608   /* Static data in a function with comdat linkage also has comdat
4609      linkage.  */
4610   if (TREE_STATIC (decl)
4611       /* Don't mess with __FUNCTION__.  */
4612       && ! DECL_ARTIFICIAL (decl)
4613       && DECL_FUNCTION_SCOPE_P (decl)
4614       /* Unfortunately, import_export_decl has not always been called
4615          before the function is processed, so we cannot simply check
4616          DECL_COMDAT.  */
4617       && (DECL_COMDAT (DECL_CONTEXT (decl))
4618           || ((DECL_DECLARED_INLINE_P (DECL_CONTEXT (decl))
4619                || DECL_TEMPLATE_INSTANTIATION (DECL_CONTEXT (decl)))
4620               && TREE_PUBLIC (DECL_CONTEXT (decl)))))
4621     {
4622       if (flag_weak)
4623         {
4624           /* With weak symbols, we simply make the variable COMDAT;
4625              that will cause copies in multiple translations units to
4626              be merged.  */
4627           comdat_linkage (decl);
4628         }
4629       else
4630         {
4631           if (DECL_INITIAL (decl) == NULL_TREE
4632               || DECL_INITIAL (decl) == error_mark_node)
4633             {
4634               /* Without weak symbols, we can use COMMON to merge
4635                  uninitialized variables.  */
4636               TREE_PUBLIC (decl) = 1;
4637               DECL_COMMON (decl) = 1;
4638             }
4639           else
4640             {
4641               /* While for initialized variables, we must use internal
4642                  linkage -- which means that multiple copies will not
4643                  be merged.  */
4644               TREE_PUBLIC (decl) = 0;
4645               DECL_COMMON (decl) = 0;
4646               warning_at (input_location, 0,
4647                           "sorry: semantics of inline function static "
4648                           "data %q+#D are wrong (you'll wind up "
4649                           "with multiple copies)", decl);
4650               warning_at (DECL_SOURCE_LOCATION (decl), 0, 
4651                           "  you can work around this by removing "
4652                           "the initializer");
4653             }
4654         }
4655     }
4656   else if (DECL_LANG_SPECIFIC (decl) && DECL_COMDAT (decl))
4657     /* Set it up again; we might have set DECL_INITIAL since the last
4658        time.  */
4659     comdat_linkage (decl);
4660 }
4661
4662 /* Issue an error message if DECL is an uninitialized const variable.  */
4663
4664 static void
4665 check_for_uninitialized_const_var (tree decl)
4666 {
4667   tree type = TREE_TYPE (decl);
4668
4669   /* ``Unless explicitly declared extern, a const object does not have
4670      external linkage and must be initialized. ($8.4; $12.1)'' ARM
4671      7.1.6 */
4672   if (TREE_CODE (decl) == VAR_DECL
4673       && TREE_CODE (type) != REFERENCE_TYPE
4674       && CP_TYPE_CONST_P (type)
4675       && !TYPE_NEEDS_CONSTRUCTING (type)
4676       && !DECL_INITIAL (decl))
4677     error ("uninitialized const %qD", decl);
4678 }
4679
4680 \f
4681 /* Structure holding the current initializer being processed by reshape_init.
4682    CUR is a pointer to the current element being processed, END is a pointer
4683    after the last element present in the initializer.  */
4684 typedef struct reshape_iterator_t
4685 {
4686   constructor_elt *cur;
4687   constructor_elt *end;
4688 } reshape_iter;
4689
4690 static tree reshape_init_r (tree, reshape_iter *, bool);
4691
4692 /* FIELD is a FIELD_DECL or NULL.  In the former case, the value
4693    returned is the next FIELD_DECL (possibly FIELD itself) that can be
4694    initialized.  If there are no more such fields, the return value
4695    will be NULL.  */
4696
4697 static tree
4698 next_initializable_field (tree field)
4699 {
4700   while (field
4701          && (TREE_CODE (field) != FIELD_DECL
4702              || (DECL_C_BIT_FIELD (field) && !DECL_NAME (field))
4703              || DECL_ARTIFICIAL (field)))
4704     field = TREE_CHAIN (field);
4705
4706   return field;
4707 }
4708
4709 /* Subroutine of reshape_init_array and reshape_init_vector, which does
4710    the actual work. ELT_TYPE is the element type of the array. MAX_INDEX is an
4711    INTEGER_CST representing the size of the array minus one (the maximum index),
4712    or NULL_TREE if the array was declared without specifying the size. D is
4713    the iterator within the constructor.  */
4714
4715 static tree
4716 reshape_init_array_1 (tree elt_type, tree max_index, reshape_iter *d)
4717 {
4718   tree new_init;
4719   bool sized_array_p = (max_index != NULL_TREE);
4720   unsigned HOST_WIDE_INT max_index_cst = 0;
4721   unsigned HOST_WIDE_INT index;
4722
4723   /* The initializer for an array is always a CONSTRUCTOR.  */
4724   new_init = build_constructor (init_list_type_node, NULL);
4725
4726   if (sized_array_p)
4727     {
4728       /* Minus 1 is used for zero sized arrays.  */
4729       if (integer_all_onesp (max_index))
4730         return new_init;
4731
4732       if (host_integerp (max_index, 1))
4733         max_index_cst = tree_low_cst (max_index, 1);
4734       /* sizetype is sign extended, not zero extended.  */
4735       else
4736         max_index_cst = tree_low_cst (fold_convert (size_type_node, max_index),
4737                                       1);
4738     }
4739
4740   /* Loop until there are no more initializers.  */
4741   for (index = 0;
4742        d->cur != d->end && (!sized_array_p || index <= max_index_cst);
4743        ++index)
4744     {
4745       tree elt_init;
4746
4747       check_array_designated_initializer (d->cur);
4748       elt_init = reshape_init_r (elt_type, d, /*first_initializer_p=*/false);
4749       if (elt_init == error_mark_node)
4750         return error_mark_node;
4751       CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init), NULL_TREE, elt_init);
4752     }
4753
4754   return new_init;
4755 }
4756
4757 /* Subroutine of reshape_init_r, processes the initializers for arrays.
4758    Parameters are the same of reshape_init_r.  */
4759
4760 static tree
4761 reshape_init_array (tree type, reshape_iter *d)
4762 {
4763   tree max_index = NULL_TREE;
4764
4765   gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
4766
4767   if (TYPE_DOMAIN (type))
4768     max_index = array_type_nelts (type);
4769
4770   return reshape_init_array_1 (TREE_TYPE (type), max_index, d);
4771 }
4772
4773 /* Subroutine of reshape_init_r, processes the initializers for vectors.
4774    Parameters are the same of reshape_init_r.  */
4775
4776 static tree
4777 reshape_init_vector (tree type, reshape_iter *d)
4778 {
4779   tree max_index = NULL_TREE;
4780   tree rtype;
4781
4782   gcc_assert (TREE_CODE (type) == VECTOR_TYPE);
4783
4784   if (COMPOUND_LITERAL_P (d->cur->value))
4785     {
4786       tree value = d->cur->value;
4787       if (!same_type_p (TREE_TYPE (value), type))
4788         {
4789           error ("invalid type %qT as initializer for a vector of type %qT",
4790                 TREE_TYPE (d->cur->value), type);
4791           value = error_mark_node;
4792         }
4793       ++d->cur;
4794       return value;
4795     }
4796
4797   /* For a vector, the representation type is a struct
4798       containing a single member which is an array of the
4799       appropriate size.  */
4800   rtype = TYPE_DEBUG_REPRESENTATION_TYPE (type);
4801   if (rtype && TYPE_DOMAIN (TREE_TYPE (TYPE_FIELDS (rtype))))
4802     max_index = array_type_nelts (TREE_TYPE (TYPE_FIELDS (rtype)));
4803
4804   return reshape_init_array_1 (TREE_TYPE (type), max_index, d);
4805 }
4806
4807 /* Subroutine of reshape_init_r, processes the initializers for classes
4808    or union. Parameters are the same of reshape_init_r.  */
4809
4810 static tree
4811 reshape_init_class (tree type, reshape_iter *d, bool first_initializer_p)
4812 {
4813   tree field;
4814   tree new_init;
4815
4816   gcc_assert (CLASS_TYPE_P (type));
4817
4818   /* The initializer for a class is always a CONSTRUCTOR.  */
4819   new_init = build_constructor (init_list_type_node, NULL);
4820   field = next_initializable_field (TYPE_FIELDS (type));
4821
4822   if (!field)
4823     {
4824       /* [dcl.init.aggr]
4825
4826         An initializer for an aggregate member that is an
4827         empty class shall have the form of an empty
4828         initializer-list {}.  */
4829       if (!first_initializer_p)
4830         {
4831           error ("initializer for %qT must be brace-enclosed", type);
4832           return error_mark_node;
4833         }
4834       return new_init;
4835     }
4836
4837   /* Loop through the initializable fields, gathering initializers.  */
4838   while (d->cur != d->end)
4839     {
4840       tree field_init;
4841
4842       /* Handle designated initializers, as an extension.  */
4843       if (d->cur->index)
4844         {
4845           field = lookup_field_1 (type, d->cur->index, /*want_type=*/false);
4846
4847           if (!field || TREE_CODE (field) != FIELD_DECL)
4848             {
4849               error ("%qT has no non-static data member named %qD", type,
4850                     d->cur->index);
4851               return error_mark_node;
4852             }
4853         }
4854
4855       /* If we processed all the member of the class, we are done.  */
4856       if (!field)
4857         break;
4858
4859       field_init = reshape_init_r (TREE_TYPE (field), d,
4860                                    /*first_initializer_p=*/false);
4861       CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init), field, field_init);
4862
4863       /* [dcl.init.aggr]
4864
4865         When a union  is  initialized with a brace-enclosed
4866         initializer, the braces shall only contain an
4867         initializer for the first member of the union.  */
4868       if (TREE_CODE (type) == UNION_TYPE)
4869         break;
4870
4871       field = next_initializable_field (TREE_CHAIN (field));
4872     }
4873
4874   return new_init;
4875 }
4876
4877 /* Subroutine of reshape_init, which processes a single initializer (part of
4878    a CONSTRUCTOR). TYPE is the type of the variable being initialized, D is the
4879    iterator within the CONSTRUCTOR which points to the initializer to process.
4880    FIRST_INITIALIZER_P is true if this is the first initializer of the
4881    outermost CONSTRUCTOR node.  */
4882
4883 static tree
4884 reshape_init_r (tree type, reshape_iter *d, bool first_initializer_p)
4885 {
4886   tree init = d->cur->value;
4887
4888   if (error_operand_p (init))
4889     return error_mark_node;
4890
4891   /* A non-aggregate type is always initialized with a single
4892      initializer.  */
4893   if (!CP_AGGREGATE_TYPE_P (type))
4894     {
4895       /* It is invalid to initialize a non-aggregate type with a
4896          brace-enclosed initializer before C++0x.
4897          We need to check for BRACE_ENCLOSED_INITIALIZER_P here because
4898          of g++.old-deja/g++.mike/p7626.C: a pointer-to-member constant is
4899          a CONSTRUCTOR (with a record type).  */
4900       if (TREE_CODE (init) == CONSTRUCTOR
4901           && BRACE_ENCLOSED_INITIALIZER_P (init))  /* p7626.C */
4902         {
4903           if (SCALAR_TYPE_P (type))
4904             {
4905               error ("braces around scalar initializer for type %qT", type);
4906               init = error_mark_node;
4907             }
4908           else
4909             maybe_warn_cpp0x ("extended initializer lists");
4910         }
4911
4912       d->cur++;
4913       return init;
4914     }
4915
4916   /* [dcl.init.aggr]
4917
4918      All implicit type conversions (clause _conv_) are considered when
4919      initializing the aggregate member with an initializer from an
4920      initializer-list.  If the initializer can initialize a member,
4921      the member is initialized.  Otherwise, if the member is itself a
4922      non-empty subaggregate, brace elision is assumed and the
4923      initializer is considered for the initialization of the first
4924      member of the subaggregate.  */
4925   if (TREE_CODE (init) != CONSTRUCTOR
4926       /* But don't try this for the first initializer, since that would be
4927          looking through the outermost braces; A a2 = { a1 }; is not a
4928          valid aggregate initialization.  */
4929       && !first_initializer_p
4930       && can_convert_arg (type, TREE_TYPE (init), init, LOOKUP_NORMAL))
4931     {
4932       d->cur++;
4933       return init;
4934     }
4935
4936   /* [dcl.init.string]
4937
4938       A char array (whether plain char, signed char, or unsigned char)
4939       can be initialized by a string-literal (optionally enclosed in
4940       braces); a wchar_t array can be initialized by a wide
4941       string-literal (optionally enclosed in braces).  */
4942   if (TREE_CODE (type) == ARRAY_TYPE
4943       && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type))))
4944     {
4945       tree str_init = init;
4946
4947       /* Strip one level of braces if and only if they enclose a single
4948          element (as allowed by [dcl.init.string]).  */
4949       if (!first_initializer_p
4950           && TREE_CODE (str_init) == CONSTRUCTOR
4951           && VEC_length (constructor_elt, CONSTRUCTOR_ELTS (str_init)) == 1)
4952         {
4953           str_init = VEC_index (constructor_elt,
4954                                 CONSTRUCTOR_ELTS (str_init), 0)->value;
4955         }
4956
4957       /* If it's a string literal, then it's the initializer for the array
4958          as a whole. Otherwise, continue with normal initialization for
4959          array types (one value per array element).  */
4960       if (TREE_CODE (str_init) == STRING_CST)
4961         {
4962           d->cur++;
4963           return str_init;
4964         }
4965     }
4966
4967   /* The following cases are about aggregates. If we are not within a full
4968      initializer already, and there is not a CONSTRUCTOR, it means that there
4969      is a missing set of braces (that is, we are processing the case for
4970      which reshape_init exists).  */
4971   if (!first_initializer_p)
4972     {
4973       if (TREE_CODE (init) == CONSTRUCTOR)
4974         {
4975           if (TREE_TYPE (init) && TYPE_PTRMEMFUNC_P (TREE_TYPE (init)))
4976             /* There is no need to reshape pointer-to-member function
4977                initializers, as they are always constructed correctly
4978                by the front end.  */
4979            ;
4980           else if (COMPOUND_LITERAL_P (init))
4981           /* For a nested compound literal, there is no need to reshape since
4982              brace elision is not allowed. Even if we decided to allow it,
4983              we should add a call to reshape_init in finish_compound_literal,
4984              before calling digest_init, so changing this code would still
4985              not be necessary.  */
4986             gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (init));
4987           else
4988             {
4989               ++d->cur;
4990               gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (init));
4991               return reshape_init (type, init);
4992             }
4993         }
4994
4995       warning (OPT_Wmissing_braces, "missing braces around initializer for %qT",
4996                type);
4997     }
4998
4999   /* Dispatch to specialized routines.  */
5000   if (CLASS_TYPE_P (type))
5001     return reshape_init_class (type, d, first_initializer_p);
5002   else if (TREE_CODE (type) == ARRAY_TYPE)
5003     return reshape_init_array (type, d);
5004   else if (TREE_CODE (type) == VECTOR_TYPE)
5005     return reshape_init_vector (type, d);
5006   else
5007     gcc_unreachable();
5008 }
5009
5010 /* Undo the brace-elision allowed by [dcl.init.aggr] in a
5011    brace-enclosed aggregate initializer.
5012
5013    INIT is the CONSTRUCTOR containing the list of initializers describing
5014    a brace-enclosed initializer for an entity of the indicated aggregate TYPE.
5015    It may not presently match the shape of the TYPE; for example:
5016
5017      struct S { int a; int b; };
5018      struct S a[] = { 1, 2, 3, 4 };
5019
5020    Here INIT will hold a VEC of four elements, rather than a
5021    VEC of two elements, each itself a VEC of two elements.  This
5022    routine transforms INIT from the former form into the latter.  The
5023    revised CONSTRUCTOR node is returned.  */
5024
5025 tree
5026 reshape_init (tree type, tree init)
5027 {
5028   VEC(constructor_elt, gc) *v;
5029   reshape_iter d;
5030   tree new_init;
5031
5032   gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (init));
5033
5034   v = CONSTRUCTOR_ELTS (init);
5035
5036   /* An empty constructor does not need reshaping, and it is always a valid
5037      initializer.  */
5038   if (VEC_empty (constructor_elt, v))
5039     return init;
5040
5041   /* Recurse on this CONSTRUCTOR.  */
5042   d.cur = VEC_index (constructor_elt, v, 0);
5043   d.end = d.cur + VEC_length (constructor_elt, v);
5044
5045   new_init = reshape_init_r (type, &d, true);
5046   if (new_init == error_mark_node)
5047     return error_mark_node;
5048
5049   /* Make sure all the element of the constructor were used. Otherwise,
5050      issue an error about exceeding initializers.  */
5051   if (d.cur != d.end)
5052     error ("too many initializers for %qT", type);
5053
5054   return new_init;
5055 }
5056
5057 /* Verify array initializer.  Returns true if errors have been reported.  */
5058
5059 bool
5060 check_array_initializer (tree decl, tree type, tree init)
5061 {
5062   tree element_type = TREE_TYPE (type);
5063
5064   /* The array type itself need not be complete, because the
5065      initializer may tell us how many elements are in the array.
5066      But, the elements of the array must be complete.  */
5067   if (!COMPLETE_TYPE_P (complete_type (element_type)))
5068     {
5069       if (decl)
5070         error ("elements of array %q#D have incomplete type", decl);
5071       else
5072         error ("elements of array %q#T have incomplete type", type);
5073       return true;
5074     }
5075   /* It is not valid to initialize a VLA.  */
5076   if (init
5077       && ((COMPLETE_TYPE_P (type) && !TREE_CONSTANT (TYPE_SIZE (type)))
5078           || !TREE_CONSTANT (TYPE_SIZE (element_type))))
5079     {
5080       if (decl)
5081         error ("variable-sized object %qD may not be initialized", decl);
5082       else
5083         error ("variable-sized compound literal");
5084       return true;
5085     }
5086   return false;
5087 }
5088
5089 /* Subroutine of check_initializer; args are passed down from that function.
5090    Set stmts_are_full_exprs_p to 1 across a call to build_aggr_init.  */
5091
5092 static tree
5093 build_aggr_init_full_exprs (tree decl, tree init, int flags)
5094      
5095 {
5096   int saved_stmts_are_full_exprs_p = 0;
5097   if (building_stmt_tree ())
5098     {
5099       saved_stmts_are_full_exprs_p = stmts_are_full_exprs_p ();
5100       current_stmt_tree ()->stmts_are_full_exprs_p = 1;
5101     }
5102   init = build_aggr_init (decl, init, flags, tf_warning_or_error);
5103   if (building_stmt_tree ())
5104     current_stmt_tree ()->stmts_are_full_exprs_p =
5105       saved_stmts_are_full_exprs_p;
5106   return init;
5107 }
5108
5109 /* Verify INIT (the initializer for DECL), and record the
5110    initialization in DECL_INITIAL, if appropriate.  CLEANUP is as for
5111    grok_reference_init.
5112
5113    If the return value is non-NULL, it is an expression that must be
5114    evaluated dynamically to initialize DECL.  */
5115
5116 static tree
5117 check_initializer (tree decl, tree init, int flags, tree *cleanup)
5118 {
5119   tree type = TREE_TYPE (decl);
5120   tree init_code = NULL;
5121
5122   /* Things that are going to be initialized need to have complete
5123      type.  */
5124   TREE_TYPE (decl) = type = complete_type (TREE_TYPE (decl));
5125
5126   if (type == error_mark_node)
5127     /* We will have already complained.  */
5128     return NULL_TREE;
5129
5130   if (TREE_CODE (type) == ARRAY_TYPE)
5131     {
5132       if (check_array_initializer (decl, type, init))
5133         return NULL_TREE;
5134     }
5135   else if (!COMPLETE_TYPE_P (type))
5136     {
5137       error ("%qD has incomplete type", decl);
5138       TREE_TYPE (decl) = error_mark_node;
5139       return NULL_TREE;
5140     }
5141   else
5142     /* There is no way to make a variable-sized class type in GNU C++.  */
5143     gcc_assert (TREE_CONSTANT (TYPE_SIZE (type)));
5144
5145   if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
5146     {
5147       int init_len = VEC_length (constructor_elt, CONSTRUCTOR_ELTS (init));
5148       if (SCALAR_TYPE_P (type))
5149         {
5150           if (init_len == 0)
5151             {
5152               maybe_warn_cpp0x ("extended initializer lists");
5153               init = build_zero_init (type, NULL_TREE, false);
5154             }
5155           else if (init_len != 1)
5156             {
5157               error ("scalar object %qD requires one element in initializer",
5158                      decl);
5159               TREE_TYPE (decl) = error_mark_node;
5160               return NULL_TREE;
5161             }
5162         }
5163     }
5164
5165   if (TREE_CODE (decl) == CONST_DECL)
5166     {
5167       gcc_assert (TREE_CODE (type) != REFERENCE_TYPE);
5168
5169       DECL_INITIAL (decl) = init;
5170
5171       gcc_assert (init != NULL_TREE);
5172       init = NULL_TREE;
5173     }
5174   else if (!DECL_EXTERNAL (decl) && TREE_CODE (type) == REFERENCE_TYPE)
5175     init = grok_reference_init (decl, type, init, cleanup);
5176   else if (init)
5177     {
5178       /* Do not reshape constructors of vectors (they don't need to be
5179          reshaped.  */
5180       if (BRACE_ENCLOSED_INITIALIZER_P (init))
5181         {
5182           if (is_std_init_list (type))
5183             return build_init_list_var_init (decl, type, init, cleanup);
5184           else if (TYPE_NON_AGGREGATE_CLASS (type))
5185             {
5186               /* Don't reshape if the class has constructors.  */
5187               if (cxx_dialect == cxx98)
5188                 error ("in C++98 %qD must be initialized by constructor, "
5189                        "not by %<{...}%>",
5190                        decl);
5191               init = build_tree_list (NULL_TREE, init);
5192             }
5193           else if (TREE_CODE (type) == VECTOR_TYPE && TYPE_VECTOR_OPAQUE (type))
5194             {
5195               error ("opaque vector types cannot be initialized");
5196               init = error_mark_node;
5197             }
5198           else
5199             init = reshape_init (type, init);       
5200         }
5201
5202       /* If DECL has an array type without a specific bound, deduce the
5203          array size from the initializer.  */
5204       maybe_deduce_size_from_array_init (decl, init);
5205       type = TREE_TYPE (decl);
5206       if (type == error_mark_node)
5207         return NULL_TREE;
5208
5209       if (TYPE_NEEDS_CONSTRUCTING (type)
5210           || (CLASS_TYPE_P (type)
5211               && !BRACE_ENCLOSED_INITIALIZER_P (init)))
5212         return build_aggr_init_full_exprs (decl, init, flags);
5213       else if (TREE_CODE (init) != TREE_VEC)
5214         {
5215           init_code = store_init_value (decl, init, flags);
5216           if (pedantic && TREE_CODE (type) == ARRAY_TYPE
5217               && DECL_INITIAL (decl)
5218               && TREE_CODE (DECL_INITIAL (decl)) == STRING_CST
5219               && PAREN_STRING_LITERAL_P (DECL_INITIAL (decl)))
5220             warning (0, "array %qD initialized by parenthesized string literal %qE",
5221                      decl, DECL_INITIAL (decl));
5222           init = NULL;
5223         }
5224     }
5225   else if (DECL_EXTERNAL (decl))
5226     ;
5227   else if (TYPE_P (type) && TYPE_NEEDS_CONSTRUCTING (type))
5228     return build_aggr_init_full_exprs (decl, init, flags);
5229   else if (MAYBE_CLASS_TYPE_P (type))
5230     {
5231       tree core_type = strip_array_types (type);
5232
5233       if (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type))
5234         error ("structure %qD with uninitialized const members", decl);
5235       if (CLASSTYPE_REF_FIELDS_NEED_INIT (core_type))
5236         error ("structure %qD with uninitialized reference members", decl);
5237
5238       check_for_uninitialized_const_var (decl);
5239     }
5240   else
5241     check_for_uninitialized_const_var (decl);
5242
5243   if (init && init != error_mark_node)
5244     init_code = build2 (INIT_EXPR, type, decl, init);
5245
5246   return init_code;
5247 }
5248
5249 /* If DECL is not a local variable, give it RTL.  */
5250
5251 static void
5252 make_rtl_for_nonlocal_decl (tree decl, tree init, const char* asmspec)
5253 {
5254   int toplev = toplevel_bindings_p ();
5255   int defer_p;
5256   const char *filename;
5257
5258   /* Set the DECL_ASSEMBLER_NAME for the object.  */
5259   if (asmspec)
5260     {
5261       /* The `register' keyword, when used together with an
5262          asm-specification, indicates that the variable should be
5263          placed in a particular register.  */
5264       if (TREE_CODE (decl) == VAR_DECL && DECL_REGISTER (decl))
5265         {
5266           set_user_assembler_name (decl, asmspec);
5267           DECL_HARD_REGISTER (decl) = 1;
5268         }
5269       else
5270         {
5271           if (TREE_CODE (decl) == FUNCTION_DECL
5272               && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
5273             set_builtin_user_assembler_name (decl, asmspec);
5274           set_user_assembler_name (decl, asmspec);
5275         }
5276     }
5277
5278   /* Handle non-variables up front.  */
5279   if (TREE_CODE (decl) != VAR_DECL)
5280     {
5281       rest_of_decl_compilation (decl, toplev, at_eof);
5282       return;
5283     }
5284
5285   /* If we see a class member here, it should be a static data
5286      member.  */
5287   if (DECL_LANG_SPECIFIC (decl) && DECL_IN_AGGR_P (decl))
5288     {
5289       gcc_assert (TREE_STATIC (decl));
5290       /* An in-class declaration of a static data member should be
5291          external; it is only a declaration, and not a definition.  */
5292       if (init == NULL_TREE)
5293         gcc_assert (DECL_EXTERNAL (decl) || !TREE_PUBLIC (decl));
5294     }
5295
5296   /* We don't create any RTL for local variables.  */
5297   if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
5298     return;
5299
5300   /* We defer emission of local statics until the corresponding
5301      DECL_EXPR is expanded.  */
5302   defer_p = DECL_FUNCTION_SCOPE_P (decl) || DECL_VIRTUAL_P (decl);
5303
5304   /* We try to defer namespace-scope static constants so that they are
5305      not emitted into the object file unnecessarily.  */
5306   filename = input_filename;
5307   if (!DECL_VIRTUAL_P (decl)
5308       && TREE_READONLY (decl)
5309       && DECL_INITIAL (decl) != NULL_TREE
5310       && DECL_INITIAL (decl) != error_mark_node
5311       && filename != NULL
5312       && ! EMPTY_CONSTRUCTOR_P (DECL_INITIAL (decl))
5313       && toplev
5314       && !TREE_PUBLIC (decl))
5315     {
5316       /* Fool with the linkage of static consts according to #pragma
5317          interface.  */
5318       struct c_fileinfo *finfo = get_fileinfo (filename);
5319       if (!finfo->interface_unknown && !TREE_PUBLIC (decl))
5320         {
5321           TREE_PUBLIC (decl) = 1;
5322           DECL_EXTERNAL (decl) = finfo->interface_only;
5323         }
5324
5325       defer_p = 1;
5326     }
5327   /* Likewise for template instantiations.  */
5328   else if (DECL_LANG_SPECIFIC (decl)
5329            && DECL_IMPLICIT_INSTANTIATION (decl))
5330     defer_p = 1;
5331
5332   /* If we're not deferring, go ahead and assemble the variable.  */
5333   if (!defer_p)
5334     rest_of_decl_compilation (decl, toplev, at_eof);
5335 }
5336
5337 /* walk_tree helper for wrap_temporary_cleanups, below.  */
5338
5339 static tree
5340 wrap_cleanups_r (tree *stmt_p, int *walk_subtrees, void *data)
5341 {
5342   if (TYPE_P (*stmt_p))
5343     {
5344       *walk_subtrees = 0;
5345       return NULL_TREE;
5346     }
5347
5348   if (TREE_CODE (*stmt_p) == TARGET_EXPR)
5349     {
5350       tree guard = (tree)data;
5351       tree tcleanup = TARGET_EXPR_CLEANUP (*stmt_p);
5352
5353       tcleanup = build2 (TRY_CATCH_EXPR, void_type_node, tcleanup, guard);
5354       /* Tell honor_protect_cleanup_actions to handle this as a separate
5355          cleanup.  */
5356       TRY_CATCH_IS_CLEANUP (tcleanup) = 1;
5357  
5358       TARGET_EXPR_CLEANUP (*stmt_p) = tcleanup;
5359     }
5360
5361   return NULL_TREE;
5362 }
5363
5364 /* We're initializing a local variable which has a cleanup GUARD.  If there
5365    are any temporaries used in the initializer INIT of this variable, we
5366    need to wrap their cleanups with TRY_CATCH_EXPR (, GUARD) so that the
5367    variable will be cleaned up properly if one of them throws.
5368
5369    Unfortunately, there's no way to express this properly in terms of
5370    nesting, as the regions for the temporaries overlap the region for the
5371    variable itself; if there are two temporaries, the variable needs to be
5372    the first thing destroyed if either of them throws.  However, we only
5373    want to run the variable's cleanup if it actually got constructed.  So
5374    we need to guard the temporary cleanups with the variable's cleanup if
5375    they are run on the normal path, but not if they are run on the
5376    exceptional path.  We implement this by telling
5377    honor_protect_cleanup_actions to strip the variable cleanup from the
5378    exceptional path.  */
5379
5380 static void
5381 wrap_temporary_cleanups (tree init, tree guard)
5382 {
5383   cp_walk_tree_without_duplicates (&init, wrap_cleanups_r, (void *)guard);
5384 }
5385
5386 /* Generate code to initialize DECL (a local variable).  */
5387
5388 static void
5389 initialize_local_var (tree decl, tree init)
5390 {
5391   tree type = TREE_TYPE (decl);
5392   tree cleanup;
5393   int already_used;
5394
5395   gcc_assert (TREE_CODE (decl) == VAR_DECL
5396               || TREE_CODE (decl) == RESULT_DECL);
5397   gcc_assert (!TREE_STATIC (decl));
5398
5399   if (DECL_SIZE (decl) == NULL_TREE)
5400     {
5401       /* If we used it already as memory, it must stay in memory.  */
5402       DECL_INITIAL (decl) = NULL_TREE;
5403       TREE_ADDRESSABLE (decl) = TREE_USED (decl);
5404       return;
5405     }
5406
5407   if (type == error_mark_node)
5408     return;
5409
5410   /* Compute and store the initial value.  */
5411   already_used = TREE_USED (decl) || TREE_USED (type);
5412
5413   /* Generate a cleanup, if necessary.  */
5414   cleanup = cxx_maybe_build_cleanup (decl);
5415
5416   /* Perform the initialization.  */
5417   if (init)
5418     {
5419       int saved_stmts_are_full_exprs_p;
5420
5421       /* If we're only initializing a single object, guard the destructors
5422          of any temporaries used in its initializer with its destructor.
5423          This isn't right for arrays because each element initialization is
5424          a full-expression.  */
5425       if (cleanup && TREE_CODE (type) != ARRAY_TYPE)
5426         wrap_temporary_cleanups (init, cleanup);
5427
5428       gcc_assert (building_stmt_tree ());
5429       saved_stmts_are_full_exprs_p = stmts_are_full_exprs_p ();
5430       current_stmt_tree ()->stmts_are_full_exprs_p = 1;
5431       finish_expr_stmt (init);
5432       current_stmt_tree ()->stmts_are_full_exprs_p =
5433         saved_stmts_are_full_exprs_p;
5434     }
5435
5436   /* Set this to 0 so we can tell whether an aggregate which was
5437      initialized was ever used.  Don't do this if it has a
5438      destructor, so we don't complain about the 'resource
5439      allocation is initialization' idiom.  Now set
5440      attribute((unused)) on types so decls of that type will be
5441      marked used. (see TREE_USED, above.)  */
5442   if (TYPE_NEEDS_CONSTRUCTING (type)
5443       && ! already_used
5444       && TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
5445       && DECL_NAME (decl))
5446     TREE_USED (decl) = 0;
5447   else if (already_used)
5448     TREE_USED (decl) = 1;
5449
5450   if (cleanup)
5451     finish_decl_cleanup (decl, cleanup);
5452 }
5453
5454 /* DECL is a VAR_DECL for a compiler-generated variable with static
5455    storage duration (like a virtual table) whose initializer is a
5456    compile-time constant.  INIT must be either a TREE_LIST of values,
5457    or a CONSTRUCTOR.  Initialize the variable and provide it to the
5458    back end.  */
5459
5460 void
5461 initialize_artificial_var (tree decl, tree init)
5462 {
5463   gcc_assert (DECL_ARTIFICIAL (decl));
5464   if (TREE_CODE (init) == TREE_LIST)
5465     init = build_constructor_from_list (TREE_TYPE (decl), init);
5466   gcc_assert (TREE_CODE (init) == CONSTRUCTOR);
5467   DECL_INITIAL (decl) = init;
5468   DECL_INITIALIZED_P (decl) = 1;
5469   determine_visibility (decl);
5470   layout_var_decl (decl);
5471   maybe_commonize_var (decl);
5472   make_rtl_for_nonlocal_decl (decl, init, /*asmspec=*/NULL);
5473 }
5474
5475 /* INIT is the initializer for a variable, as represented by the
5476    parser.  Returns true iff INIT is value-dependent.  */
5477
5478 static bool
5479 value_dependent_init_p (tree init)
5480 {
5481   if (TREE_CODE (init) == TREE_LIST)
5482     /* A parenthesized initializer, e.g.: int i (3, 2); ? */
5483     return any_value_dependent_elements_p (init);
5484   else if (TREE_CODE (init) == CONSTRUCTOR)
5485   /* A brace-enclosed initializer, e.g.: int i = { 3 }; ? */
5486     {
5487       VEC(constructor_elt, gc) *elts;
5488       size_t nelts;
5489       size_t i;
5490
5491       elts = CONSTRUCTOR_ELTS (init);
5492       nelts = VEC_length (constructor_elt, elts);
5493       for (i = 0; i < nelts; ++i)
5494         if (value_dependent_init_p (VEC_index (constructor_elt,
5495                                                elts, i)->value))
5496           return true;
5497     }
5498   else
5499     /* It must be a simple expression, e.g., int i = 3;  */
5500     return value_dependent_expression_p (init);
5501   
5502   return false;
5503 }
5504
5505 /* Finish processing of a declaration;
5506    install its line number and initial value.
5507    If the length of an array type is not known before,
5508    it must be determined now, from the initial value, or it is an error.
5509
5510    INIT is the initializer (if any) for DECL.  If INIT_CONST_EXPR_P is
5511    true, then INIT is an integral constant expression.
5512
5513    FLAGS is LOOKUP_ONLYCONVERTING if the = init syntax was used, else 0
5514    if the (init) syntax was used.  */
5515
5516 void
5517 cp_finish_decl (tree decl, tree init, bool init_const_expr_p,
5518                 tree asmspec_tree, int flags)
5519 {
5520   tree type;
5521   tree cleanup;
5522   const char *asmspec = NULL;
5523   int was_readonly = 0;
5524   bool var_definition_p = false;
5525   int saved_processing_template_decl;
5526   tree auto_node;
5527
5528   if (decl == error_mark_node)
5529     return;
5530   else if (! decl)
5531     {
5532       if (init)
5533         error ("assignment (not initialization) in declaration");
5534       return;
5535     }
5536
5537   gcc_assert (TREE_CODE (decl) != RESULT_DECL);
5538   /* Parameters are handled by store_parm_decls, not cp_finish_decl.  */
5539   gcc_assert (TREE_CODE (decl) != PARM_DECL);
5540
5541   type = TREE_TYPE (decl);
5542   if (type == error_mark_node)
5543     return;
5544
5545   /* Assume no cleanup is required.  */
5546   cleanup = NULL_TREE;
5547   saved_processing_template_decl = processing_template_decl;
5548
5549   /* If a name was specified, get the string.  */
5550   if (global_scope_p (current_binding_level))
5551     asmspec_tree = maybe_apply_renaming_pragma (decl, asmspec_tree);
5552   if (asmspec_tree && asmspec_tree != error_mark_node)
5553     asmspec = TREE_STRING_POINTER (asmspec_tree);
5554
5555   if (current_class_type
5556       && CP_DECL_CONTEXT (decl) == current_class_type
5557       && TYPE_BEING_DEFINED (current_class_type)
5558       && (DECL_INITIAL (decl) || init))
5559     DECL_INITIALIZED_IN_CLASS_P (decl) = 1;
5560
5561   auto_node = type_uses_auto (type);
5562   if (auto_node)
5563     {
5564       if (init == NULL_TREE)
5565         {
5566           error ("declaration of %q#D has no initializer", decl);
5567           TREE_TYPE (decl) = error_mark_node;
5568           return;
5569         }
5570       if (TREE_CODE (init) == TREE_LIST)
5571         init = build_x_compound_expr_from_list (init, "initializer");
5572       if (describable_type (init))
5573         {
5574           type = TREE_TYPE (decl) = do_auto_deduction (type, init, auto_node);
5575           if (type == error_mark_node)
5576             return;
5577         }
5578     }
5579
5580   if (init && TREE_CODE (decl) == FUNCTION_DECL)
5581     {
5582       if (init == ridpointers[(int)RID_DELETE])
5583         {
5584           /* FIXME check this is 1st decl.  */
5585           DECL_DELETED_FN (decl) = 1;
5586           DECL_DECLARED_INLINE_P (decl) = 1;
5587           DECL_INITIAL (decl) = error_mark_node;
5588           init = NULL_TREE;
5589         }
5590       else if (init == ridpointers[(int)RID_DEFAULT])
5591         {
5592           if (!defaultable_fn_p (decl))
5593             {
5594               error ("%qD cannot be defaulted", decl);
5595               DECL_INITIAL (decl) = NULL_TREE;
5596             }
5597           else
5598             DECL_DEFAULTED_FN (decl) = 1;
5599         }
5600     }
5601     
5602   if (processing_template_decl)
5603     {
5604       bool type_dependent_p;
5605
5606       /* Add this declaration to the statement-tree.  */
5607       if (at_function_scope_p ())
5608         add_decl_expr (decl);
5609
5610       type_dependent_p = dependent_type_p (type);
5611
5612       if (check_for_bare_parameter_packs (init))
5613         {
5614           init = NULL_TREE;
5615           DECL_INITIAL (decl) = NULL_TREE;
5616         }
5617
5618       if (init && init_const_expr_p && TREE_CODE (decl) == VAR_DECL)
5619         {
5620           DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
5621           if (DECL_INTEGRAL_CONSTANT_VAR_P (decl))
5622             TREE_CONSTANT (decl) = 1;
5623         }
5624
5625       /* Generally, initializers in templates are expanded when the
5626          template is instantiated.  But, if DECL is an integral
5627          constant static data member, then it can be used in future
5628          integral constant expressions, and its value must be
5629          available. */
5630       if (!(init
5631             && DECL_CLASS_SCOPE_P (decl)
5632             && DECL_INTEGRAL_CONSTANT_VAR_P (decl)
5633             && !type_dependent_p
5634             && !value_dependent_init_p (init)))
5635         {
5636           if (init)
5637             DECL_INITIAL (decl) = init;
5638           if (TREE_CODE (decl) == VAR_DECL
5639               && !DECL_PRETTY_FUNCTION_P (decl)
5640               && !type_dependent_p)
5641             maybe_deduce_size_from_array_init (decl, init);
5642           goto finish_end;
5643         }
5644
5645       if (TREE_CODE (init) == TREE_LIST)
5646         {
5647           /* If the parenthesized-initializer form was used (e.g.,
5648              "int A<N>::i(X)"), then INIT will be a TREE_LIST of initializer
5649              arguments.  (There is generally only one.)  We convert them
5650              individually.  */
5651           tree list = init;
5652           for (; list; list = TREE_CHAIN (list))
5653             {
5654               tree elt = TREE_VALUE (list);
5655               TREE_VALUE (list) = fold_non_dependent_expr (elt);
5656             }
5657         }
5658       else
5659         init = fold_non_dependent_expr (init);
5660       processing_template_decl = 0;
5661     }
5662
5663   /* Take care of TYPE_DECLs up front.  */
5664   if (TREE_CODE (decl) == TYPE_DECL)
5665     {
5666       if (type != error_mark_node
5667           && MAYBE_CLASS_TYPE_P (type) && DECL_NAME (decl))
5668         {
5669           if (TREE_TYPE (DECL_NAME (decl)) && TREE_TYPE (decl) != type)
5670             warning (0, "shadowing previous type declaration of %q#D", decl);
5671           set_identifier_type_value (DECL_NAME (decl), decl);
5672         }
5673
5674       /* If we have installed this as the canonical typedef for this
5675          type, and that type has not been defined yet, delay emitting
5676          the debug information for it, as we will emit it later.  */
5677       if (TYPE_MAIN_DECL (TREE_TYPE (decl)) == decl
5678           && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
5679         TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
5680
5681       rest_of_decl_compilation (decl, DECL_CONTEXT (decl) == NULL_TREE,
5682                                 at_eof);
5683       goto finish_end;
5684     }
5685
5686   /* A reference will be modified here, as it is initialized.  */
5687   if (! DECL_EXTERNAL (decl)
5688       && TREE_READONLY (decl)
5689       && TREE_CODE (type) == REFERENCE_TYPE)
5690     {
5691       was_readonly = 1;
5692       TREE_READONLY (decl) = 0;
5693     }
5694
5695   if (TREE_CODE (decl) == VAR_DECL)
5696     {
5697       /* Only variables with trivial initialization and destruction can
5698          have thread-local storage.  */
5699       if (DECL_THREAD_LOCAL_P (decl)
5700           && (type_has_nontrivial_default_init (TREE_TYPE (decl))
5701               || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl))))
5702         error ("%qD cannot be thread-local because it has non-trivial "
5703                "type %qT", decl, TREE_TYPE (decl));
5704       /* If this is a local variable that will need a mangled name,
5705          register it now.  We must do this before processing the
5706          initializer for the variable, since the initialization might
5707          require a guard variable, and since the mangled name of the
5708          guard variable will depend on the mangled name of this
5709          variable.  */
5710       if (DECL_FUNCTION_SCOPE_P (decl)
5711           && TREE_STATIC (decl)
5712           && !DECL_ARTIFICIAL (decl))
5713         push_local_name (decl);
5714       /* Convert the initializer to the type of DECL, if we have not
5715          already initialized DECL.  */
5716       if (!DECL_INITIALIZED_P (decl)
5717           /* If !DECL_EXTERNAL then DECL is being defined.  In the
5718              case of a static data member initialized inside the
5719              class-specifier, there can be an initializer even if DECL
5720              is *not* defined.  */
5721           && (!DECL_EXTERNAL (decl) || init))
5722         {
5723           if (TYPE_FOR_JAVA (type) && MAYBE_CLASS_TYPE_P (type))
5724             {
5725               tree jclass
5726                 = IDENTIFIER_GLOBAL_VALUE (get_identifier ("jclass"));
5727               /* Allow libjava/prims.cc define primitive classes.  */
5728               if (init != NULL_TREE
5729                   || jclass == NULL_TREE
5730                   || TREE_CODE (jclass) != TYPE_DECL
5731                   || !POINTER_TYPE_P (TREE_TYPE (jclass))
5732                   || !same_type_ignoring_top_level_qualifiers_p
5733                                         (type, TREE_TYPE (TREE_TYPE (jclass))))
5734                 error ("Java object %qD not allocated with %<new%>", decl);
5735               init = NULL_TREE;
5736             }
5737           if (init)
5738             {
5739               DECL_NONTRIVIALLY_INITIALIZED_P (decl) = 1;
5740               if (init_const_expr_p)
5741                 {
5742                   DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
5743                   if (DECL_INTEGRAL_CONSTANT_VAR_P (decl))
5744                     TREE_CONSTANT (decl) = 1;
5745                 }
5746             }
5747           init = check_initializer (decl, init, flags, &cleanup);
5748           /* Thread-local storage cannot be dynamically initialized.  */
5749           if (DECL_THREAD_LOCAL_P (decl) && init)
5750             {
5751               error ("%qD is thread-local and so cannot be dynamically "
5752                      "initialized", decl);
5753               init = NULL_TREE;
5754             }
5755
5756           /* Check that the initializer for a static data member was a
5757              constant.  Although we check in the parser that the
5758              initializer is an integral constant expression, we do not
5759              simplify division-by-zero at the point at which it
5760              occurs.  Therefore, in:
5761
5762                struct S { static const int i = 7 / 0; };
5763
5764              we issue an error at this point.  It would
5765              probably be better to forbid division by zero in
5766              integral constant expressions.  */
5767           if (DECL_EXTERNAL (decl) && init)
5768             {
5769               error ("%qD cannot be initialized by a non-constant expression"
5770                      " when being declared", decl);
5771               DECL_INITIALIZED_IN_CLASS_P (decl) = 0;
5772               init = NULL_TREE;
5773             }
5774
5775           /* Handle:
5776
5777              [dcl.init]
5778
5779              The memory occupied by any object of static storage
5780              duration is zero-initialized at program startup before
5781              any other initialization takes place.
5782
5783              We cannot create an appropriate initializer until after
5784              the type of DECL is finalized.  If DECL_INITIAL is set,
5785              then the DECL is statically initialized, and any
5786              necessary zero-initialization has already been performed.  */
5787           if (TREE_STATIC (decl) && !DECL_INITIAL (decl))
5788             DECL_INITIAL (decl) = build_zero_init (TREE_TYPE (decl),
5789                                                    /*nelts=*/NULL_TREE,
5790                                                    /*static_storage_p=*/true);
5791           /* Remember that the initialization for this variable has
5792              taken place.  */
5793           DECL_INITIALIZED_P (decl) = 1;
5794           /* This declaration is the definition of this variable,
5795              unless we are initializing a static data member within
5796              the class specifier.  */
5797           if (!DECL_EXTERNAL (decl))
5798             var_definition_p = true;
5799         }
5800       /* If the variable has an array type, lay out the type, even if
5801          there is no initializer.  It is valid to index through the
5802          array, and we must get TYPE_ALIGN set correctly on the array
5803          type.  */
5804       else if (TREE_CODE (type) == ARRAY_TYPE)
5805         layout_type (type);
5806     }
5807   else if (TREE_CODE (decl) == FIELD_DECL
5808            && TYPE_FOR_JAVA (type) && MAYBE_CLASS_TYPE_P (type))
5809     error ("non-static data member %qD has Java class type", decl);
5810
5811   /* Add this declaration to the statement-tree.  This needs to happen
5812      after the call to check_initializer so that the DECL_EXPR for a
5813      reference temp is added before the DECL_EXPR for the reference itself.  */
5814   if (at_function_scope_p ())
5815     add_decl_expr (decl);
5816
5817   /* Let the middle end know about variables and functions -- but not
5818      static data members in uninstantiated class templates.  */
5819   if (!saved_processing_template_decl
5820       && (TREE_CODE (decl) == VAR_DECL 
5821           || TREE_CODE (decl) == FUNCTION_DECL))
5822     {
5823       if (TREE_CODE (decl) == VAR_DECL)
5824         {
5825           layout_var_decl (decl);
5826           maybe_commonize_var (decl);
5827         }
5828
5829       /* This needs to happen after the linkage is set. */
5830       determine_visibility (decl);
5831
5832       if (var_definition_p && TREE_STATIC (decl))
5833         {
5834           /* If a TREE_READONLY variable needs initialization
5835              at runtime, it is no longer readonly and we need to
5836              avoid MEM_READONLY_P being set on RTL created for it.  */
5837           if (init)
5838             {
5839               if (TREE_READONLY (decl))
5840                 TREE_READONLY (decl) = 0;
5841               was_readonly = 0;
5842             }
5843           else if (was_readonly)
5844             TREE_READONLY (decl) = 1;
5845         }
5846
5847       make_rtl_for_nonlocal_decl (decl, init, asmspec);
5848
5849       /* Check for abstractness of the type. Notice that there is no
5850          need to strip array types here since the check for those types
5851          is already done within create_array_type_for_decl.  */
5852       if (TREE_CODE (type) == FUNCTION_TYPE
5853           || TREE_CODE (type) == METHOD_TYPE)
5854         abstract_virtuals_error (decl, TREE_TYPE (type));
5855       else
5856         abstract_virtuals_error (decl, type);
5857
5858       if (TREE_TYPE (decl) == error_mark_node)
5859         /* No initialization required.  */
5860         ;
5861       else if (TREE_CODE (decl) == FUNCTION_DECL)
5862         {
5863           if (init)
5864             {
5865               if (init == ridpointers[(int)RID_DEFAULT])
5866                 {
5867                   /* An out-of-class default definition is defined at
5868                      the point where it is explicitly defaulted.  */
5869                   if (DECL_INITIAL (decl) == error_mark_node)
5870                     synthesize_method (decl);
5871                 }
5872               else
5873                 error ("function %q#D is initialized like a variable", decl);
5874             }
5875           /* else no initialization required.  */
5876         }
5877       else if (DECL_EXTERNAL (decl)
5878                && ! (DECL_LANG_SPECIFIC (decl)
5879                      && DECL_NOT_REALLY_EXTERN (decl)))
5880         {
5881           if (init)
5882             DECL_INITIAL (decl) = init;
5883         }
5884       /* A variable definition.  */
5885       else if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
5886         /* Initialize the local variable.  */
5887         initialize_local_var (decl, init);
5888
5889       /* If a variable is defined, and then a subsequent
5890          definition with external linkage is encountered, we will
5891          get here twice for the same variable.  We want to avoid
5892          calling expand_static_init more than once.  For variables
5893          that are not static data members, we can call
5894          expand_static_init only when we actually process the
5895          initializer.  It is not legal to redeclare a static data
5896          member, so this issue does not arise in that case.  */
5897       else if (var_definition_p && TREE_STATIC (decl))
5898         expand_static_init (decl, init);
5899     }
5900
5901   /* If a CLEANUP_STMT was created to destroy a temporary bound to a
5902      reference, insert it in the statement-tree now.  */
5903   if (cleanup)
5904     push_cleanup (decl, cleanup, false);
5905
5906  finish_end:
5907   processing_template_decl = saved_processing_template_decl;
5908
5909   if (was_readonly)
5910     TREE_READONLY (decl) = 1;
5911
5912   /* If this was marked 'used', be sure it will be output.  */
5913   if (lookup_attribute ("used", DECL_ATTRIBUTES (decl)))
5914     mark_decl_referenced (decl);
5915 }
5916
5917 /* Returns a declaration for a VAR_DECL as if:
5918
5919      extern "C" TYPE NAME;
5920
5921    had been seen.  Used to create compiler-generated global
5922    variables.  */
5923
5924 static tree
5925 declare_global_var (tree name, tree type)
5926 {
5927   tree decl;
5928
5929   push_to_top_level ();
5930   decl = build_decl (input_location, VAR_DECL, name, type);
5931   TREE_PUBLIC (decl) = 1;
5932   DECL_EXTERNAL (decl) = 1;
5933   DECL_ARTIFICIAL (decl) = 1;
5934   /* If the user has explicitly declared this variable (perhaps
5935      because the code we are compiling is part of a low-level runtime
5936      library), then it is possible that our declaration will be merged
5937      with theirs by pushdecl.  */
5938   decl = pushdecl (decl);
5939   cp_finish_decl (decl, NULL_TREE, false, NULL_TREE, 0);
5940   pop_from_top_level ();
5941
5942   return decl;
5943 }
5944
5945 /* Returns the type for the argument to "__cxa_atexit" (or "atexit",
5946    if "__cxa_atexit" is not being used) corresponding to the function
5947    to be called when the program exits.  */
5948
5949 static tree
5950 get_atexit_fn_ptr_type (void)
5951 {
5952   tree arg_types;
5953   tree fn_type;
5954
5955   if (!atexit_fn_ptr_type_node)
5956     {
5957       if (flag_use_cxa_atexit 
5958           && !targetm.cxx.use_atexit_for_cxa_atexit ())
5959         /* The parameter to "__cxa_atexit" is "void (*)(void *)".  */
5960         arg_types = tree_cons (NULL_TREE, ptr_type_node, void_list_node);
5961       else
5962         /* The parameter to "atexit" is "void (*)(void)".  */
5963         arg_types = void_list_node;
5964       
5965       fn_type = build_function_type (void_type_node, arg_types);
5966       atexit_fn_ptr_type_node = build_pointer_type (fn_type);
5967     }
5968
5969   return atexit_fn_ptr_type_node;
5970 }
5971
5972 /* Returns a pointer to the `atexit' function.  Note that if
5973    FLAG_USE_CXA_ATEXIT is nonzero, then this will actually be the new
5974    `__cxa_atexit' function specified in the IA64 C++ ABI.  */
5975
5976 static tree
5977 get_atexit_node (void)
5978 {
5979   tree atexit_fndecl;
5980   tree arg_types;
5981   tree fn_type;
5982   tree fn_ptr_type;
5983   const char *name;
5984   bool use_aeabi_atexit;
5985
5986   if (atexit_node)
5987     return atexit_node;
5988
5989   if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
5990     {
5991       /* The declaration for `__cxa_atexit' is:
5992
5993            int __cxa_atexit (void (*)(void *), void *, void *)
5994
5995          We build up the argument types and then then function type
5996          itself.  */
5997
5998       use_aeabi_atexit = targetm.cxx.use_aeabi_atexit ();
5999       /* First, build the pointer-to-function type for the first
6000          argument.  */
6001       fn_ptr_type = get_atexit_fn_ptr_type ();
6002       /* Then, build the rest of the argument types.  */
6003       arg_types = tree_cons (NULL_TREE, ptr_type_node, void_list_node);
6004       if (use_aeabi_atexit)
6005         {
6006           arg_types = tree_cons (NULL_TREE, fn_ptr_type, arg_types);
6007           arg_types = tree_cons (NULL_TREE, ptr_type_node, arg_types);
6008         }
6009       else
6010         {
6011           arg_types = tree_cons (NULL_TREE, ptr_type_node, arg_types);
6012           arg_types = tree_cons (NULL_TREE, fn_ptr_type, arg_types);
6013         }
6014       /* And the final __cxa_atexit type.  */
6015       fn_type = build_function_type (integer_type_node, arg_types);
6016       fn_ptr_type = build_pointer_type (fn_type);
6017       if (use_aeabi_atexit)
6018         name = "__aeabi_atexit";
6019       else
6020         name = "__cxa_atexit";
6021     }
6022   else
6023     {
6024       /* The declaration for `atexit' is:
6025
6026            int atexit (void (*)());
6027
6028          We build up the argument types and then then function type
6029          itself.  */
6030       fn_ptr_type = get_atexit_fn_ptr_type ();
6031       arg_types = tree_cons (NULL_TREE, fn_ptr_type, void_list_node);
6032       /* Build the final atexit type.  */
6033       fn_type = build_function_type (integer_type_node, arg_types);
6034       name = "atexit";
6035     }
6036
6037   /* Now, build the function declaration.  */
6038   push_lang_context (lang_name_c);
6039   atexit_fndecl = build_library_fn_ptr (name, fn_type);
6040   mark_used (atexit_fndecl);
6041   pop_lang_context ();
6042   atexit_node = decay_conversion (atexit_fndecl);
6043
6044   return atexit_node;
6045 }
6046
6047 /* Returns the __dso_handle VAR_DECL.  */
6048
6049 static tree
6050 get_dso_handle_node (void)
6051 {
6052   if (dso_handle_node)
6053     return dso_handle_node;
6054
6055   /* Declare the variable.  */
6056   dso_handle_node = declare_global_var (get_identifier ("__dso_handle"),
6057                                         ptr_type_node);
6058
6059   return dso_handle_node;
6060 }
6061
6062 /* Begin a new function with internal linkage whose job will be simply
6063    to destroy some particular variable.  */
6064
6065 static GTY(()) int start_cleanup_cnt;
6066
6067 static tree
6068 start_cleanup_fn (void)
6069 {
6070   char name[32];
6071   tree fntype;
6072   tree fndecl;
6073   bool use_cxa_atexit = flag_use_cxa_atexit
6074                         && !targetm.cxx.use_atexit_for_cxa_atexit ();
6075
6076   push_to_top_level ();
6077
6078   /* No need to mangle this.  */
6079   push_lang_context (lang_name_c);
6080
6081   /* Build the name of the function.  */
6082   sprintf (name, "__tcf_%d", start_cleanup_cnt++);
6083   /* Build the function declaration.  */
6084   fntype = TREE_TYPE (get_atexit_fn_ptr_type ());
6085   fndecl = build_lang_decl (FUNCTION_DECL, get_identifier (name), fntype);
6086   /* It's a function with internal linkage, generated by the
6087      compiler.  */
6088   TREE_PUBLIC (fndecl) = 0;
6089   DECL_ARTIFICIAL (fndecl) = 1;
6090   /* Make the function `inline' so that it is only emitted if it is
6091      actually needed.  It is unlikely that it will be inlined, since
6092      it is only called via a function pointer, but we avoid unnecessary
6093      emissions this way.  */
6094   DECL_DECLARED_INLINE_P (fndecl) = 1;
6095   DECL_INTERFACE_KNOWN (fndecl) = 1;
6096   /* Build the parameter.  */
6097   if (use_cxa_atexit)
6098     {
6099       tree parmdecl;
6100
6101       parmdecl = cp_build_parm_decl (NULL_TREE, ptr_type_node);
6102       DECL_CONTEXT (parmdecl) = fndecl;
6103       TREE_USED (parmdecl) = 1;
6104       DECL_ARGUMENTS (fndecl) = parmdecl;
6105     }
6106
6107   pushdecl (fndecl);
6108   start_preparsed_function (fndecl, NULL_TREE, SF_PRE_PARSED);
6109
6110   pop_lang_context ();
6111
6112   return current_function_decl;
6113 }
6114
6115 /* Finish the cleanup function begun by start_cleanup_fn.  */
6116
6117 static void
6118 end_cleanup_fn (void)
6119 {
6120   expand_or_defer_fn (finish_function (0));
6121
6122   pop_from_top_level ();
6123 }
6124
6125 /* Generate code to handle the destruction of DECL, an object with
6126    static storage duration.  */
6127
6128 tree
6129 register_dtor_fn (tree decl)
6130 {
6131   tree cleanup;
6132   tree compound_stmt;
6133   tree args;
6134   tree fcall;
6135   tree type;
6136   bool use_dtor;
6137
6138   type = TREE_TYPE (decl);
6139   if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
6140     return void_zero_node;
6141
6142   /* If we're using "__cxa_atexit" (or "__aeabi_atexit"), and DECL is
6143      a class object, we can just pass the destructor to
6144      "__cxa_atexit"; we don't have to build a temporary function to do
6145      the cleanup.  */
6146   use_dtor = (flag_use_cxa_atexit 
6147               && !targetm.cxx.use_atexit_for_cxa_atexit ()
6148               && CLASS_TYPE_P (type));
6149   if (use_dtor)
6150     {
6151       int idx;
6152
6153       /* Find the destructor.  */
6154       idx = lookup_fnfields_1 (type, complete_dtor_identifier);
6155       gcc_assert (idx >= 0);
6156       cleanup = VEC_index (tree, CLASSTYPE_METHOD_VEC (type), idx);
6157       /* Make sure it is accessible.  */
6158       perform_or_defer_access_check (TYPE_BINFO (type), cleanup, cleanup);
6159     }
6160   else
6161     {
6162       /* Call build_cleanup before we enter the anonymous function so
6163          that any access checks will be done relative to the current
6164          scope, rather than the scope of the anonymous function.  */
6165       build_cleanup (decl);
6166   
6167       /* Now start the function.  */
6168       cleanup = start_cleanup_fn ();
6169       
6170       /* Now, recompute the cleanup.  It may contain SAVE_EXPRs that refer
6171          to the original function, rather than the anonymous one.  That
6172          will make the back end think that nested functions are in use,
6173          which causes confusion.  */
6174       push_deferring_access_checks (dk_no_check);
6175       fcall = build_cleanup (decl);
6176       pop_deferring_access_checks ();
6177       
6178       /* Create the body of the anonymous function.  */
6179       compound_stmt = begin_compound_stmt (BCS_FN_BODY);
6180       finish_expr_stmt (fcall);
6181       finish_compound_stmt (compound_stmt);
6182       end_cleanup_fn ();
6183     }
6184
6185   /* Call atexit with the cleanup function.  */
6186   mark_used (cleanup);
6187   cleanup = build_address (cleanup);
6188   if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
6189     {
6190       tree addr;
6191
6192       if (use_dtor)
6193         {
6194           /* We must convert CLEANUP to the type that "__cxa_atexit"
6195              expects.  */
6196           cleanup = build_nop (get_atexit_fn_ptr_type (), cleanup);
6197           /* "__cxa_atexit" will pass the address of DECL to the
6198              cleanup function.  */
6199           mark_used (decl);
6200           addr = build_address (decl);
6201           /* The declared type of the parameter to "__cxa_atexit" is
6202              "void *".  For plain "T*", we could just let the
6203              machinery in cp_build_function_call convert it -- but if the
6204              type is "cv-qualified T *", then we need to convert it
6205              before passing it in, to avoid spurious errors.  */
6206           addr = build_nop (ptr_type_node, addr);
6207         }
6208       else
6209         /* Since the cleanup functions we build ignore the address
6210            they're given, there's no reason to pass the actual address
6211            in, and, in general, it's cheaper to pass NULL than any
6212            other value.  */
6213         addr = null_pointer_node;
6214       args = tree_cons (NULL_TREE,
6215                         cp_build_unary_op (ADDR_EXPR, get_dso_handle_node (), 0,
6216                                         tf_warning_or_error),
6217                         NULL_TREE);
6218       if (targetm.cxx.use_aeabi_atexit ())
6219         {
6220           args = tree_cons (NULL_TREE, cleanup, args);
6221           args = tree_cons (NULL_TREE, addr, args);
6222         }
6223       else
6224         {
6225           args = tree_cons (NULL_TREE, addr, args);
6226           args = tree_cons (NULL_TREE, cleanup, args);
6227         }
6228     }
6229   else
6230     args = tree_cons (NULL_TREE, cleanup, NULL_TREE);
6231   return cp_build_function_call (get_atexit_node (), args, 
6232                                  tf_warning_or_error);
6233 }
6234
6235 /* DECL is a VAR_DECL with static storage duration.  INIT, if present,
6236    is its initializer.  Generate code to handle the construction
6237    and destruction of DECL.  */
6238
6239 static void
6240 expand_static_init (tree decl, tree init)
6241 {
6242   gcc_assert (TREE_CODE (decl) == VAR_DECL);
6243   gcc_assert (TREE_STATIC (decl));
6244
6245   /* Some variables require no initialization.  */
6246   if (!init
6247       && !TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (decl))
6248       && TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
6249     return;
6250
6251   if (DECL_FUNCTION_SCOPE_P (decl))
6252     {
6253       /* Emit code to perform this initialization but once.  */
6254       tree if_stmt = NULL_TREE, inner_if_stmt = NULL_TREE;
6255       tree then_clause = NULL_TREE, inner_then_clause = NULL_TREE;
6256       tree guard, guard_addr;
6257       tree acquire_fn, release_fn, abort_fn;
6258       tree flag, begin;
6259
6260       /* Emit code to perform this initialization but once.  This code
6261          looks like:
6262
6263            static <type> guard;
6264            if (!guard.first_byte) {
6265              if (__cxa_guard_acquire (&guard)) {
6266                bool flag = false;
6267                try {
6268                  // Do initialization.
6269                  flag = true; __cxa_guard_release (&guard);
6270                  // Register variable for destruction at end of program.
6271                } catch {
6272                  if (!flag) __cxa_guard_abort (&guard);
6273                }
6274            }
6275
6276          Note that the `flag' variable is only set to 1 *after* the
6277          initialization is complete.  This ensures that an exception,
6278          thrown during the construction, will cause the variable to
6279          reinitialized when we pass through this code again, as per:
6280
6281            [stmt.dcl]
6282
6283            If the initialization exits by throwing an exception, the
6284            initialization is not complete, so it will be tried again
6285            the next time control enters the declaration.
6286
6287          This process should be thread-safe, too; multiple threads
6288          should not be able to initialize the variable more than
6289          once.  */
6290
6291       /* Create the guard variable.  */
6292       guard = get_guard (decl);
6293
6294       /* This optimization isn't safe on targets with relaxed memory
6295          consistency.  On such targets we force synchronization in
6296          __cxa_guard_acquire.  */
6297       if (!targetm.relaxed_ordering || !flag_threadsafe_statics)
6298         {
6299           /* Begin the conditional initialization.  */
6300           if_stmt = begin_if_stmt ();
6301           finish_if_stmt_cond (get_guard_cond (guard), if_stmt);
6302           then_clause = begin_compound_stmt (BCS_NO_SCOPE);
6303         }
6304
6305       if (flag_threadsafe_statics)
6306         {
6307           guard_addr = build_address (guard);
6308
6309           acquire_fn = get_identifier ("__cxa_guard_acquire");
6310           release_fn = get_identifier ("__cxa_guard_release");
6311           abort_fn = get_identifier ("__cxa_guard_abort");
6312           if (!get_global_value_if_present (acquire_fn, &acquire_fn))
6313             {
6314               tree argtypes = tree_cons (NULL_TREE, TREE_TYPE (guard_addr),
6315                                          void_list_node);
6316               tree vfntype = build_function_type (void_type_node, argtypes);
6317               acquire_fn = push_library_fn
6318                 (acquire_fn, build_function_type (integer_type_node, argtypes),
6319                  NULL_TREE);
6320               release_fn = push_library_fn (release_fn, vfntype, NULL_TREE);
6321               abort_fn = push_library_fn (abort_fn, vfntype, NULL_TREE);
6322             }
6323           else
6324             {
6325               release_fn = identifier_global_value (release_fn);
6326               abort_fn = identifier_global_value (abort_fn);
6327             }
6328
6329           inner_if_stmt = begin_if_stmt ();
6330           finish_if_stmt_cond (build_call_n (acquire_fn, 1, guard_addr),
6331                                inner_if_stmt);
6332
6333           inner_then_clause = begin_compound_stmt (BCS_NO_SCOPE);
6334           begin = get_target_expr (boolean_false_node);
6335           flag = TARGET_EXPR_SLOT (begin);
6336
6337           TARGET_EXPR_CLEANUP (begin)
6338             = build3 (COND_EXPR, void_type_node, flag,
6339                       void_zero_node,
6340                       build_call_n (abort_fn, 1, guard_addr));
6341           CLEANUP_EH_ONLY (begin) = 1;
6342
6343           /* Do the initialization itself.  */
6344           init = add_stmt_to_compound (begin, init);
6345           init = add_stmt_to_compound
6346             (init, build2 (MODIFY_EXPR, void_type_node, flag, boolean_true_node));
6347           init = add_stmt_to_compound
6348             (init, build_call_n (release_fn, 1, guard_addr));
6349         }
6350       else
6351         init = add_stmt_to_compound (init, set_guard (guard));
6352
6353       /* Use atexit to register a function for destroying this static
6354          variable.  */
6355       init = add_stmt_to_compound (init, register_dtor_fn (decl));
6356
6357       finish_expr_stmt (init);
6358
6359       if (flag_threadsafe_statics)
6360         {
6361           finish_compound_stmt (inner_then_clause);
6362           finish_then_clause (inner_if_stmt);
6363           finish_if_stmt (inner_if_stmt);
6364         }
6365
6366       if (!targetm.relaxed_ordering || !flag_threadsafe_statics)
6367         {
6368           finish_compound_stmt (then_clause);
6369           finish_then_clause (if_stmt);
6370           finish_if_stmt (if_stmt);
6371         }
6372     }
6373   else
6374     static_aggregates = tree_cons (init, decl, static_aggregates);
6375 }
6376
6377 \f
6378 /* Make TYPE a complete type based on INITIAL_VALUE.
6379    Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
6380    2 if there was no information (in which case assume 0 if DO_DEFAULT),
6381    3 if the initializer list is empty (in pedantic mode). */
6382
6383 int
6384 cp_complete_array_type (tree *ptype, tree initial_value, bool do_default)
6385 {
6386   int failure;
6387   tree type, elt_type;
6388
6389   if (initial_value)
6390     {
6391       unsigned HOST_WIDE_INT i;
6392       tree value;
6393
6394       /* An array of character type can be initialized from a
6395          brace-enclosed string constant.
6396
6397          FIXME: this code is duplicated from reshape_init. Probably
6398          we should just call reshape_init here?  */
6399       if (char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (*ptype)))
6400           && TREE_CODE (initial_value) == CONSTRUCTOR
6401           && !VEC_empty (constructor_elt, CONSTRUCTOR_ELTS (initial_value)))
6402         {
6403           VEC(constructor_elt,gc) *v = CONSTRUCTOR_ELTS (initial_value);
6404           tree value = VEC_index (constructor_elt, v, 0)->value;
6405
6406           if (TREE_CODE (value) == STRING_CST
6407               && VEC_length (constructor_elt, v) == 1)
6408             initial_value = value;
6409         }
6410
6411       /* If any of the elements are parameter packs, we can't actually
6412          complete this type now because the array size is dependent.  */
6413       if (TREE_CODE (initial_value) == CONSTRUCTOR)
6414         {
6415           FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (initial_value), 
6416                                       i, value)
6417             {
6418               if (PACK_EXPANSION_P (value))
6419                 return 0;
6420             }
6421         }
6422     }
6423
6424   failure = complete_array_type (ptype, initial_value, do_default);
6425
6426   /* We can create the array before the element type is complete, which
6427      means that we didn't have these two bits set in the original type
6428      either.  In completing the type, we are expected to propagate these
6429      bits.  See also complete_type which does the same thing for arrays
6430      of fixed size.  */
6431   type = *ptype;
6432   if (TYPE_DOMAIN (type))
6433     {
6434       elt_type = TREE_TYPE (type);
6435       TYPE_NEEDS_CONSTRUCTING (type) = TYPE_NEEDS_CONSTRUCTING (elt_type);
6436       TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
6437         = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (elt_type);
6438     }
6439
6440   return failure;
6441 }
6442 \f
6443 /* Return zero if something is declared to be a member of type
6444    CTYPE when in the context of CUR_TYPE.  STRING is the error
6445    message to print in that case.  Otherwise, quietly return 1.  */
6446
6447 static int
6448 member_function_or_else (tree ctype, tree cur_type, enum overload_flags flags)
6449 {
6450   if (ctype && ctype != cur_type)
6451     {
6452       if (flags == DTOR_FLAG)
6453         error ("destructor for alien class %qT cannot be a member", ctype);
6454       else
6455         error ("constructor for alien class %qT cannot be a member", ctype);
6456       return 0;
6457     }
6458   return 1;
6459 }
6460 \f
6461 /* Subroutine of `grokdeclarator'.  */
6462
6463 /* Generate errors possibly applicable for a given set of specifiers.
6464    This is for ARM $7.1.2.  */
6465
6466 static void
6467 bad_specifiers (tree object,
6468                 const char* type,
6469                 int virtualp,
6470                 int quals,
6471                 int inlinep,
6472                 int friendp,
6473                 int raises)
6474 {
6475   if (virtualp)
6476     error ("%qD declared as a %<virtual%> %s", object, type);
6477   if (inlinep)
6478     error ("%qD declared as an %<inline%> %s", object, type);
6479   if (quals)
6480     error ("%<const%> and %<volatile%> function specifiers on "
6481            "%qD invalid in %s declaration",
6482            object, type);
6483   if (friendp)
6484     error ("%q+D declared as a friend", object);
6485   if (raises
6486       && (TREE_CODE (object) == TYPE_DECL
6487           || (!TYPE_PTRFN_P (TREE_TYPE (object))
6488               && !TYPE_REFFN_P (TREE_TYPE (object))
6489               && !TYPE_PTRMEMFUNC_P (TREE_TYPE (object)))))
6490     error ("%q+D declared with an exception specification", object);
6491 }
6492
6493 /* DECL is a member function or static data member and is presently
6494    being defined.  Check that the definition is taking place in a
6495    valid namespace.  */
6496
6497 static void
6498 check_class_member_definition_namespace (tree decl)
6499 {
6500   /* These checks only apply to member functions and static data
6501      members.  */
6502   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
6503               || TREE_CODE (decl) == VAR_DECL);
6504   /* We check for problems with specializations in pt.c in
6505      check_specialization_namespace, where we can issue better
6506      diagnostics.  */
6507   if (processing_specialization)
6508     return;
6509   /* There are no restrictions on the placement of
6510      explicit instantiations.  */
6511   if (processing_explicit_instantiation)
6512     return;
6513   /* [class.mfct]
6514
6515      A member function definition that appears outside of the
6516      class definition shall appear in a namespace scope enclosing
6517      the class definition.
6518
6519      [class.static.data]
6520
6521      The definition for a static data member shall appear in a
6522      namespace scope enclosing the member's class definition.  */
6523   if (!is_ancestor (current_namespace, DECL_CONTEXT (decl)))
6524     permerror (input_location, "definition of %qD is not in namespace enclosing %qT",
6525                decl, DECL_CONTEXT (decl));
6526 }
6527
6528 /* Build a PARM_DECL for the "this" parameter.  TYPE is the
6529    METHOD_TYPE for a non-static member function; QUALS are the
6530    cv-qualifiers that apply to the function.  */
6531
6532 tree
6533 build_this_parm (tree type, cp_cv_quals quals)
6534 {
6535   tree this_type;
6536   tree qual_type;
6537   tree parm;
6538   cp_cv_quals this_quals;
6539
6540   this_type = TREE_VALUE (TYPE_ARG_TYPES (type));
6541   /* The `this' parameter is implicitly `const'; it cannot be
6542      assigned to.  */
6543   this_quals = (quals & TYPE_QUAL_RESTRICT) | TYPE_QUAL_CONST;
6544   qual_type = cp_build_qualified_type (this_type, this_quals);
6545   parm = build_artificial_parm (this_identifier, qual_type);
6546   cp_apply_type_quals_to_decl (this_quals, parm);
6547   return parm;
6548 }
6549
6550 /* CTYPE is class type, or null if non-class.
6551    TYPE is type this FUNCTION_DECL should have, either FUNCTION_TYPE
6552    or METHOD_TYPE.
6553    DECLARATOR is the function's name.
6554    PARMS is a chain of PARM_DECLs for the function.
6555    VIRTUALP is truthvalue of whether the function is virtual or not.
6556    FLAGS are to be passed through to `grokclassfn'.
6557    QUALS are qualifiers indicating whether the function is `const'
6558    or `volatile'.
6559    RAISES is a list of exceptions that this function can raise.
6560    CHECK is 1 if we must find this method in CTYPE, 0 if we should
6561    not look, and -1 if we should not call `grokclassfn' at all.
6562
6563    SFK is the kind of special function (if any) for the new function.
6564
6565    Returns `NULL_TREE' if something goes wrong, after issuing
6566    applicable error messages.  */
6567
6568 static tree
6569 grokfndecl (tree ctype,
6570             tree type,
6571             tree declarator,
6572             tree parms,
6573             tree orig_declarator,
6574             int virtualp,
6575             enum overload_flags flags,
6576             cp_cv_quals quals,
6577             tree raises,
6578             int check,
6579             int friendp,
6580             int publicp,
6581             int inlinep,
6582             special_function_kind sfk,
6583             bool funcdef_flag,
6584             int template_count,
6585             tree in_namespace,
6586             tree* attrlist,
6587             location_t location)
6588 {
6589   tree decl;
6590   int staticp = ctype && TREE_CODE (type) == FUNCTION_TYPE;
6591   tree t;
6592
6593   if (raises)
6594     type = build_exception_variant (type, raises);
6595
6596   decl = build_lang_decl (FUNCTION_DECL, declarator, type);
6597
6598   /* If we have an explicit location, use it, otherwise use whatever
6599      build_lang_decl used (probably input_location).  */
6600   if (location != UNKNOWN_LOCATION)
6601     DECL_SOURCE_LOCATION (decl) = location;
6602
6603   if (TREE_CODE (type) == METHOD_TYPE)
6604     {
6605       tree parm;
6606       parm = build_this_parm (type, quals);
6607       TREE_CHAIN (parm) = parms;
6608       parms = parm;
6609     }
6610   DECL_ARGUMENTS (decl) = parms;
6611   for (t = parms; t; t = TREE_CHAIN (t))
6612     DECL_CONTEXT (t) = decl;
6613   /* Propagate volatile out from type to decl.  */
6614   if (TYPE_VOLATILE (type))
6615     TREE_THIS_VOLATILE (decl) = 1;
6616
6617   /* Setup decl according to sfk.  */
6618   switch (sfk)
6619     {
6620     case sfk_constructor:
6621     case sfk_copy_constructor:
6622       DECL_CONSTRUCTOR_P (decl) = 1;
6623       break;
6624     case sfk_destructor:
6625       DECL_DESTRUCTOR_P (decl) = 1;
6626       break;
6627     default:
6628       break;
6629     }
6630
6631   /* If pointers to member functions use the least significant bit to
6632      indicate whether a function is virtual, ensure a pointer
6633      to this function will have that bit clear.  */
6634   if (TARGET_PTRMEMFUNC_VBIT_LOCATION == ptrmemfunc_vbit_in_pfn
6635       && TREE_CODE (type) == METHOD_TYPE
6636       && DECL_ALIGN (decl) < 2 * BITS_PER_UNIT)
6637     DECL_ALIGN (decl) = 2 * BITS_PER_UNIT;
6638
6639   if (friendp
6640       && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)
6641     {
6642       if (funcdef_flag)
6643         error
6644           ("defining explicit specialization %qD in friend declaration",
6645            orig_declarator);
6646       else
6647         {
6648           tree fns = TREE_OPERAND (orig_declarator, 0);
6649           tree args = TREE_OPERAND (orig_declarator, 1);
6650
6651           if (PROCESSING_REAL_TEMPLATE_DECL_P ())
6652             {
6653               /* Something like `template <class T> friend void f<T>()'.  */
6654               error ("invalid use of template-id %qD in declaration "
6655                      "of primary template",
6656                      orig_declarator);
6657               return NULL_TREE;
6658             }
6659
6660
6661           /* A friend declaration of the form friend void f<>().  Record
6662              the information in the TEMPLATE_ID_EXPR.  */
6663           SET_DECL_IMPLICIT_INSTANTIATION (decl);
6664
6665           if (TREE_CODE (fns) == COMPONENT_REF)
6666             {
6667               /* Due to bison parser ickiness, we will have already looked
6668                  up an operator_name or PFUNCNAME within the current class
6669                  (see template_id in parse.y). If the current class contains
6670                  such a name, we'll get a COMPONENT_REF here. Undo that.  */
6671
6672               gcc_assert (TREE_TYPE (TREE_OPERAND (fns, 0))
6673                           == current_class_type);
6674               fns = TREE_OPERAND (fns, 1);
6675             }
6676           gcc_assert (TREE_CODE (fns) == IDENTIFIER_NODE
6677                       || TREE_CODE (fns) == OVERLOAD);
6678           DECL_TEMPLATE_INFO (decl) = tree_cons (fns, args, NULL_TREE);
6679
6680           for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
6681             if (TREE_PURPOSE (t)
6682                 && TREE_CODE (TREE_PURPOSE (t)) == DEFAULT_ARG)
6683             {
6684               error ("default arguments are not allowed in declaration "
6685                      "of friend template specialization %qD",
6686                      decl);
6687               return NULL_TREE;
6688             }
6689
6690           if (inlinep)
6691             {
6692               error ("%<inline%> is not allowed in declaration of friend "
6693                      "template specialization %qD",
6694                      decl);
6695               return NULL_TREE;
6696             }
6697         }
6698     }
6699
6700   /* If this decl has namespace scope, set that up.  */
6701   if (in_namespace)
6702     set_decl_namespace (decl, in_namespace, friendp);
6703   else if (!ctype)
6704     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
6705
6706   /* `main' and builtins have implicit 'C' linkage.  */
6707   if ((MAIN_NAME_P (declarator)
6708        || (IDENTIFIER_LENGTH (declarator) > 10
6709            && IDENTIFIER_POINTER (declarator)[0] == '_'
6710            && IDENTIFIER_POINTER (declarator)[1] == '_'
6711            && strncmp (IDENTIFIER_POINTER (declarator)+2, "builtin_", 8) == 0))
6712       && current_lang_name == lang_name_cplusplus
6713       && ctype == NULL_TREE
6714       /* NULL_TREE means global namespace.  */
6715       && DECL_CONTEXT (decl) == NULL_TREE)
6716     SET_DECL_LANGUAGE (decl, lang_c);
6717
6718   /* Should probably propagate const out from type to decl I bet (mrs).  */
6719   if (staticp)
6720     {
6721       DECL_STATIC_FUNCTION_P (decl) = 1;
6722       DECL_CONTEXT (decl) = ctype;
6723     }
6724
6725   if (ctype)
6726     {
6727       DECL_CONTEXT (decl) = ctype;
6728       if (funcdef_flag)
6729         check_class_member_definition_namespace (decl);
6730     }
6731
6732   if (ctype == NULL_TREE && DECL_MAIN_P (decl))
6733     {
6734       if (processing_template_decl)
6735         error ("cannot declare %<::main%> to be a template");
6736       if (inlinep)
6737         error ("cannot declare %<::main%> to be inline");
6738       if (!publicp)
6739         error ("cannot declare %<::main%> to be static");
6740       inlinep = 0;
6741       publicp = 1;
6742     }
6743
6744   /* Members of anonymous types and local classes have no linkage; make
6745      them internal.  If a typedef is made later, this will be changed.  */
6746   if (ctype && (TYPE_ANONYMOUS_P (ctype)
6747                 || decl_function_context (TYPE_MAIN_DECL (ctype))))
6748     publicp = 0;
6749
6750   TREE_PUBLIC (decl) = publicp;
6751   if (! publicp)
6752     {
6753       DECL_INTERFACE_KNOWN (decl) = 1;
6754       DECL_NOT_REALLY_EXTERN (decl) = 1;
6755     }
6756
6757   /* If the declaration was declared inline, mark it as such.  */
6758   if (inlinep)
6759     DECL_DECLARED_INLINE_P (decl) = 1;
6760
6761   DECL_EXTERNAL (decl) = 1;
6762   if (quals && TREE_CODE (type) == FUNCTION_TYPE)
6763     {
6764       error (ctype
6765              ? G_("static member function %qD cannot have cv-qualifier")
6766              : G_("non-member function %qD cannot have cv-qualifier"),
6767              decl);
6768       quals = TYPE_UNQUALIFIED;
6769     }
6770
6771   if (IDENTIFIER_OPNAME_P (DECL_NAME (decl))
6772       && !grok_op_properties (decl, /*complain=*/true))
6773     return NULL_TREE;
6774
6775   if (ctype && decl_function_context (decl))
6776     DECL_NO_STATIC_CHAIN (decl) = 1;
6777
6778   if (funcdef_flag)
6779     /* Make the init_value nonzero so pushdecl knows this is not
6780        tentative.  error_mark_node is replaced later with the BLOCK.  */
6781     DECL_INITIAL (decl) = error_mark_node;
6782
6783   if (TYPE_NOTHROW_P (type) || nothrow_libfn_p (decl))
6784     TREE_NOTHROW (decl) = 1;
6785
6786   /* Caller will do the rest of this.  */
6787   if (check < 0)
6788     return decl;
6789
6790   if (ctype != NULL_TREE)
6791     grokclassfn (ctype, decl, flags);
6792
6793   decl = check_explicit_specialization (orig_declarator, decl,
6794                                         template_count,
6795                                         2 * funcdef_flag +
6796                                         4 * (friendp != 0));
6797   if (decl == error_mark_node)
6798     return NULL_TREE;
6799
6800   if (attrlist)
6801     {
6802       cplus_decl_attributes (&decl, *attrlist, 0);
6803       *attrlist = NULL_TREE;
6804     }
6805
6806   /* Check main's type after attributes have been applied.  */
6807   if (ctype == NULL_TREE && DECL_MAIN_P (decl))
6808     {
6809       if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
6810                         integer_type_node))
6811         {
6812           tree oldtypeargs = TYPE_ARG_TYPES (TREE_TYPE (decl));
6813           tree newtype;
6814           error ("%<::main%> must return %<int%>");
6815           newtype = build_function_type (integer_type_node, oldtypeargs);
6816           TREE_TYPE (decl) = newtype;
6817         }
6818       if (warn_main)
6819         check_main_parameter_types (decl);
6820     }
6821
6822   if (ctype != NULL_TREE
6823       && (! TYPE_FOR_JAVA (ctype) || check_java_method (decl))
6824       && check)
6825     {
6826       tree old_decl = check_classfn (ctype, decl,
6827                                      (processing_template_decl
6828                                       > template_class_depth (ctype))
6829                                      ? current_template_parms
6830                                      : NULL_TREE);
6831
6832       if (old_decl == error_mark_node)
6833         return NULL_TREE;
6834
6835       if (old_decl)
6836         {
6837           tree ok;
6838           tree pushed_scope;
6839
6840           if (TREE_CODE (old_decl) == TEMPLATE_DECL)
6841             /* Because grokfndecl is always supposed to return a
6842                FUNCTION_DECL, we pull out the DECL_TEMPLATE_RESULT
6843                here.  We depend on our callers to figure out that its
6844                really a template that's being returned.  */
6845             old_decl = DECL_TEMPLATE_RESULT (old_decl);
6846
6847           if (DECL_STATIC_FUNCTION_P (old_decl)
6848               && TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
6849             /* Remove the `this' parm added by grokclassfn.
6850                XXX Isn't this done in start_function, too?  */
6851             revert_static_member_fn (decl);
6852           if (DECL_ARTIFICIAL (old_decl))
6853             {
6854               error ("definition of implicitly-declared %qD", old_decl);
6855               return NULL_TREE;
6856             }
6857
6858           /* Since we've smashed OLD_DECL to its
6859              DECL_TEMPLATE_RESULT, we must do the same to DECL.  */
6860           if (TREE_CODE (decl) == TEMPLATE_DECL)
6861             decl = DECL_TEMPLATE_RESULT (decl);
6862
6863           /* Attempt to merge the declarations.  This can fail, in
6864              the case of some invalid specialization declarations.  */
6865           pushed_scope = push_scope (ctype);
6866           ok = duplicate_decls (decl, old_decl, friendp);
6867           if (pushed_scope)
6868             pop_scope (pushed_scope);
6869           if (!ok)
6870             {
6871               error ("no %q#D member function declared in class %qT",
6872                      decl, ctype);
6873               return NULL_TREE;
6874             }
6875           return old_decl;
6876         }
6877     }
6878
6879   if (DECL_CONSTRUCTOR_P (decl) && !grok_ctor_properties (ctype, decl))
6880     return NULL_TREE;
6881
6882   if (ctype == NULL_TREE || check)
6883     return decl;
6884
6885   if (virtualp)
6886     DECL_VIRTUAL_P (decl) = 1;
6887
6888   return decl;
6889 }
6890
6891 /* DECL is a VAR_DECL for a static data member.  Set flags to reflect
6892    the linkage that DECL will receive in the object file.  */
6893
6894 static void
6895 set_linkage_for_static_data_member (tree decl)
6896 {
6897   /* A static data member always has static storage duration and
6898      external linkage.  Note that static data members are forbidden in
6899      local classes -- the only situation in which a class has
6900      non-external linkage.  */
6901   TREE_PUBLIC (decl) = 1;
6902   TREE_STATIC (decl) = 1;
6903   /* For non-template classes, static data members are always put
6904      out in exactly those files where they are defined, just as
6905      with ordinary namespace-scope variables.  */
6906   if (!processing_template_decl)
6907     DECL_INTERFACE_KNOWN (decl) = 1;
6908 }
6909
6910 /* Create a VAR_DECL named NAME with the indicated TYPE.
6911
6912    If SCOPE is non-NULL, it is the class type or namespace containing
6913    the variable.  If SCOPE is NULL, the variable should is created in
6914    the innermost enclosings scope.  */
6915
6916 static tree
6917 grokvardecl (tree type,
6918              tree name,
6919              const cp_decl_specifier_seq *declspecs,
6920              int initialized,
6921              int constp,
6922              tree scope)
6923 {
6924   tree decl;
6925   tree explicit_scope;
6926
6927   gcc_assert (!name || TREE_CODE (name) == IDENTIFIER_NODE);
6928
6929   /* Compute the scope in which to place the variable, but remember
6930      whether or not that scope was explicitly specified by the user.   */
6931   explicit_scope = scope;
6932   if (!scope)
6933     {
6934       /* An explicit "extern" specifier indicates a namespace-scope
6935          variable.  */
6936       if (declspecs->storage_class == sc_extern)
6937         scope = current_namespace;
6938       else if (!at_function_scope_p ())
6939         scope = current_scope ();
6940     }
6941
6942   if (scope
6943       && (/* If the variable is a namespace-scope variable declared in a
6944              template, we need DECL_LANG_SPECIFIC.  */
6945           (TREE_CODE (scope) == NAMESPACE_DECL && processing_template_decl)
6946           /* Similarly for namespace-scope variables with language linkage
6947              other than C++.  */
6948           || (TREE_CODE (scope) == NAMESPACE_DECL
6949               && current_lang_name != lang_name_cplusplus)
6950           /* Similarly for static data members.  */
6951           || TYPE_P (scope)))
6952     decl = build_lang_decl (VAR_DECL, name, type);
6953   else
6954     decl = build_decl (input_location, VAR_DECL, name, type);
6955
6956   if (explicit_scope && TREE_CODE (explicit_scope) == NAMESPACE_DECL)
6957     set_decl_namespace (decl, explicit_scope, 0);
6958   else
6959     DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
6960
6961   if (declspecs->storage_class == sc_extern)
6962     {
6963       DECL_THIS_EXTERN (decl) = 1;
6964       DECL_EXTERNAL (decl) = !initialized;
6965     }
6966
6967   if (DECL_CLASS_SCOPE_P (decl))
6968     {
6969       set_linkage_for_static_data_member (decl);
6970       /* This function is only called with out-of-class definitions.  */
6971       DECL_EXTERNAL (decl) = 0;
6972       check_class_member_definition_namespace (decl);
6973     }
6974   /* At top level, either `static' or no s.c. makes a definition
6975      (perhaps tentative), and absence of `static' makes it public.  */
6976   else if (toplevel_bindings_p ())
6977     {
6978       TREE_PUBLIC (decl) = (declspecs->storage_class != sc_static
6979                             && (DECL_THIS_EXTERN (decl) || ! constp));
6980       TREE_STATIC (decl) = ! DECL_EXTERNAL (decl);
6981     }
6982   /* Not at top level, only `static' makes a static definition.  */
6983   else
6984     {
6985       TREE_STATIC (decl) = declspecs->storage_class == sc_static;
6986       TREE_PUBLIC (decl) = DECL_EXTERNAL (decl);
6987     }
6988
6989   if (declspecs->specs[(int)ds_thread])
6990     DECL_TLS_MODEL (decl) = decl_default_tls_model (decl);
6991
6992   if (TREE_PUBLIC (decl))
6993     {
6994       /* If the type of the decl has no linkage, make sure that we'll
6995          notice that in mark_used.  */
6996       if (DECL_LANG_SPECIFIC (decl) == NULL
6997           && TREE_PUBLIC (decl)
6998           && !DECL_EXTERN_C_P (decl)
6999           && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
7000         retrofit_lang_decl (decl);
7001     }
7002   else
7003     DECL_INTERFACE_KNOWN (decl) = 1;
7004
7005   return decl;
7006 }
7007
7008 /* Create and return a canonical pointer to member function type, for
7009    TYPE, which is a POINTER_TYPE to a METHOD_TYPE.  */
7010
7011 tree
7012 build_ptrmemfunc_type (tree type)
7013 {
7014   tree field, fields;
7015   tree t;
7016   tree unqualified_variant = NULL_TREE;
7017
7018   if (type == error_mark_node)
7019     return type;
7020
7021   /* If a canonical type already exists for this type, use it.  We use
7022      this method instead of type_hash_canon, because it only does a
7023      simple equality check on the list of field members.  */
7024
7025   if ((t = TYPE_GET_PTRMEMFUNC_TYPE (type)))
7026     return t;
7027
7028   /* Make sure that we always have the unqualified pointer-to-member
7029      type first.  */
7030   if (cp_type_quals (type) != TYPE_UNQUALIFIED)
7031     unqualified_variant
7032       = build_ptrmemfunc_type (TYPE_MAIN_VARIANT (type));
7033
7034   t = make_class_type (RECORD_TYPE);
7035   xref_basetypes (t, NULL_TREE);
7036
7037   /* Let the front end know this is a pointer to member function...  */
7038   TYPE_PTRMEMFUNC_FLAG (t) = 1;
7039   /* ... and not really a class type.  */
7040   SET_CLASS_TYPE_P (t, 0);
7041
7042   field = build_decl (input_location, FIELD_DECL, pfn_identifier, type);
7043   fields = field;
7044
7045   field = build_decl (input_location, FIELD_DECL, delta_identifier, 
7046                       delta_type_node);
7047   TREE_CHAIN (field) = fields;
7048   fields = field;
7049
7050   finish_builtin_struct (t, "__ptrmemfunc_type", fields, ptr_type_node);
7051
7052   /* Zap out the name so that the back end will give us the debugging
7053      information for this anonymous RECORD_TYPE.  */
7054   TYPE_NAME (t) = NULL_TREE;
7055
7056   /* If this is not the unqualified form of this pointer-to-member
7057      type, set the TYPE_MAIN_VARIANT for this type to be the
7058      unqualified type.  Since they are actually RECORD_TYPEs that are
7059      not variants of each other, we must do this manually.
7060      As we just built a new type there is no need to do yet another copy.  */
7061   if (cp_type_quals (type) != TYPE_UNQUALIFIED)
7062     {
7063       int type_quals = cp_type_quals (type);
7064       TYPE_READONLY (t) = (type_quals & TYPE_QUAL_CONST) != 0;
7065       TYPE_VOLATILE (t) = (type_quals & TYPE_QUAL_VOLATILE) != 0;
7066       TYPE_RESTRICT (t) = (type_quals & TYPE_QUAL_RESTRICT) != 0;
7067       TYPE_MAIN_VARIANT (t) = unqualified_variant;
7068       TYPE_NEXT_VARIANT (t) = TYPE_NEXT_VARIANT (unqualified_variant);
7069       TYPE_NEXT_VARIANT (unqualified_variant) = t;
7070       TREE_TYPE (TYPE_BINFO (t)) = t;
7071     }
7072
7073   /* Cache this pointer-to-member type so that we can find it again
7074      later.  */
7075   TYPE_SET_PTRMEMFUNC_TYPE (type, t);
7076
7077   if (TYPE_STRUCTURAL_EQUALITY_P (type))
7078     SET_TYPE_STRUCTURAL_EQUALITY (t);
7079   else if (TYPE_CANONICAL (type) != type)
7080     TYPE_CANONICAL (t) = build_ptrmemfunc_type (TYPE_CANONICAL (type));
7081
7082   return t;
7083 }
7084
7085 /* Create and return a pointer to data member type.  */
7086
7087 tree
7088 build_ptrmem_type (tree class_type, tree member_type)
7089 {
7090   if (TREE_CODE (member_type) == METHOD_TYPE)
7091     {
7092       tree arg_types;
7093
7094       arg_types = TYPE_ARG_TYPES (member_type);
7095       class_type = (cp_build_qualified_type
7096                     (class_type,
7097                      cp_type_quals (TREE_TYPE (TREE_VALUE (arg_types)))));
7098       member_type
7099         = build_method_type_directly (class_type,
7100                                       TREE_TYPE (member_type),
7101                                       TREE_CHAIN (arg_types));
7102       return build_ptrmemfunc_type (build_pointer_type (member_type));
7103     }
7104   else
7105     {
7106       gcc_assert (TREE_CODE (member_type) != FUNCTION_TYPE);
7107       return build_offset_type (class_type, member_type);
7108     }
7109 }
7110
7111 /* DECL is a VAR_DECL defined in-class, whose TYPE is also given.
7112    Check to see that the definition is valid.  Issue appropriate error
7113    messages.  Return 1 if the definition is particularly bad, or 0
7114    otherwise.  */
7115
7116 int
7117 check_static_variable_definition (tree decl, tree type)
7118 {
7119   /* Motion 10 at San Diego: If a static const integral data member is
7120      initialized with an integral constant expression, the initializer
7121      may appear either in the declaration (within the class), or in
7122      the definition, but not both.  If it appears in the class, the
7123      member is a member constant.  The file-scope definition is always
7124      required.  */
7125   if (!ARITHMETIC_TYPE_P (type) && TREE_CODE (type) != ENUMERAL_TYPE)
7126     {
7127       error ("invalid in-class initialization of static data member "
7128              "of non-integral type %qT",
7129              type);
7130       /* If we just return the declaration, crashes will sometimes
7131          occur.  We therefore return void_type_node, as if this were a
7132          friend declaration, to cause callers to completely ignore
7133          this declaration.  */
7134       return 1;
7135     }
7136   else if (!CP_TYPE_CONST_P (type))
7137     error ("ISO C++ forbids in-class initialization of non-const "
7138            "static member %qD",
7139            decl);
7140   else if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type))
7141     pedwarn (input_location, OPT_pedantic, "ISO C++ forbids initialization of member constant "
7142              "%qD of non-integral type %qT", decl, type);
7143
7144   return 0;
7145 }
7146
7147 /* Given the SIZE (i.e., number of elements) in an array, compute an
7148    appropriate index type for the array.  If non-NULL, NAME is the
7149    name of the thing being declared.  */
7150
7151 tree
7152 compute_array_index_type (tree name, tree size)
7153 {
7154   tree type;
7155   tree itype;
7156   tree abi_1_itype = NULL_TREE;
7157
7158   if (error_operand_p (size))
7159     return error_mark_node;
7160
7161   type = TREE_TYPE (size);
7162   /* The array bound must be an integer type.  */
7163   if (!dependent_type_p (type) && !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
7164     {
7165       if (name)
7166         error ("size of array %qD has non-integral type %qT", name, type);
7167       else
7168         error ("size of array has non-integral type %qT", type);
7169       size = integer_one_node;
7170       type = TREE_TYPE (size);
7171     }
7172
7173   /* We can only call value_dependent_expression_p on integral constant
7174      expressions; the parser adds a dummy NOP_EXPR with TREE_SIDE_EFFECTS
7175      set if this isn't one.  */
7176   if (processing_template_decl
7177       && (TREE_SIDE_EFFECTS (size) || value_dependent_expression_p (size)))
7178     {
7179       /* We cannot do any checking for a SIZE that isn't known to be
7180          constant. Just build the index type and mark that it requires
7181          structural equality checks.  */
7182       itype = build_index_type (build_min (MINUS_EXPR, sizetype,
7183                                            size, integer_one_node));
7184       if (!TREE_SIDE_EFFECTS (size))
7185         {
7186           TYPE_DEPENDENT_P (itype) = 1;
7187           TYPE_DEPENDENT_P_VALID (itype) = 1;
7188         }
7189       SET_TYPE_STRUCTURAL_EQUALITY (itype);
7190       return itype;
7191     }
7192   
7193   if (!abi_version_at_least (2) && processing_template_decl)
7194     /* For abi-1, we handled all instances in templates the same way,
7195        even when they were non-dependent. This affects the manglings
7196        produced.  So, we do the normal checking for non-dependent
7197        sizes, but at the end we'll return the same type that abi-1
7198        would have, but with TYPE_CANONICAL set to the "right"
7199        value that the current ABI would provide. */
7200     abi_1_itype = build_index_type (build_min (MINUS_EXPR, sizetype,
7201                                                size, integer_one_node));
7202
7203   /* The size might be the result of a cast.  */
7204   STRIP_TYPE_NOPS (size);
7205
7206   /* It might be a const variable or enumeration constant.  */
7207   size = integral_constant_value (size);
7208
7209   /* Normally, the array-bound will be a constant.  */
7210   if (TREE_CODE (size) == INTEGER_CST)
7211     {
7212       /* Check to see if the array bound overflowed.  Make that an
7213          error, no matter how generous we're being.  */
7214       constant_expression_error (size);
7215
7216       /* An array must have a positive number of elements.  */
7217       if (INT_CST_LT (size, integer_zero_node))
7218         {
7219           if (name)
7220             error ("size of array %qD is negative", name);
7221           else
7222             error ("size of array is negative");
7223           size = integer_one_node;
7224         }
7225       /* As an extension we allow zero-sized arrays.  We always allow
7226          them in system headers because glibc uses them.  */
7227       else if (integer_zerop (size) && !in_system_header)
7228         {
7229           if (name)
7230             pedwarn (input_location, OPT_pedantic, "ISO C++ forbids zero-size array %qD", name);
7231           else
7232             pedwarn (input_location, OPT_pedantic, "ISO C++ forbids zero-size array");
7233         }
7234     }
7235   else if (TREE_CONSTANT (size))
7236     {
7237       /* `(int) &fn' is not a valid array bound.  */
7238       if (name)
7239         error ("size of array %qD is not an integral constant-expression",
7240                name);
7241       else
7242         error ("size of array is not an integral constant-expression");
7243       size = integer_one_node;
7244     }
7245   else if (pedantic && warn_vla != 0)
7246     {
7247       if (name)
7248         pedwarn (input_location, OPT_Wvla, "ISO C++ forbids variable length array %qD", name);
7249       else
7250         pedwarn (input_location, OPT_Wvla, "ISO C++ forbids variable length array");
7251     }
7252   else if (warn_vla > 0)
7253     {
7254       if (name)
7255         warning (OPT_Wvla, 
7256                  "variable length array %qD is used", name);
7257       else
7258         warning (OPT_Wvla, 
7259                  "variable length array is used");
7260     }
7261
7262   if (processing_template_decl && !TREE_CONSTANT (size))
7263     /* A variable sized array.  */
7264     itype = build_min (MINUS_EXPR, sizetype, size, integer_one_node);
7265   else
7266     {
7267       HOST_WIDE_INT saved_processing_template_decl;
7268
7269       /* Compute the index of the largest element in the array.  It is
7270          one less than the number of elements in the array.  We save
7271          and restore PROCESSING_TEMPLATE_DECL so that computations in
7272          cp_build_binary_op will be appropriately folded.  */
7273       saved_processing_template_decl = processing_template_decl;
7274       processing_template_decl = 0;
7275       itype = cp_build_binary_op (input_location,
7276                                   MINUS_EXPR,
7277                                   cp_convert (ssizetype, size),
7278                                   cp_convert (ssizetype, integer_one_node),
7279                                   tf_warning_or_error);
7280       itype = fold (itype);
7281       processing_template_decl = saved_processing_template_decl;
7282
7283       if (!TREE_CONSTANT (itype))
7284         /* A variable sized array.  */
7285         itype = variable_size (itype);
7286       /* Make sure that there was no overflow when creating to a signed
7287          index type.  (For example, on a 32-bit machine, an array with
7288          size 2^32 - 1 is too big.)  */
7289       else if (TREE_CODE (itype) == INTEGER_CST
7290                && TREE_OVERFLOW (itype))
7291         {
7292           error ("overflow in array dimension");
7293           TREE_OVERFLOW (itype) = 0;
7294         }
7295     }
7296
7297   /* Create and return the appropriate index type.  */
7298   if (abi_1_itype)
7299     {
7300       tree t = build_index_type (itype);
7301       TYPE_CANONICAL (abi_1_itype) = TYPE_CANONICAL (t);
7302       return abi_1_itype;
7303     }
7304   else
7305     return build_index_type (itype);
7306 }
7307
7308 /* Returns the scope (if any) in which the entity declared by
7309    DECLARATOR will be located.  If the entity was declared with an
7310    unqualified name, NULL_TREE is returned.  */
7311
7312 tree
7313 get_scope_of_declarator (const cp_declarator *declarator)
7314 {
7315   while (declarator && declarator->kind != cdk_id)
7316     declarator = declarator->declarator;
7317
7318   /* If the declarator-id is a SCOPE_REF, the scope in which the
7319      declaration occurs is the first operand.  */
7320   if (declarator
7321       && declarator->u.id.qualifying_scope)
7322     return declarator->u.id.qualifying_scope;
7323
7324   /* Otherwise, the declarator is not a qualified name; the entity will
7325      be declared in the current scope.  */
7326   return NULL_TREE;
7327 }
7328
7329 /* Returns an ARRAY_TYPE for an array with SIZE elements of the
7330    indicated TYPE.  If non-NULL, NAME is the NAME of the declaration
7331    with this type.  */
7332
7333 static tree
7334 create_array_type_for_decl (tree name, tree type, tree size)
7335 {
7336   tree itype = NULL_TREE;
7337   const char* error_msg;
7338
7339   /* If things have already gone awry, bail now.  */
7340   if (type == error_mark_node || size == error_mark_node)
7341     return error_mark_node;
7342
7343   /* Assume that everything will go OK.  */
7344   error_msg = NULL;
7345
7346   /* There are some types which cannot be array elements.  */
7347   switch (TREE_CODE (type))
7348     {
7349     case VOID_TYPE:
7350       error_msg = "array of void";
7351       break;
7352
7353     case FUNCTION_TYPE:
7354       error_msg = "array of functions";
7355       break;
7356
7357     case REFERENCE_TYPE:
7358       error_msg = "array of references";
7359       break;
7360
7361     case METHOD_TYPE:
7362       error_msg = "array of function members";
7363       break;
7364
7365     default:
7366       break;
7367     }
7368
7369   /* If something went wrong, issue an error-message and return.  */
7370   if (error_msg)
7371     {
7372       if (name)
7373         error ("declaration of %qD as %s", name, error_msg);
7374       else
7375         error ("creating %s", error_msg);
7376
7377       return error_mark_node;
7378     }
7379
7380   /* [dcl.array]
7381
7382      The constant expressions that specify the bounds of the arrays
7383      can be omitted only for the first member of the sequence.  */
7384   if (TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type))
7385     {
7386       if (name)
7387         error ("declaration of %qD as multidimensional array must "
7388                "have bounds for all dimensions except the first",
7389                name);
7390       else
7391         error ("multidimensional array must have bounds for all "
7392                "dimensions except the first");
7393
7394       return error_mark_node;
7395     }
7396
7397   /* Figure out the index type for the array.  */
7398   if (size)
7399     itype = compute_array_index_type (name, size);
7400
7401   /* [dcl.array]
7402      T is called the array element type; this type shall not be [...] an
7403      abstract class type.  */
7404   abstract_virtuals_error (name, type);
7405
7406   return build_cplus_array_type (type, itype);
7407 }
7408
7409 /* Check that it's OK to declare a function with the indicated TYPE.
7410    SFK indicates the kind of special function (if any) that this
7411    function is.  OPTYPE is the type given in a conversion operator
7412    declaration, or the class type for a constructor/destructor.
7413    Returns the actual return type of the function; that
7414    may be different than TYPE if an error occurs, or for certain
7415    special functions.  */
7416
7417 static tree
7418 check_special_function_return_type (special_function_kind sfk,
7419                                     tree type,
7420                                     tree optype)
7421 {
7422   switch (sfk)
7423     {
7424     case sfk_constructor:
7425       if (type)
7426         error ("return type specification for constructor invalid");
7427
7428       if (targetm.cxx.cdtor_returns_this () && !TYPE_FOR_JAVA (optype))
7429         type = build_pointer_type (optype);
7430       else
7431         type = void_type_node;
7432       break;
7433
7434     case sfk_destructor:
7435       if (type)
7436         error ("return type specification for destructor invalid");
7437       /* We can't use the proper return type here because we run into
7438          problems with ambiguous bases and covariant returns.
7439          Java classes are left unchanged because (void *) isn't a valid
7440          Java type, and we don't want to change the Java ABI.  */
7441       if (targetm.cxx.cdtor_returns_this () && !TYPE_FOR_JAVA (optype))
7442         type = build_pointer_type (void_type_node);
7443       else
7444         type = void_type_node;
7445       break;
7446
7447     case sfk_conversion:
7448       if (type)
7449         error ("return type specified for %<operator %T%>",  optype);
7450       type = optype;
7451       break;
7452
7453     default:
7454       gcc_unreachable ();
7455     }
7456
7457   return type;
7458 }
7459
7460 /* A variable or data member (whose unqualified name is IDENTIFIER)
7461    has been declared with the indicated TYPE.  If the TYPE is not
7462    acceptable, issue an error message and return a type to use for
7463    error-recovery purposes.  */
7464
7465 tree
7466 check_var_type (tree identifier, tree type)
7467 {
7468   if (VOID_TYPE_P (type))
7469     {
7470       if (!identifier)
7471         error ("unnamed variable or field declared void");
7472       else if (TREE_CODE (identifier) == IDENTIFIER_NODE)
7473         {
7474           gcc_assert (!IDENTIFIER_OPNAME_P (identifier));
7475           error ("variable or field %qE declared void", identifier);
7476         }
7477       else
7478         error ("variable or field declared void");
7479       type = error_mark_node;
7480     }
7481
7482   return type;
7483 }
7484
7485 /* Given declspecs and a declarator (abstract or otherwise), determine
7486    the name and type of the object declared and construct a DECL node
7487    for it.
7488
7489    DECLSPECS points to the representation of declaration-specifier
7490    sequence that precedes declarator.
7491
7492    DECL_CONTEXT says which syntactic context this declaration is in:
7493      NORMAL for most contexts.  Make a VAR_DECL or FUNCTION_DECL or TYPE_DECL.
7494      FUNCDEF for a function definition.  Like NORMAL but a few different
7495       error messages in each case.  Return value may be zero meaning
7496       this definition is too screwy to try to parse.
7497      MEMFUNCDEF for a function definition.  Like FUNCDEF but prepares to
7498       handle member functions (which have FIELD context).
7499       Return value may be zero meaning this definition is too screwy to
7500       try to parse.
7501      PARM for a parameter declaration (either within a function prototype
7502       or before a function body).  Make a PARM_DECL, or return void_type_node.
7503      CATCHPARM for a parameter declaration before a catch clause.
7504      TYPENAME if for a typename (in a cast or sizeof).
7505       Don't make a DECL node; just return the ..._TYPE node.
7506      FIELD for a struct or union field; make a FIELD_DECL.
7507      BITFIELD for a field with specified width.
7508    INITIALIZED is as for start_decl.
7509
7510    ATTRLIST is a pointer to the list of attributes, which may be NULL
7511    if there are none; *ATTRLIST may be modified if attributes from inside
7512    the declarator should be applied to the declaration.
7513
7514    When this function is called, scoping variables (such as
7515    CURRENT_CLASS_TYPE) should reflect the scope in which the
7516    declaration occurs, not the scope in which the new declaration will
7517    be placed.  For example, on:
7518
7519      void S::f() { ... }
7520
7521    when grokdeclarator is called for `S::f', the CURRENT_CLASS_TYPE
7522    should not be `S'.
7523
7524    Returns a DECL (if a declarator is present), a TYPE (if there is no
7525    declarator, in cases like "struct S;"), or the ERROR_MARK_NODE if an
7526    error occurs. */
7527
7528 tree
7529 grokdeclarator (const cp_declarator *declarator,
7530                 const cp_decl_specifier_seq *declspecs,
7531                 enum decl_context decl_context,
7532                 int initialized,
7533                 tree* attrlist)
7534 {
7535   tree type = NULL_TREE;
7536   int longlong = 0;
7537   int virtualp, explicitp, friendp, inlinep, staticp;
7538   int explicit_int = 0;
7539   int explicit_char = 0;
7540   int defaulted_int = 0;
7541   tree dependent_name = NULL_TREE;
7542
7543   tree typedef_decl = NULL_TREE;
7544   const char *name = NULL;
7545   tree typedef_type = NULL_TREE;
7546   /* True if this declarator is a function definition.  */
7547   bool funcdef_flag = false;
7548   cp_declarator_kind innermost_code = cdk_error;
7549   int bitfield = 0;
7550 #if 0
7551   /* See the code below that used this.  */
7552   tree decl_attr = NULL_TREE;
7553 #endif
7554
7555   /* Keep track of what sort of function is being processed
7556      so that we can warn about default return values, or explicit
7557      return values which do not match prescribed defaults.  */
7558   special_function_kind sfk = sfk_none;
7559
7560   tree dname = NULL_TREE;
7561   tree ctor_return_type = NULL_TREE;
7562   enum overload_flags flags = NO_SPECIAL;
7563   /* cv-qualifiers that apply to the declarator, for a declaration of
7564      a member function.  */
7565   cp_cv_quals memfn_quals = TYPE_UNQUALIFIED;
7566   /* cv-qualifiers that apply to the type specified by the DECLSPECS.  */
7567   int type_quals;
7568   tree raises = NULL_TREE;
7569   int template_count = 0;
7570   tree returned_attrs = NULL_TREE;
7571   tree parms = NULL_TREE;
7572   const cp_declarator *id_declarator;
7573   /* The unqualified name of the declarator; either an
7574      IDENTIFIER_NODE, BIT_NOT_EXPR, or TEMPLATE_ID_EXPR.  */
7575   tree unqualified_id;
7576   /* The class type, if any, in which this entity is located,
7577      or NULL_TREE if none.  Note that this value may be different from
7578      the current class type; for example if an attempt is made to declare
7579      "A::f" inside "B", this value will be "A".  */
7580   tree ctype = current_class_type;
7581   /* The NAMESPACE_DECL for the namespace in which this entity is
7582      located.  If an unqualified name is used to declare the entity,
7583      this value will be NULL_TREE, even if the entity is located at
7584      namespace scope.  */
7585   tree in_namespace = NULL_TREE;
7586   cp_storage_class storage_class;
7587   bool unsigned_p, signed_p, short_p, long_p, thread_p;
7588   bool type_was_error_mark_node = false;
7589   bool parameter_pack_p = declarator? declarator->parameter_pack_p : false;
7590   bool template_type_arg = false;
7591   const char *errmsg;
7592
7593   signed_p = declspecs->specs[(int)ds_signed];
7594   unsigned_p = declspecs->specs[(int)ds_unsigned];
7595   short_p = declspecs->specs[(int)ds_short];
7596   long_p = declspecs->specs[(int)ds_long];
7597   longlong = declspecs->specs[(int)ds_long] >= 2;
7598   thread_p = declspecs->specs[(int)ds_thread];
7599
7600   if (decl_context == FUNCDEF)
7601     funcdef_flag = true, decl_context = NORMAL;
7602   else if (decl_context == MEMFUNCDEF)
7603     funcdef_flag = true, decl_context = FIELD;
7604   else if (decl_context == BITFIELD)
7605     bitfield = 1, decl_context = FIELD;
7606   else if (decl_context == TEMPLATE_TYPE_ARG)
7607     template_type_arg = true, decl_context = TYPENAME;
7608
7609   if (initialized > 1)
7610     funcdef_flag = true;
7611
7612   /* Look inside a declarator for the name being declared
7613      and get it as a string, for an error message.  */
7614   for (id_declarator = declarator;
7615        id_declarator;
7616        id_declarator = id_declarator->declarator)
7617     {
7618       if (id_declarator->kind != cdk_id)
7619         innermost_code = id_declarator->kind;
7620
7621       switch (id_declarator->kind)
7622         {
7623         case cdk_function:
7624           if (id_declarator->declarator
7625               && id_declarator->declarator->kind == cdk_id)
7626             {
7627               sfk = id_declarator->declarator->u.id.sfk;
7628               if (sfk == sfk_destructor)
7629                 flags = DTOR_FLAG;
7630             }
7631           break;
7632
7633         case cdk_id:
7634           {
7635             tree qualifying_scope = id_declarator->u.id.qualifying_scope;
7636             tree decl = id_declarator->u.id.unqualified_name;
7637             if (!decl)
7638               break;
7639             if (qualifying_scope)
7640               {
7641                 if (at_function_scope_p ())
7642                   {
7643                     /* [dcl.meaning] 
7644
7645                        A declarator-id shall not be qualified except
7646                        for ... 
7647
7648                        None of the cases are permitted in block
7649                        scope.  */
7650                     if (qualifying_scope == global_namespace)
7651                       error ("invalid use of qualified-name %<::%D%>",
7652                              decl);
7653                     else if (TYPE_P (qualifying_scope))
7654                       error ("invalid use of qualified-name %<%T::%D%>",
7655                              qualifying_scope, decl);
7656                     else 
7657                       error ("invalid use of qualified-name %<%D::%D%>",
7658                              qualifying_scope, decl);
7659                     return error_mark_node;
7660                   }
7661                 else if (TYPE_P (qualifying_scope))
7662                   {
7663                     ctype = qualifying_scope;
7664                     if (innermost_code != cdk_function
7665                         && current_class_type
7666                         && !UNIQUELY_DERIVED_FROM_P (ctype,
7667                                                      current_class_type))
7668                       {
7669                         error ("type %qT is not derived from type %qT",
7670                                ctype, current_class_type);
7671                         return error_mark_node;
7672                       }
7673                   }
7674                 else if (TREE_CODE (qualifying_scope) == NAMESPACE_DECL)
7675                   in_namespace = qualifying_scope;
7676               }
7677             switch (TREE_CODE (decl))
7678               {
7679               case BIT_NOT_EXPR:
7680                 {
7681                   tree type;
7682
7683                   if (innermost_code != cdk_function)
7684                     {
7685                       error ("declaration of %qD as non-function", decl);
7686                       return error_mark_node;
7687                     }
7688                   else if (!qualifying_scope
7689                            && !(current_class_type && at_class_scope_p ()))
7690                     {
7691                       error ("declaration of %qD as non-member", decl);
7692                       return error_mark_node;
7693                     }
7694
7695                   type = TREE_OPERAND (decl, 0);
7696                   if (TYPE_P (type))
7697                     type = constructor_name (type);
7698                   name = identifier_to_locale (IDENTIFIER_POINTER (type));
7699                   dname = decl;
7700                 }
7701                 break;
7702
7703               case TEMPLATE_ID_EXPR:
7704                 {
7705                   tree fns = TREE_OPERAND (decl, 0);
7706
7707                   dname = fns;
7708                   if (TREE_CODE (dname) != IDENTIFIER_NODE)
7709                     {
7710                       gcc_assert (is_overloaded_fn (dname));
7711                       dname = DECL_NAME (get_first_fn (dname));
7712                     }
7713                 }
7714                 /* Fall through.  */
7715
7716               case IDENTIFIER_NODE:
7717                 if (TREE_CODE (decl) == IDENTIFIER_NODE)
7718                   dname = decl;
7719
7720                 if (C_IS_RESERVED_WORD (dname))
7721                   {
7722                     error ("declarator-id missing; using reserved word %qD",
7723                            dname);
7724                     name = identifier_to_locale (IDENTIFIER_POINTER (dname));
7725                   }
7726                 else if (!IDENTIFIER_TYPENAME_P (dname))
7727                   name = identifier_to_locale (IDENTIFIER_POINTER (dname));
7728                 else
7729                   {
7730                     gcc_assert (flags == NO_SPECIAL);
7731                     flags = TYPENAME_FLAG;
7732                     ctor_return_type = TREE_TYPE (dname);
7733                     sfk = sfk_conversion;
7734                     if (is_typename_at_global_scope (dname))
7735                       name = identifier_to_locale (IDENTIFIER_POINTER (dname));
7736                     else
7737                       name = "<invalid operator>";
7738                   }
7739                 break;
7740
7741               default:
7742                 gcc_unreachable ();
7743               }
7744             break;
7745           }
7746
7747         case cdk_array:
7748         case cdk_pointer:
7749         case cdk_reference:
7750         case cdk_ptrmem:
7751           break;
7752
7753         case cdk_error:
7754           return error_mark_node;
7755
7756         default:
7757           gcc_unreachable ();
7758         }
7759       if (id_declarator->kind == cdk_id)
7760         break;
7761     }
7762
7763   /* [dcl.fct.edf]
7764
7765      The declarator in a function-definition shall have the form
7766      D1 ( parameter-declaration-clause) ...  */
7767   if (funcdef_flag && innermost_code != cdk_function)
7768     {
7769       error ("function definition does not declare parameters");
7770       return error_mark_node;
7771     }
7772
7773   if (((dname && IDENTIFIER_OPNAME_P (dname)) || flags == TYPENAME_FLAG)
7774       && innermost_code != cdk_function
7775       && ! (ctype && !declspecs->any_specifiers_p))
7776     {
7777       error ("declaration of %qD as non-function", dname);
7778       return error_mark_node;
7779     }
7780
7781   /* Anything declared one level down from the top level
7782      must be one of the parameters of a function
7783      (because the body is at least two levels down).  */
7784
7785   /* This heuristic cannot be applied to C++ nodes! Fixed, however,
7786      by not allowing C++ class definitions to specify their parameters
7787      with xdecls (must be spec.d in the parmlist).
7788
7789      Since we now wait to push a class scope until we are sure that
7790      we are in a legitimate method context, we must set oldcname
7791      explicitly (since current_class_name is not yet alive).
7792
7793      We also want to avoid calling this a PARM if it is in a namespace.  */
7794
7795   if (decl_context == NORMAL && !toplevel_bindings_p ())
7796     {
7797       struct cp_binding_level *b = current_binding_level;
7798       current_binding_level = b->level_chain;
7799       if (current_binding_level != 0 && toplevel_bindings_p ())
7800         decl_context = PARM;
7801       current_binding_level = b;
7802     }
7803
7804   if (name == NULL)
7805     name = decl_context == PARM ? "parameter" : "type name";
7806
7807   /* If there were multiple types specified in the decl-specifier-seq,
7808      issue an error message.  */
7809   if (declspecs->multiple_types_p)
7810     {
7811       error ("two or more data types in declaration of %qs", name);
7812       return error_mark_node;
7813     }
7814
7815   if (declspecs->conflicting_specifiers_p)
7816     {
7817       error ("conflicting specifiers in declaration of %qs", name);
7818       return error_mark_node;
7819     }
7820
7821   /* Extract the basic type from the decl-specifier-seq.  */
7822   type = declspecs->type;
7823   if (type == error_mark_node)
7824     {
7825       type = NULL_TREE;
7826       type_was_error_mark_node = true;
7827     }
7828   /* If the entire declaration is itself tagged as deprecated then
7829      suppress reports of deprecated items.  */
7830   if (type && TREE_DEPRECATED (type)
7831       && deprecated_state != DEPRECATED_SUPPRESS)
7832     warn_deprecated_use (type, NULL_TREE);
7833   if (type && TREE_CODE (type) == TYPE_DECL)
7834     {
7835       typedef_decl = type;
7836       type = TREE_TYPE (typedef_decl);
7837       if (TREE_DEPRECATED (type)
7838           && DECL_ARTIFICIAL (typedef_decl)
7839           && deprecated_state != DEPRECATED_SUPPRESS)
7840         warn_deprecated_use (type, NULL_TREE);
7841     }
7842   /* No type at all: default to `int', and set DEFAULTED_INT
7843      because it was not a user-defined typedef.  */
7844   if (type == NULL_TREE && (signed_p || unsigned_p || long_p || short_p))
7845     {
7846       /* These imply 'int'.  */
7847       type = integer_type_node;
7848       defaulted_int = 1;
7849     }
7850   /* Gather flags.  */
7851   explicit_int = declspecs->explicit_int_p;
7852   explicit_char = declspecs->explicit_char_p;
7853
7854 #if 0
7855   /* See the code below that used this.  */
7856   if (typedef_decl)
7857     decl_attr = DECL_ATTRIBUTES (typedef_decl);
7858 #endif
7859   typedef_type = type;
7860
7861
7862   if (sfk != sfk_conversion)
7863     ctor_return_type = ctype;
7864
7865   if (sfk != sfk_none)
7866     type = check_special_function_return_type (sfk, type,
7867                                                ctor_return_type);
7868   else if (type == NULL_TREE)
7869     {
7870       int is_main;
7871
7872       explicit_int = -1;
7873
7874       /* We handle `main' specially here, because 'main () { }' is so
7875          common.  With no options, it is allowed.  With -Wreturn-type,
7876          it is a warning.  It is only an error with -pedantic-errors.  */
7877       is_main = (funcdef_flag
7878                  && dname && MAIN_NAME_P (dname)
7879                  && ctype == NULL_TREE
7880                  && in_namespace == NULL_TREE
7881                  && current_namespace == global_namespace);
7882
7883       if (type_was_error_mark_node)
7884         /* We've already issued an error, don't complain more.  */;
7885       else if (in_system_header || flag_ms_extensions)
7886         /* Allow it, sigh.  */;
7887       else if (! is_main)
7888         permerror (input_location, "ISO C++ forbids declaration of %qs with no type", name);
7889       else if (pedantic)
7890         pedwarn (input_location, OPT_pedantic,
7891                  "ISO C++ forbids declaration of %qs with no type", name);
7892       else
7893         warning (OPT_Wreturn_type,
7894                  "ISO C++ forbids declaration of %qs with no type", name);
7895
7896       type = integer_type_node;
7897     }
7898
7899   ctype = NULL_TREE;
7900
7901   /* Now process the modifiers that were specified
7902      and check for invalid combinations.  */
7903
7904   /* Long double is a special combination.  */
7905   if (long_p && !longlong && TYPE_MAIN_VARIANT (type) == double_type_node)
7906     {
7907       long_p = false;
7908       type = build_qualified_type (long_double_type_node,
7909                                    cp_type_quals (type));
7910     }
7911
7912   /* Check all other uses of type modifiers.  */
7913
7914   if (unsigned_p || signed_p || long_p || short_p)
7915     {
7916       int ok = 0;
7917
7918       if ((signed_p || unsigned_p) && TREE_CODE (type) != INTEGER_TYPE)
7919         error ("%<signed%> or %<unsigned%> invalid for %qs", name);
7920       else if (signed_p && unsigned_p)
7921         error ("%<signed%> and %<unsigned%> specified together for %qs", name);
7922       else if (longlong && TREE_CODE (type) != INTEGER_TYPE)
7923         error ("%<long long%> invalid for %qs", name);
7924       else if (long_p && TREE_CODE (type) == REAL_TYPE)
7925         error ("%<long%> invalid for %qs", name);
7926       else if (short_p && TREE_CODE (type) == REAL_TYPE)
7927         error ("%<short%> invalid for %qs", name);
7928       else if ((long_p || short_p) && TREE_CODE (type) != INTEGER_TYPE)
7929         error ("%<long%> or %<short%> invalid for %qs", name);
7930       else if ((long_p || short_p) && explicit_char)
7931         error ("%<long%> or %<short%> specified with char for %qs", name);
7932       else if (long_p && short_p)
7933         error ("%<long%> and %<short%> specified together for %qs", name);
7934       else if (type == char16_type_node || type == char32_type_node)
7935         {
7936           if (signed_p || unsigned_p)
7937             error ("%<signed%> or %<unsigned%> invalid for %qs", name);
7938           else if (short_p || long_p)
7939             error ("%<short%> or %<long%> invalid for %qs", name);
7940         }
7941       else
7942         {
7943           ok = 1;
7944           if (!explicit_int && !defaulted_int && !explicit_char && pedantic)
7945             {
7946               pedwarn (input_location, OPT_pedantic, 
7947                        "long, short, signed or unsigned used invalidly for %qs",
7948                        name);
7949               if (flag_pedantic_errors)
7950                 ok = 0;
7951             }
7952         }
7953
7954       /* Discard the type modifiers if they are invalid.  */
7955       if (! ok)
7956         {
7957           unsigned_p = false;
7958           signed_p = false;
7959           long_p = false;
7960           short_p = false;
7961           longlong = 0;
7962         }
7963     }
7964
7965   /* Decide whether an integer type is signed or not.
7966      Optionally treat bitfields as signed by default.  */
7967   if (unsigned_p
7968       /* [class.bit]
7969
7970          It is implementation-defined whether a plain (neither
7971          explicitly signed or unsigned) char, short, int, or long
7972          bit-field is signed or unsigned.
7973
7974          Naturally, we extend this to long long as well.  Note that
7975          this does not include wchar_t.  */
7976       || (bitfield && !flag_signed_bitfields
7977           && !signed_p
7978           /* A typedef for plain `int' without `signed' can be
7979              controlled just like plain `int', but a typedef for
7980              `signed int' cannot be so controlled.  */
7981           && !(typedef_decl
7982                && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl))
7983           && TREE_CODE (type) == INTEGER_TYPE
7984           && !same_type_p (TYPE_MAIN_VARIANT (type), wchar_type_node)))
7985     {
7986       if (longlong)
7987         type = long_long_unsigned_type_node;
7988       else if (long_p)
7989         type = long_unsigned_type_node;
7990       else if (short_p)
7991         type = short_unsigned_type_node;
7992       else if (type == char_type_node)
7993         type = unsigned_char_type_node;
7994       else if (typedef_decl)
7995         type = unsigned_type_for (type);
7996       else
7997         type = unsigned_type_node;
7998     }
7999   else if (signed_p && type == char_type_node)
8000     type = signed_char_type_node;
8001   else if (longlong)
8002     type = long_long_integer_type_node;
8003   else if (long_p)
8004     type = long_integer_type_node;
8005   else if (short_p)
8006     type = short_integer_type_node;
8007
8008   if (declspecs->specs[(int)ds_complex])
8009     {
8010       if (TREE_CODE (type) != INTEGER_TYPE && TREE_CODE (type) != REAL_TYPE)
8011         error ("complex invalid for %qs", name);
8012       /* If we just have "complex", it is equivalent to
8013          "complex double", but if any modifiers at all are specified it is
8014          the complex form of TYPE.  E.g, "complex short" is
8015          "complex short int".  */
8016
8017       else if (defaulted_int && ! longlong
8018                && ! (long_p || short_p || signed_p || unsigned_p))
8019         type = complex_double_type_node;
8020       else if (type == integer_type_node)
8021         type = complex_integer_type_node;
8022       else if (type == float_type_node)
8023         type = complex_float_type_node;
8024       else if (type == double_type_node)
8025         type = complex_double_type_node;
8026       else if (type == long_double_type_node)
8027         type = complex_long_double_type_node;
8028       else
8029         type = build_complex_type (type);
8030     }
8031
8032   type_quals = TYPE_UNQUALIFIED;
8033   if (declspecs->specs[(int)ds_const])
8034     type_quals |= TYPE_QUAL_CONST;
8035   if (declspecs->specs[(int)ds_volatile])
8036     type_quals |= TYPE_QUAL_VOLATILE;
8037   if (declspecs->specs[(int)ds_restrict])
8038     type_quals |= TYPE_QUAL_RESTRICT;
8039   if (sfk == sfk_conversion && type_quals != TYPE_UNQUALIFIED)
8040     error ("qualifiers are not allowed on declaration of %<operator %T%>",
8041            ctor_return_type);
8042
8043   if (TREE_CODE (type) == FUNCTION_TYPE
8044       && type_quals != TYPE_UNQUALIFIED)
8045     {
8046       /* This was an error in C++98 (cv-qualifiers cannot be added to
8047          a function type), but DR 295 makes the code well-formed by
8048          dropping the extra qualifiers. */
8049       if (pedantic)
8050         {
8051           tree bad_type = build_qualified_type (type, type_quals);
8052           pedwarn (input_location, OPT_pedantic, 
8053                    "ignoring %qV qualifiers added to function type %qT",
8054                    bad_type, type);
8055         }
8056       type_quals = TYPE_UNQUALIFIED;
8057     }
8058   type_quals |= cp_type_quals (type);
8059   type = cp_build_qualified_type_real
8060     (type, type_quals, ((typedef_decl && !DECL_ARTIFICIAL (typedef_decl)
8061                          ? tf_ignore_bad_quals : 0) | tf_warning_or_error));
8062   /* We might have ignored or rejected some of the qualifiers.  */
8063   type_quals = cp_type_quals (type);
8064
8065   staticp = 0;
8066   inlinep = !! declspecs->specs[(int)ds_inline];
8067   virtualp = !! declspecs->specs[(int)ds_virtual];
8068   explicitp = !! declspecs->specs[(int)ds_explicit];
8069
8070   storage_class = declspecs->storage_class;
8071   if (storage_class == sc_static)
8072     staticp = 1 + (decl_context == FIELD);
8073
8074   if (virtualp && staticp == 2)
8075     {
8076       error ("member %qD cannot be declared both virtual and static", dname);
8077       storage_class = sc_none;
8078       staticp = 0;
8079     }
8080   friendp = !! declspecs->specs[(int)ds_friend];
8081
8082   if (dependent_name && !friendp)
8083     {
8084       error ("%<%T::%D%> is not a valid declarator", ctype, dependent_name);
8085       return error_mark_node;
8086     }
8087
8088   /* Issue errors about use of storage classes for parameters.  */
8089   if (decl_context == PARM)
8090     {
8091       if (declspecs->specs[(int)ds_typedef])
8092         {
8093           error ("typedef declaration invalid in parameter declaration");
8094           return error_mark_node;
8095         }
8096       else if (storage_class == sc_static
8097                || storage_class == sc_extern
8098                || thread_p)
8099         error ("storage class specifiers invalid in parameter declarations");
8100
8101       if (type_uses_auto (type))
8102         {
8103           error ("parameter declared %<auto%>");
8104           type = error_mark_node;
8105         }
8106     }
8107
8108   /* Give error if `virtual' is used outside of class declaration.  */
8109   if (virtualp
8110       && (current_class_name == NULL_TREE || decl_context != FIELD))
8111     {
8112       error ("%<virtual%> outside class declaration");
8113       virtualp = 0;
8114     }
8115
8116   /* Static anonymous unions are dealt with here.  */
8117   if (staticp && decl_context == TYPENAME
8118       && declspecs->type
8119       && ANON_AGGR_TYPE_P (declspecs->type))
8120     decl_context = FIELD;
8121
8122   /* Warn about storage classes that are invalid for certain
8123      kinds of declarations (parameters, typenames, etc.).  */
8124   if (thread_p
8125       && ((storage_class
8126            && storage_class != sc_extern
8127            && storage_class != sc_static)
8128           || declspecs->specs[(int)ds_typedef]))
8129     {
8130       error ("multiple storage classes in declaration of %qs", name);
8131       thread_p = false;
8132     }
8133   if (decl_context != NORMAL
8134       && ((storage_class != sc_none
8135            && storage_class != sc_mutable)
8136           || thread_p))
8137     {
8138       if ((decl_context == PARM || decl_context == CATCHPARM)
8139           && (storage_class == sc_register
8140               || storage_class == sc_auto))
8141         ;
8142       else if (declspecs->specs[(int)ds_typedef])
8143         ;
8144       else if (decl_context == FIELD
8145                /* C++ allows static class elements.  */
8146                && storage_class == sc_static)
8147         /* C++ also allows inlines and signed and unsigned elements,
8148            but in those cases we don't come in here.  */
8149         ;
8150       else
8151         {
8152           if (decl_context == FIELD)
8153             error ("storage class specified for %qs", name);
8154           else
8155             {
8156               if (decl_context == PARM || decl_context == CATCHPARM)
8157                 error ("storage class specified for parameter %qs", name);
8158               else
8159                 error ("storage class specified for typename");
8160             }
8161           if (storage_class == sc_register
8162               || storage_class == sc_auto
8163               || storage_class == sc_extern
8164               || thread_p)
8165             storage_class = sc_none;
8166         }
8167     }
8168   else if (storage_class == sc_extern && funcdef_flag
8169            && ! toplevel_bindings_p ())
8170     error ("nested function %qs declared %<extern%>", name);
8171   else if (toplevel_bindings_p ())
8172     {
8173       if (storage_class == sc_auto)
8174         error ("top-level declaration of %qs specifies %<auto%>", name);
8175     }
8176   else if (thread_p
8177            && storage_class != sc_extern
8178            && storage_class != sc_static)
8179     {
8180       error ("function-scope %qs implicitly auto and declared %<__thread%>",
8181              name);
8182       thread_p = false;
8183     }
8184
8185   if (storage_class && friendp)
8186     {
8187       error ("storage class specifiers invalid in friend function declarations");
8188       storage_class = sc_none;
8189       staticp = 0;
8190     }
8191
8192   if (!id_declarator)
8193     unqualified_id = NULL_TREE;
8194   else
8195     {
8196       unqualified_id = id_declarator->u.id.unqualified_name;
8197       switch (TREE_CODE (unqualified_id))
8198         {
8199         case BIT_NOT_EXPR:
8200           unqualified_id = TREE_OPERAND (unqualified_id, 0);
8201           if (TYPE_P (unqualified_id))
8202             unqualified_id = constructor_name (unqualified_id);
8203           break;
8204
8205         case IDENTIFIER_NODE:
8206         case TEMPLATE_ID_EXPR:
8207           break;
8208
8209         default:
8210           gcc_unreachable ();
8211         }
8212     }
8213
8214   /* Determine the type of the entity declared by recurring on the
8215      declarator.  */
8216   for (; declarator; declarator = declarator->declarator)
8217     {
8218       const cp_declarator *inner_declarator;
8219       tree attrs;
8220
8221       if (type == error_mark_node)
8222         return error_mark_node;
8223
8224       attrs = declarator->attributes;
8225       if (attrs)
8226         {
8227           int attr_flags;
8228
8229           attr_flags = 0;
8230           if (declarator == NULL || declarator->kind == cdk_id)
8231             attr_flags |= (int) ATTR_FLAG_DECL_NEXT;
8232           if (declarator->kind == cdk_function)
8233             attr_flags |= (int) ATTR_FLAG_FUNCTION_NEXT;
8234           if (declarator->kind == cdk_array)
8235             attr_flags |= (int) ATTR_FLAG_ARRAY_NEXT;
8236           returned_attrs = decl_attributes (&type,
8237                                             chainon (returned_attrs, attrs),
8238                                             attr_flags);
8239         }
8240
8241       if (declarator->kind == cdk_id)
8242         break;
8243
8244       inner_declarator = declarator->declarator;
8245
8246       switch (declarator->kind)
8247         {
8248         case cdk_array:
8249           type = create_array_type_for_decl (dname, type,
8250                                              declarator->u.array.bounds);
8251           break;
8252
8253         case cdk_function:
8254           {
8255             tree arg_types;
8256             int funcdecl_p;
8257
8258             /* Declaring a function type.
8259                Make sure we have a valid type for the function to return.  */
8260
8261             if (type_quals != TYPE_UNQUALIFIED)
8262               {
8263                 if (SCALAR_TYPE_P (type) || VOID_TYPE_P (type))
8264                   warning (OPT_Wignored_qualifiers,
8265                            "type qualifiers ignored on function return type");
8266                 /* We now know that the TYPE_QUALS don't apply to the
8267                    decl, but to its return type.  */
8268                 type_quals = TYPE_UNQUALIFIED;
8269               }
8270             errmsg = targetm.invalid_return_type (type);
8271             if (errmsg)
8272               {
8273                 error (errmsg);
8274                 type = integer_type_node;
8275               }
8276
8277             /* Error about some types functions can't return.  */
8278
8279             if (TREE_CODE (type) == FUNCTION_TYPE)
8280               {
8281                 error ("%qs declared as function returning a function", name);
8282                 return error_mark_node;
8283               }
8284             if (TREE_CODE (type) == ARRAY_TYPE)
8285               {
8286                 error ("%qs declared as function returning an array", name);
8287                 return error_mark_node;
8288               }
8289
8290             /* Pick up type qualifiers which should be applied to `this'.  */
8291             memfn_quals = declarator->u.function.qualifiers;
8292
8293             /* Pick up the exception specifications.  */
8294             raises = declarator->u.function.exception_specification;
8295
8296             /* Say it's a definition only for the CALL_EXPR
8297                closest to the identifier.  */
8298             funcdecl_p = inner_declarator && inner_declarator->kind == cdk_id;
8299
8300             /* Handle a late-specified return type.  */
8301             if (funcdecl_p)
8302               {
8303                 if (type_uses_auto (type))
8304                   {
8305                     if (!declarator->u.function.late_return_type)
8306                       {
8307                         error ("%qs function uses %<auto%> type specifier without"
8308                                " late return type", name);
8309                         return error_mark_node;
8310                       }
8311                     else if (!is_auto (type))
8312                       {
8313                         error ("%qs function with late return type has"
8314                                " %qT as its type rather than plain %<auto%>",
8315                                name, type);
8316                         return error_mark_node;
8317                       }
8318                   }
8319                 else if (declarator->u.function.late_return_type)
8320                   {
8321                     error ("%qs function with late return type not declared"
8322                            " with %<auto%> type specifier", name);
8323                     return error_mark_node;
8324                   }
8325               }
8326             type = splice_late_return_type
8327               (type, declarator->u.function.late_return_type);
8328             if (type == error_mark_node)
8329               return error_mark_node;
8330
8331             if (ctype == NULL_TREE
8332                 && decl_context == FIELD
8333                 && funcdecl_p
8334                 && (friendp == 0 || dname == current_class_name))
8335               ctype = current_class_type;
8336
8337             if (ctype && (sfk == sfk_constructor
8338                           || sfk == sfk_destructor))
8339               {
8340                 /* We are within a class's scope. If our declarator name
8341                    is the same as the class name, and we are defining
8342                    a function, then it is a constructor/destructor, and
8343                    therefore returns a void type.  */
8344
8345                 /* ISO C++ 12.4/2.  A destructor may not be declared
8346                    const or volatile.  A destructor may not be
8347                    static.
8348
8349                    ISO C++ 12.1.  A constructor may not be declared
8350                    const or volatile.  A constructor may not be
8351                    virtual.  A constructor may not be static.  */
8352                 if (staticp == 2)
8353                   error ((flags == DTOR_FLAG)
8354                          ? "destructor cannot be static member function"
8355                          : "constructor cannot be static member function");
8356                 if (memfn_quals)
8357                   {
8358                     error ((flags == DTOR_FLAG)
8359                            ? "destructors may not be cv-qualified"
8360                            : "constructors may not be cv-qualified");
8361                     memfn_quals = TYPE_UNQUALIFIED;
8362                   }
8363
8364                 if (decl_context == FIELD
8365                     && !member_function_or_else (ctype,
8366                                                  current_class_type,
8367                                                  flags))
8368                   return error_mark_node;
8369
8370                 if (flags != DTOR_FLAG)
8371                   {
8372                     /* It's a constructor.  */
8373                     if (explicitp == 1)
8374                       explicitp = 2;
8375                     if (virtualp)
8376                       {
8377                         permerror (input_location, "constructors cannot be declared virtual");
8378                         virtualp = 0;
8379                       }
8380                     if (decl_context == FIELD
8381                         && sfk != sfk_constructor)
8382                       return error_mark_node;
8383                   }
8384                 if (decl_context == FIELD)
8385                   staticp = 0;
8386               }
8387             else if (friendp)
8388               {
8389                 if (initialized)
8390                   error ("can't initialize friend function %qs", name);
8391                 if (virtualp)
8392                   {
8393                     /* Cannot be both friend and virtual.  */
8394                     error ("virtual functions cannot be friends");
8395                     friendp = 0;
8396                   }
8397                 if (decl_context == NORMAL)
8398                   error ("friend declaration not in class definition");
8399                 if (current_function_decl && funcdef_flag)
8400                   error ("can't define friend function %qs in a local "
8401                          "class definition",
8402                          name);
8403               }
8404             else if (ctype && sfk == sfk_conversion)
8405               {
8406                 if (explicitp == 1)
8407                   {
8408                     maybe_warn_cpp0x ("explicit conversion operators");
8409                     explicitp = 2;
8410                   }
8411               }
8412
8413             arg_types = grokparms (declarator->u.function.parameters,
8414                                    &parms);
8415
8416             if (inner_declarator
8417                 && inner_declarator->kind == cdk_id
8418                 && inner_declarator->u.id.sfk == sfk_destructor
8419                 && arg_types != void_list_node)
8420               {
8421                 error ("destructors may not have parameters");
8422                 arg_types = void_list_node;
8423                 parms = NULL_TREE;
8424               }
8425
8426             type = build_function_type (type, arg_types);
8427           }
8428           break;
8429
8430         case cdk_pointer:
8431         case cdk_reference:
8432         case cdk_ptrmem:
8433           /* Filter out pointers-to-references and references-to-references.
8434              We can get these if a TYPE_DECL is used.  */
8435
8436           if (TREE_CODE (type) == REFERENCE_TYPE)
8437             {
8438               if (declarator->kind != cdk_reference)
8439                 {
8440                   error ("cannot declare pointer to %q#T", type);
8441                   type = TREE_TYPE (type);
8442                 }
8443
8444               /* In C++0x, we allow reference to reference declarations
8445                  that occur indirectly through typedefs [7.1.3/8 dcl.typedef]
8446                  and template type arguments [14.3.1/4 temp.arg.type]. The
8447                  check for direct reference to reference declarations, which
8448                  are still forbidden, occurs below. Reasoning behind the change
8449                  can be found in DR106, DR540, and the rvalue reference
8450                  proposals. */
8451               else if (cxx_dialect == cxx98)
8452                 {
8453                   error ("cannot declare reference to %q#T", type);
8454                   type = TREE_TYPE (type);
8455                 }
8456             }
8457           else if (VOID_TYPE_P (type))
8458             {
8459               if (declarator->kind == cdk_reference)
8460                 error ("cannot declare reference to %q#T", type);
8461               else if (declarator->kind == cdk_ptrmem)
8462                 error ("cannot declare pointer to %q#T member", type);
8463             }
8464
8465           /* We now know that the TYPE_QUALS don't apply to the decl,
8466              but to the target of the pointer.  */
8467           type_quals = TYPE_UNQUALIFIED;
8468
8469           if (declarator->kind == cdk_ptrmem
8470               && (TREE_CODE (type) == FUNCTION_TYPE
8471                   || (memfn_quals && TREE_CODE (type) == METHOD_TYPE)))
8472             {
8473               memfn_quals |= cp_type_quals (type);
8474               type = build_memfn_type (type,
8475                                        declarator->u.pointer.class_type,
8476                                        memfn_quals);
8477               memfn_quals = TYPE_UNQUALIFIED;
8478             }
8479
8480           if (TREE_CODE (type) == FUNCTION_TYPE
8481               && cp_type_quals (type) != TYPE_UNQUALIFIED)
8482             error ("cannot declare %s to qualified function type %qT",
8483                    declarator->kind == cdk_reference ? "reference" : "pointer",
8484                    type);
8485
8486           if (declarator->kind == cdk_reference)
8487             {
8488               /* In C++0x, the type we are creating a reference to might be
8489                  a typedef which is itself a reference type. In that case,
8490                  we follow the reference collapsing rules in
8491                  [7.1.3/8 dcl.typedef] to create the final reference type:
8492
8493                  "If a typedef TD names a type that is a reference to a type
8494                  T, an attempt to create the type 'lvalue reference to cv TD'
8495                  creates the type 'lvalue reference to T,' while an attempt
8496                  to create the type "rvalue reference to cv TD' creates the
8497                  type TD."
8498               */
8499               if (!VOID_TYPE_P (type))
8500                 type = cp_build_reference_type
8501                        ((TREE_CODE (type) == REFERENCE_TYPE
8502                          ? TREE_TYPE (type) : type),
8503                         (declarator->u.reference.rvalue_ref
8504                          && (TREE_CODE(type) != REFERENCE_TYPE
8505                              || TYPE_REF_IS_RVALUE (type))));
8506
8507               /* In C++0x, we need this check for direct reference to
8508                  reference declarations, which are forbidden by
8509                  [8.3.2/5 dcl.ref]. Reference to reference declarations
8510                  are only allowed indirectly through typedefs and template
8511                  type arguments. Example:
8512
8513                    void foo(int & &);      // invalid ref-to-ref decl
8514
8515                    typedef int & int_ref;
8516                    void foo(int_ref &);    // valid ref-to-ref decl
8517               */
8518               if (inner_declarator && inner_declarator->kind == cdk_reference)
8519                 error ("cannot declare reference to %q#T, which is not "
8520                        "a typedef or a template type argument", type);
8521             }
8522           else if (TREE_CODE (type) == METHOD_TYPE)
8523             type = build_ptrmemfunc_type (build_pointer_type (type));
8524           else if (declarator->kind == cdk_ptrmem)
8525             {
8526               gcc_assert (TREE_CODE (declarator->u.pointer.class_type)
8527                           != NAMESPACE_DECL);
8528               if (declarator->u.pointer.class_type == error_mark_node)
8529                 /* We will already have complained.  */
8530                 type = error_mark_node;
8531               else
8532                 type = build_ptrmem_type (declarator->u.pointer.class_type,
8533                                           type);
8534             }
8535           else
8536             type = build_pointer_type (type);
8537
8538           /* Process a list of type modifier keywords (such as
8539              const or volatile) that were given inside the `*' or `&'.  */
8540
8541           if (declarator->u.pointer.qualifiers)
8542             {
8543               type
8544                 = cp_build_qualified_type (type,
8545                                            declarator->u.pointer.qualifiers);
8546               type_quals = cp_type_quals (type);
8547             }
8548           ctype = NULL_TREE;
8549           break;
8550
8551         case cdk_error:
8552           break;
8553
8554         default:
8555           gcc_unreachable ();
8556         }
8557     }
8558
8559   if (unqualified_id && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR
8560       && TREE_CODE (type) != FUNCTION_TYPE
8561       && TREE_CODE (type) != METHOD_TYPE)
8562     {
8563       error ("template-id %qD used as a declarator",
8564              unqualified_id);
8565       unqualified_id = dname;
8566     }
8567
8568   /* If TYPE is a FUNCTION_TYPE, but the function name was explicitly
8569      qualified with a class-name, turn it into a METHOD_TYPE, unless
8570      we know that the function is static.  We take advantage of this
8571      opportunity to do other processing that pertains to entities
8572      explicitly declared to be class members.  Note that if DECLARATOR
8573      is non-NULL, we know it is a cdk_id declarator; otherwise, we
8574      would not have exited the loop above.  */
8575   if (declarator
8576       && declarator->u.id.qualifying_scope
8577       && TYPE_P (declarator->u.id.qualifying_scope))
8578     {
8579       tree t;
8580
8581       ctype = declarator->u.id.qualifying_scope;
8582       ctype = TYPE_MAIN_VARIANT (ctype);
8583       t = ctype;
8584       while (t != NULL_TREE && CLASS_TYPE_P (t))
8585         {
8586           /* You're supposed to have one `template <...>' for every
8587              template class, but you don't need one for a full
8588              specialization.  For example:
8589
8590                template <class T> struct S{};
8591                template <> struct S<int> { void f(); };
8592                void S<int>::f () {}
8593
8594              is correct; there shouldn't be a `template <>' for the
8595              definition of `S<int>::f'.  */
8596           if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t)
8597               && !any_dependent_template_arguments_p (CLASSTYPE_TI_ARGS (t)))
8598             /* T is an explicit (not partial) specialization.  All
8599                containing classes must therefore also be explicitly
8600                specialized.  */
8601             break;
8602           if ((CLASSTYPE_USE_TEMPLATE (t) || CLASSTYPE_IS_TEMPLATE (t))
8603               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))
8604             template_count += 1;
8605
8606           t = TYPE_MAIN_DECL (t);
8607           t = DECL_CONTEXT (t);
8608         }
8609
8610       if (ctype == current_class_type)
8611         {
8612           if (friendp)
8613             {
8614               permerror (input_location, "member functions are implicitly friends of their class");
8615               friendp = 0;
8616             }
8617           else
8618             permerror (declarator->id_loc, 
8619                           "extra qualification %<%T::%> on member %qs",
8620                           ctype, name);
8621         }
8622       else if (/* If the qualifying type is already complete, then we
8623                   can skip the following checks.  */
8624                !COMPLETE_TYPE_P (ctype)
8625                && (/* If the function is being defined, then
8626                       qualifying type must certainly be complete.  */
8627                    funcdef_flag
8628                    /* A friend declaration of "T::f" is OK, even if
8629                       "T" is a template parameter.  But, if this
8630                       function is not a friend, the qualifying type
8631                       must be a class.  */
8632                    || (!friendp && !CLASS_TYPE_P (ctype))
8633                    /* For a declaration, the type need not be
8634                       complete, if either it is dependent (since there
8635                       is no meaningful definition of complete in that
8636                       case) or the qualifying class is currently being
8637                       defined.  */
8638                    || !(dependent_type_p (ctype)
8639                         || currently_open_class (ctype)))
8640                /* Check that the qualifying type is complete.  */
8641                && !complete_type_or_else (ctype, NULL_TREE))
8642         return error_mark_node;
8643       else if (TREE_CODE (type) == FUNCTION_TYPE)
8644         {
8645           tree sname = declarator->u.id.unqualified_name;
8646
8647           if (current_class_type
8648               && (!friendp || funcdef_flag))
8649             {
8650               error (funcdef_flag
8651                      ? "cannot define member function %<%T::%s%> within %<%T%>"
8652                      : "cannot declare member function %<%T::%s%> within %<%T%>",
8653                      ctype, name, current_class_type);
8654               return error_mark_node;
8655             }
8656
8657           if (TREE_CODE (sname) == IDENTIFIER_NODE
8658               && NEW_DELETE_OPNAME_P (sname))
8659             /* Overloaded operator new and operator delete
8660                are always static functions.  */
8661             ;
8662           else
8663             type = build_memfn_type (type, ctype, memfn_quals);
8664         }
8665       else if (declspecs->specs[(int)ds_typedef]
8666                && current_class_type)
8667         {
8668           error ("cannot declare member %<%T::%s%> within %qT",
8669                  ctype, name, current_class_type);
8670           return error_mark_node;
8671         }
8672     }
8673
8674   /* Now TYPE has the actual type.  */
8675
8676   if (returned_attrs)
8677     {
8678       if (attrlist)
8679         *attrlist = chainon (returned_attrs, *attrlist);
8680       else
8681         attrlist = &returned_attrs;
8682     }
8683
8684   /* Handle parameter packs. */
8685   if (parameter_pack_p)
8686     {
8687       if (decl_context == PARM)
8688         /* Turn the type into a pack expansion.*/
8689         type = make_pack_expansion (type);
8690       else
8691         error ("non-parameter %qs cannot be a parameter pack", name);
8692     }
8693
8694   /* Did array size calculations overflow?  */
8695
8696   if (TREE_CODE (type) == ARRAY_TYPE
8697       && COMPLETE_TYPE_P (type)
8698       && TREE_CODE (TYPE_SIZE_UNIT (type)) == INTEGER_CST
8699       && TREE_OVERFLOW (TYPE_SIZE_UNIT (type)))
8700     {
8701       error ("size of array %qs is too large", name);
8702       /* If we proceed with the array type as it is, we'll eventually
8703          crash in tree_low_cst().  */
8704       type = error_mark_node;
8705     }
8706
8707   if ((decl_context == FIELD || decl_context == PARM)
8708       && !processing_template_decl
8709       && variably_modified_type_p (type, NULL_TREE))
8710     {
8711       if (decl_context == FIELD)
8712         error ("data member may not have variably modified type %qT", type);
8713       else
8714         error ("parameter may not have variably modified type %qT", type);
8715       type = error_mark_node;
8716     }
8717
8718   if (explicitp == 1 || (explicitp && friendp))
8719     {
8720       /* [dcl.fct.spec] The explicit specifier shall only be used in
8721          declarations of constructors within a class definition.  */
8722       error ("only declarations of constructors can be %<explicit%>");
8723       explicitp = 0;
8724     }
8725
8726   if (storage_class == sc_mutable)
8727     {
8728       if (decl_context != FIELD || friendp)
8729         {
8730           error ("non-member %qs cannot be declared %<mutable%>", name);
8731           storage_class = sc_none;
8732         }
8733       else if (decl_context == TYPENAME || declspecs->specs[(int)ds_typedef])
8734         {
8735           error ("non-object member %qs cannot be declared %<mutable%>", name);
8736           storage_class = sc_none;
8737         }
8738       else if (TREE_CODE (type) == FUNCTION_TYPE
8739                || TREE_CODE (type) == METHOD_TYPE)
8740         {
8741           error ("function %qs cannot be declared %<mutable%>", name);
8742           storage_class = sc_none;
8743         }
8744       else if (staticp)
8745         {
8746           error ("static %qs cannot be declared %<mutable%>", name);
8747           storage_class = sc_none;
8748         }
8749       else if (type_quals & TYPE_QUAL_CONST)
8750         {
8751           error ("const %qs cannot be declared %<mutable%>", name);
8752           storage_class = sc_none;
8753         }
8754     }
8755
8756   /* If this is declaring a typedef name, return a TYPE_DECL.  */
8757   if (declspecs->specs[(int)ds_typedef] && decl_context != TYPENAME)
8758     {
8759       tree decl;
8760
8761       /* Note that the grammar rejects storage classes
8762          in typenames, fields or parameters.  */
8763       if (current_lang_name == lang_name_java)
8764         TYPE_FOR_JAVA (type) = 1;
8765
8766       /* This declaration:
8767
8768            typedef void f(int) const;
8769
8770          declares a function type which is not a member of any
8771          particular class, but which is cv-qualified; for
8772          example "f S::*" declares a pointer to a const-qualified
8773          member function of S.  We record the cv-qualification in the
8774          function type.  */
8775       if (memfn_quals && TREE_CODE (type) == FUNCTION_TYPE)
8776         {
8777           type = cp_build_qualified_type (type, memfn_quals);
8778           
8779           /* We have now dealt with these qualifiers.  */
8780           memfn_quals = TYPE_UNQUALIFIED;
8781         }
8782
8783       if (decl_context == FIELD)
8784         decl = build_lang_decl (TYPE_DECL, unqualified_id, type);
8785       else
8786         decl = build_decl (input_location, TYPE_DECL, unqualified_id, type);
8787       if (id_declarator && declarator->u.id.qualifying_scope) {
8788         error_at (DECL_SOURCE_LOCATION (decl), 
8789                   "typedef name may not be a nested-name-specifier");
8790         TREE_TYPE (decl) = error_mark_node;
8791       }
8792
8793       if (decl_context != FIELD)
8794         {
8795           if (!current_function_decl)
8796             DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
8797           else if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (current_function_decl)
8798                    || (DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P
8799                        (current_function_decl)))
8800             /* The TYPE_DECL is "abstract" because there will be
8801                clones of this constructor/destructor, and there will
8802                be copies of this TYPE_DECL generated in those
8803                clones.  */
8804             DECL_ABSTRACT (decl) = 1;
8805         }
8806       else if (constructor_name_p (unqualified_id, current_class_type))
8807         permerror (input_location, "ISO C++ forbids nested type %qD with same name "
8808                    "as enclosing class",
8809                    unqualified_id);
8810
8811       /* If the user declares "typedef struct {...} foo" then the
8812          struct will have an anonymous name.  Fill that name in now.
8813          Nothing can refer to it, so nothing needs know about the name
8814          change.  */
8815       if (type != error_mark_node
8816           && unqualified_id
8817           && TYPE_NAME (type)
8818           && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL
8819           && TYPE_ANONYMOUS_P (type)
8820           && cp_type_quals (type) == TYPE_UNQUALIFIED)
8821         {
8822           tree t;
8823
8824           /* Replace the anonymous name with the real name everywhere.  */
8825           for (t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
8826             {
8827               if (ANON_AGGRNAME_P (TYPE_IDENTIFIER (t)))
8828                 {
8829                   debug_hooks->set_name (t, decl);
8830                   TYPE_NAME (t) = decl;
8831                 }
8832             }
8833
8834           if (TYPE_LANG_SPECIFIC (type))
8835             TYPE_WAS_ANONYMOUS (type) = 1;
8836
8837           /* If this is a typedef within a template class, the nested
8838              type is a (non-primary) template.  The name for the
8839              template needs updating as well.  */
8840           if (TYPE_LANG_SPECIFIC (type) && CLASSTYPE_TEMPLATE_INFO (type))
8841             DECL_NAME (CLASSTYPE_TI_TEMPLATE (type))
8842               = TYPE_IDENTIFIER (type);
8843
8844           /* FIXME remangle member functions; member functions of a
8845              type with external linkage have external linkage.  */
8846         }
8847
8848       if (signed_p
8849           || (typedef_decl && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl)))
8850         C_TYPEDEF_EXPLICITLY_SIGNED (decl) = 1;
8851
8852       bad_specifiers (decl, "type", virtualp,
8853                       memfn_quals != TYPE_UNQUALIFIED,
8854                       inlinep, friendp, raises != NULL_TREE);
8855
8856       return decl;
8857     }
8858
8859   /* Detect the case of an array type of unspecified size
8860      which came, as such, direct from a typedef name.
8861      We must copy the type, so that the array's domain can be
8862      individually set by the object's initializer.  */
8863
8864   if (type && typedef_type
8865       && TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type)
8866       && TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (typedef_type))
8867     type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
8868
8869   /* Detect where we're using a typedef of function type to declare a
8870      function. PARMS will not be set, so we must create it now.  */
8871
8872   if (type == typedef_type && TREE_CODE (type) == FUNCTION_TYPE)
8873     {
8874       tree decls = NULL_TREE;
8875       tree args;
8876
8877       for (args = TYPE_ARG_TYPES (type); args; args = TREE_CHAIN (args))
8878         {
8879           tree decl = cp_build_parm_decl (NULL_TREE, TREE_VALUE (args));
8880
8881           TREE_CHAIN (decl) = decls;
8882           decls = decl;
8883         }
8884
8885       parms = nreverse (decls);
8886
8887       if (decl_context != TYPENAME)
8888         {
8889           /* A cv-qualifier-seq shall only be part of the function type
8890              for a non-static member function. [8.3.5/4 dcl.fct] */
8891           if (cp_type_quals (type) != TYPE_UNQUALIFIED
8892               && (current_class_type == NULL_TREE || staticp) )
8893             {
8894               error (staticp
8895                      ? G_("qualified function types cannot be used to "
8896                           "declare static member functions")
8897                      : G_("qualified function types cannot be used to "
8898                           "declare free functions"));
8899               type = TYPE_MAIN_VARIANT (type);
8900             }
8901
8902           /* The qualifiers on the function type become the qualifiers on
8903              the non-static member function. */
8904           memfn_quals |= cp_type_quals (type);
8905         }
8906     }
8907
8908   /* If this is a type name (such as, in a cast or sizeof),
8909      compute the type and return it now.  */
8910
8911   if (decl_context == TYPENAME)
8912     {
8913       /* Note that the grammar rejects storage classes
8914          in typenames, fields or parameters.  */
8915       if (type_quals != TYPE_UNQUALIFIED)
8916         type_quals = TYPE_UNQUALIFIED;
8917
8918       /* Special case: "friend class foo" looks like a TYPENAME context.  */
8919       if (friendp)
8920         {
8921           if (type_quals != TYPE_UNQUALIFIED)
8922             {
8923               error ("type qualifiers specified for friend class declaration");
8924               type_quals = TYPE_UNQUALIFIED;
8925             }
8926           if (inlinep)
8927             {
8928               error ("%<inline%> specified for friend class declaration");
8929               inlinep = 0;
8930             }
8931
8932           if (!current_aggr)
8933             {
8934               /* Don't allow friend declaration without a class-key.  */
8935               if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
8936                 permerror (input_location, "template parameters cannot be friends");
8937               else if (TREE_CODE (type) == TYPENAME_TYPE)
8938                 permerror (input_location, "friend declaration requires class-key, "
8939                            "i.e. %<friend class %T::%D%>",
8940                            TYPE_CONTEXT (type), TYPENAME_TYPE_FULLNAME (type));
8941               else
8942                 permerror (input_location, "friend declaration requires class-key, "
8943                            "i.e. %<friend %#T%>",
8944                            type);
8945             }
8946
8947           /* Only try to do this stuff if we didn't already give up.  */
8948           if (type != integer_type_node)
8949             {
8950               /* A friendly class?  */
8951               if (current_class_type)
8952                 make_friend_class (current_class_type, TYPE_MAIN_VARIANT (type),
8953                                    /*complain=*/true);
8954               else
8955                 error ("trying to make class %qT a friend of global scope",
8956                        type);
8957
8958               type = void_type_node;
8959             }
8960         }
8961       else if (memfn_quals)
8962         {
8963           if (ctype == NULL_TREE
8964               && TREE_CODE (type) == METHOD_TYPE)
8965             ctype = TYPE_METHOD_BASETYPE (type);
8966
8967           if (ctype)
8968             type = build_memfn_type (type, ctype, memfn_quals);
8969           /* Core issue #547: need to allow this in template type args.  */
8970           else if (template_type_arg && TREE_CODE (type) == FUNCTION_TYPE)
8971             type = cp_build_qualified_type (type, memfn_quals);
8972           else
8973             error ("invalid qualifiers on non-member function type");
8974         }
8975
8976       return type;
8977     }
8978   else if (unqualified_id == NULL_TREE && decl_context != PARM
8979            && decl_context != CATCHPARM
8980            && TREE_CODE (type) != UNION_TYPE
8981            && ! bitfield)
8982     {
8983       error ("abstract declarator %qT used as declaration", type);
8984       return error_mark_node;
8985     }
8986
8987   /* Only functions may be declared using an operator-function-id.  */
8988   if (unqualified_id
8989       && IDENTIFIER_OPNAME_P (unqualified_id)
8990       && TREE_CODE (type) != FUNCTION_TYPE
8991       && TREE_CODE (type) != METHOD_TYPE)
8992     {
8993       error ("declaration of %qD as non-function", unqualified_id);
8994       return error_mark_node;
8995     }
8996
8997   /* We don't check parameter types here because we can emit a better
8998      error message later.  */
8999   if (decl_context != PARM)
9000     {
9001       type = check_var_type (unqualified_id, type);
9002       if (type == error_mark_node)
9003         return error_mark_node;
9004     }
9005
9006   /* Now create the decl, which may be a VAR_DECL, a PARM_DECL
9007      or a FUNCTION_DECL, depending on DECL_CONTEXT and TYPE.  */
9008
9009   if (decl_context == PARM || decl_context == CATCHPARM)
9010     {
9011       if (ctype || in_namespace)
9012         error ("cannot use %<::%> in parameter declaration");
9013
9014       /* A parameter declared as an array of T is really a pointer to T.
9015          One declared as a function is really a pointer to a function.
9016          One declared as a member is really a pointer to member.  */
9017
9018       if (TREE_CODE (type) == ARRAY_TYPE)
9019         {
9020           /* Transfer const-ness of array into that of type pointed to.  */
9021           type = build_pointer_type (TREE_TYPE (type));
9022           type_quals = TYPE_UNQUALIFIED;
9023         }
9024       else if (TREE_CODE (type) == FUNCTION_TYPE)
9025         type = build_pointer_type (type);
9026     }
9027
9028   {
9029     tree decl;
9030
9031     if (decl_context == PARM)
9032       {
9033         decl = cp_build_parm_decl (unqualified_id, type);
9034
9035         bad_specifiers (decl, "parameter", virtualp,
9036                         memfn_quals != TYPE_UNQUALIFIED,
9037                         inlinep, friendp, raises != NULL_TREE);
9038       }
9039     else if (decl_context == FIELD)
9040       {
9041         /* The C99 flexible array extension.  */
9042         if (!staticp && TREE_CODE (type) == ARRAY_TYPE
9043             && TYPE_DOMAIN (type) == NULL_TREE)
9044           {
9045             tree itype = compute_array_index_type (dname, integer_zero_node);
9046             type = build_cplus_array_type (TREE_TYPE (type), itype);
9047           }
9048
9049         if (type == error_mark_node)
9050           {
9051             /* Happens when declaring arrays of sizes which
9052                are error_mark_node, for example.  */
9053             decl = NULL_TREE;
9054           }
9055         else if (in_namespace && !friendp)
9056           {
9057             /* Something like struct S { int N::j; };  */
9058             error ("invalid use of %<::%>");
9059             return error_mark_node;
9060           }
9061         else if (TREE_CODE (type) == FUNCTION_TYPE)
9062           {
9063             int publicp = 0;
9064             tree function_context;
9065
9066             if (friendp == 0)
9067               {
9068                 if (ctype == NULL_TREE)
9069                   ctype = current_class_type;
9070
9071                 if (ctype == NULL_TREE)
9072                   {
9073                     error ("can't make %qD into a method -- not in a class",
9074                            unqualified_id);
9075                     return error_mark_node;
9076                   }
9077
9078                 /* ``A union may [ ... ] not [ have ] virtual functions.''
9079                    ARM 9.5 */
9080                 if (virtualp && TREE_CODE (ctype) == UNION_TYPE)
9081                   {
9082                     error ("function %qD declared virtual inside a union",
9083                            unqualified_id);
9084                     return error_mark_node;
9085                   }
9086
9087                 if (NEW_DELETE_OPNAME_P (unqualified_id))
9088                   {
9089                     if (virtualp)
9090                       {
9091                         error ("%qD cannot be declared virtual, since it "
9092                                "is always static",
9093                                unqualified_id);
9094                         virtualp = 0;
9095                       }
9096                   }
9097                 else if (staticp < 2)
9098                   type = build_memfn_type (type, ctype, memfn_quals);
9099               }
9100
9101             /* Check that the name used for a destructor makes sense.  */
9102             if (sfk == sfk_destructor)
9103               {
9104                 tree uqname = id_declarator->u.id.unqualified_name;
9105
9106                 if (!ctype)
9107                   {
9108                     gcc_assert (friendp);
9109                     error ("expected qualified name in friend declaration "
9110                            "for destructor %qD", uqname);
9111                     return error_mark_node;
9112                   }
9113
9114                 if (!check_dtor_name (ctype, TREE_OPERAND (uqname, 0)))
9115                   {
9116                     error ("declaration of %qD as member of %qT",
9117                            uqname, ctype);
9118                     return error_mark_node;
9119                   }
9120               }
9121             else if (sfk == sfk_constructor && friendp)
9122               {
9123                 error ("expected qualified name in friend declaration "
9124                        "for constructor %qD",
9125                        id_declarator->u.id.unqualified_name);
9126                 return error_mark_node;
9127               }
9128
9129             /* Tell grokfndecl if it needs to set TREE_PUBLIC on the node.  */
9130             function_context = (ctype != NULL_TREE) ?
9131               decl_function_context (TYPE_MAIN_DECL (ctype)) : NULL_TREE;
9132             publicp = (! friendp || ! staticp)
9133               && function_context == NULL_TREE;
9134             decl = grokfndecl (ctype, type,
9135                                TREE_CODE (unqualified_id) != TEMPLATE_ID_EXPR
9136                                ? unqualified_id : dname,
9137                                parms,
9138                                unqualified_id,
9139                                virtualp, flags, memfn_quals, raises,
9140                                friendp ? -1 : 0, friendp, publicp, inlinep,
9141                                sfk,
9142                                funcdef_flag, template_count, in_namespace,
9143                                attrlist, declarator->id_loc);
9144             if (decl == NULL_TREE)
9145               return error_mark_node;
9146 #if 0
9147             /* This clobbers the attrs stored in `decl' from `attrlist'.  */
9148             /* The decl and setting of decl_attr is also turned off.  */
9149             decl = build_decl_attribute_variant (decl, decl_attr);
9150 #endif
9151
9152             /* [class.conv.ctor]
9153
9154                A constructor declared without the function-specifier
9155                explicit that can be called with a single parameter
9156                specifies a conversion from the type of its first
9157                parameter to the type of its class.  Such a constructor
9158                is called a converting constructor.  */
9159             if (explicitp == 2)
9160               DECL_NONCONVERTING_P (decl) = 1;
9161           }
9162         else if (TREE_CODE (type) == METHOD_TYPE)
9163           {
9164             /* We only get here for friend declarations of
9165                members of other classes.  */
9166             /* All method decls are public, so tell grokfndecl to set
9167                TREE_PUBLIC, also.  */
9168             decl = grokfndecl (ctype, type,
9169                                TREE_CODE (unqualified_id) != TEMPLATE_ID_EXPR
9170                                ? unqualified_id : dname,
9171                                parms,
9172                                unqualified_id,
9173                                virtualp, flags, memfn_quals, raises,
9174                                friendp ? -1 : 0, friendp, 1, 0, sfk,
9175                                funcdef_flag, template_count, in_namespace,
9176                                attrlist,
9177                                declarator->id_loc);
9178             if (decl == NULL_TREE)
9179               return error_mark_node;
9180           }
9181         else if (!staticp && !dependent_type_p (type)
9182                  && !COMPLETE_TYPE_P (complete_type (type))
9183                  && (TREE_CODE (type) != ARRAY_TYPE || initialized == 0))
9184           {
9185             if (unqualified_id)
9186               error ("field %qD has incomplete type", unqualified_id);
9187             else
9188               error ("name %qT has incomplete type", type);
9189
9190             /* If we're instantiating a template, tell them which
9191                instantiation made the field's type be incomplete.  */
9192             if (current_class_type
9193                 && TYPE_NAME (current_class_type)
9194                 && IDENTIFIER_TEMPLATE (TYPE_IDENTIFIER (current_class_type))
9195                 && declspecs->type
9196                 && declspecs->type == type)
9197               error ("  in instantiation of template %qT",
9198                      current_class_type);
9199
9200             return error_mark_node;
9201           }
9202         else
9203           {
9204             if (friendp)
9205               {
9206                 error ("%qE is neither function nor member function; "
9207                        "cannot be declared friend", unqualified_id);
9208                 friendp = 0;
9209               }
9210             decl = NULL_TREE;
9211           }
9212
9213         if (friendp)
9214           {
9215             /* Friends are treated specially.  */
9216             if (ctype == current_class_type)
9217               ;  /* We already issued a permerror.  */
9218             else if (decl && DECL_NAME (decl))
9219               {
9220                 if (template_class_depth (current_class_type) == 0)
9221                   {
9222                     decl = check_explicit_specialization
9223                       (unqualified_id, decl, template_count,
9224                        2 * funcdef_flag + 4);
9225                     if (decl == error_mark_node)
9226                       return error_mark_node;
9227                   }
9228
9229                 decl = do_friend (ctype, unqualified_id, decl,
9230                                   *attrlist, flags,
9231                                   funcdef_flag);
9232                 return decl;
9233               }
9234             else
9235               return error_mark_node;
9236           }
9237
9238         /* Structure field.  It may not be a function, except for C++.  */
9239
9240         if (decl == NULL_TREE)
9241           {
9242             if (initialized)
9243               {
9244                 if (!staticp)
9245                   {
9246                     /* An attempt is being made to initialize a non-static
9247                        member.  But, from [class.mem]:
9248
9249                        4 A member-declarator can contain a
9250                        constant-initializer only if it declares a static
9251                        member (_class.static_) of integral or enumeration
9252                        type, see _class.static.data_.
9253
9254                        This used to be relatively common practice, but
9255                        the rest of the compiler does not correctly
9256                        handle the initialization unless the member is
9257                        static so we make it static below.  */
9258                     permerror (input_location, "ISO C++ forbids initialization of member %qD",
9259                                unqualified_id);
9260                     permerror (input_location, "making %qD static", unqualified_id);
9261                     staticp = 1;
9262                   }
9263
9264                 if (uses_template_parms (type))
9265                   /* We'll check at instantiation time.  */
9266                   ;
9267                 else if (check_static_variable_definition (unqualified_id,
9268                                                            type))
9269                   /* If we just return the declaration, crashes
9270                      will sometimes occur.  We therefore return
9271                      void_type_node, as if this was a friend
9272                      declaration, to cause callers to completely
9273                      ignore this declaration.  */
9274                   return error_mark_node;
9275               }
9276
9277             if (staticp)
9278               {
9279                 /* C++ allows static class members.  All other work
9280                    for this is done by grokfield.  */
9281                 decl = build_lang_decl (VAR_DECL, unqualified_id, type);
9282                 set_linkage_for_static_data_member (decl);
9283                 /* Even if there is an in-class initialization, DECL
9284                    is considered undefined until an out-of-class
9285                    definition is provided.  */
9286                 DECL_EXTERNAL (decl) = 1;
9287
9288                 if (thread_p)
9289                   DECL_TLS_MODEL (decl) = decl_default_tls_model (decl);
9290               }
9291             else
9292               {
9293                 decl = build_decl (input_location,
9294                                    FIELD_DECL, unqualified_id, type);
9295                 DECL_NONADDRESSABLE_P (decl) = bitfield;
9296                 if (bitfield && !unqualified_id)
9297                   TREE_NO_WARNING (decl) = 1;
9298
9299                 if (storage_class == sc_mutable)
9300                   {
9301                     DECL_MUTABLE_P (decl) = 1;
9302                     storage_class = sc_none;
9303                   }
9304               }
9305
9306             bad_specifiers (decl, "field", virtualp,
9307                             memfn_quals != TYPE_UNQUALIFIED,
9308                             inlinep, friendp, raises != NULL_TREE);
9309           }
9310       }
9311     else if (TREE_CODE (type) == FUNCTION_TYPE
9312              || TREE_CODE (type) == METHOD_TYPE)
9313       {
9314         tree original_name;
9315         int publicp = 0;
9316
9317         if (!unqualified_id)
9318           return error_mark_node;
9319
9320         if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
9321           original_name = dname;
9322         else
9323           original_name = unqualified_id;
9324
9325         if (storage_class == sc_auto)
9326           error ("storage class %<auto%> invalid for function %qs", name);
9327         else if (storage_class == sc_register)
9328           error ("storage class %<register%> invalid for function %qs", name);
9329         else if (thread_p)
9330           error ("storage class %<__thread%> invalid for function %qs", name);
9331
9332         /* Function declaration not at top level.
9333            Storage classes other than `extern' are not allowed
9334            and `extern' makes no difference.  */
9335         if (! toplevel_bindings_p ()
9336             && (storage_class == sc_static
9337                 || declspecs->specs[(int)ds_inline])
9338             && pedantic)
9339           {
9340             if (storage_class == sc_static)
9341               pedwarn (input_location, OPT_pedantic, 
9342                        "%<static%> specified invalid for function %qs "
9343                        "declared out of global scope", name);
9344             else
9345               pedwarn (input_location, OPT_pedantic, 
9346                        "%<inline%> specifier invalid for function %qs "
9347                        "declared out of global scope", name);
9348           }
9349
9350         if (ctype != NULL_TREE
9351             && TREE_CODE (ctype) != NAMESPACE_DECL && !MAYBE_CLASS_TYPE_P (ctype))
9352           {
9353             error ("%q#T is not a class or a namespace", ctype);
9354             ctype = NULL_TREE;
9355           }
9356
9357         if (ctype == NULL_TREE)
9358           {
9359             if (virtualp)
9360               {
9361                 error ("virtual non-class function %qs", name);
9362                 virtualp = 0;
9363               }
9364             else if (sfk == sfk_constructor
9365                      || sfk == sfk_destructor)
9366               {
9367                 error (funcdef_flag
9368                        ? "%qs defined in a non-class scope"
9369                        : "%qs declared in a non-class scope", name);
9370                 sfk = sfk_none;
9371               }
9372           }
9373         else if (TREE_CODE (type) == FUNCTION_TYPE && staticp < 2
9374                  && !NEW_DELETE_OPNAME_P (original_name))
9375           type = build_method_type_directly (ctype,
9376                                              TREE_TYPE (type),
9377                                              TYPE_ARG_TYPES (type));
9378
9379         /* Record presence of `static'.  */
9380         publicp = (ctype != NULL_TREE
9381                    || storage_class == sc_extern
9382                    || storage_class != sc_static);
9383
9384         decl = grokfndecl (ctype, type, original_name, parms, unqualified_id,
9385                            virtualp, flags, memfn_quals, raises,
9386                            1, friendp,
9387                            publicp, inlinep, sfk, funcdef_flag,
9388                            template_count, in_namespace, attrlist,
9389                            declarator->id_loc);
9390         if (decl == NULL_TREE)
9391           return error_mark_node;
9392
9393         if (staticp == 1)
9394           {
9395             int invalid_static = 0;
9396
9397             /* Don't allow a static member function in a class, and forbid
9398                declaring main to be static.  */
9399             if (TREE_CODE (type) == METHOD_TYPE)
9400               {
9401                 permerror (input_location, "cannot declare member function %qD to have "
9402                            "static linkage", decl);
9403                 invalid_static = 1;
9404               }
9405             else if (current_function_decl)
9406               {
9407                 /* FIXME need arm citation */
9408                 error ("cannot declare static function inside another function");
9409                 invalid_static = 1;
9410               }
9411
9412             if (invalid_static)
9413               {
9414                 staticp = 0;
9415                 storage_class = sc_none;
9416               }
9417           }
9418       }
9419     else
9420       {
9421         /* It's a variable.  */
9422
9423         /* An uninitialized decl with `extern' is a reference.  */
9424         decl = grokvardecl (type, unqualified_id,
9425                             declspecs,
9426                             initialized,
9427                             (type_quals & TYPE_QUAL_CONST) != 0,
9428                             ctype ? ctype : in_namespace);
9429         bad_specifiers (decl, "variable", virtualp,
9430                         memfn_quals != TYPE_UNQUALIFIED,
9431                         inlinep, friendp, raises != NULL_TREE);
9432
9433         if (ctype)
9434           {
9435             DECL_CONTEXT (decl) = ctype;
9436             if (staticp == 1)
9437               {
9438                 permerror (input_location, "%<static%> may not be used when defining "
9439                            "(as opposed to declaring) a static data member");
9440                 staticp = 0;
9441                 storage_class = sc_none;
9442               }
9443             if (storage_class == sc_register && TREE_STATIC (decl))
9444               {
9445                 error ("static member %qD declared %<register%>", decl);
9446                 storage_class = sc_none;
9447               }
9448             if (storage_class == sc_extern && pedantic)
9449               {
9450                 pedwarn (input_location, OPT_pedantic, 
9451                          "cannot explicitly declare member %q#D to have "
9452                          "extern linkage", decl);
9453                 storage_class = sc_none;
9454               }
9455           }
9456       }
9457
9458     if (storage_class == sc_extern && initialized && !funcdef_flag)
9459       {
9460         if (toplevel_bindings_p ())
9461           {
9462             /* It's common practice (and completely valid) to have a const
9463                be initialized and declared extern.  */
9464             if (!(type_quals & TYPE_QUAL_CONST))
9465               warning (0, "%qs initialized and declared %<extern%>", name);
9466           }
9467         else
9468           {
9469             error ("%qs has both %<extern%> and initializer", name);
9470             return error_mark_node;
9471           }
9472       }
9473
9474     /* Record `register' declaration for warnings on &
9475        and in case doing stupid register allocation.  */
9476
9477     if (storage_class == sc_register)
9478       DECL_REGISTER (decl) = 1;
9479     else if (storage_class == sc_extern)
9480       DECL_THIS_EXTERN (decl) = 1;
9481     else if (storage_class == sc_static)
9482       DECL_THIS_STATIC (decl) = 1;
9483
9484     /* Record constancy and volatility on the DECL itself .  There's
9485        no need to do this when processing a template; we'll do this
9486        for the instantiated declaration based on the type of DECL.  */
9487     if (!processing_template_decl)
9488       cp_apply_type_quals_to_decl (type_quals, decl);
9489
9490     return decl;
9491   }
9492 }
9493 \f
9494 /* Subroutine of start_function.  Ensure that each of the parameter
9495    types (as listed in PARMS) is complete, as is required for a
9496    function definition.  */
9497
9498 static void
9499 require_complete_types_for_parms (tree parms)
9500 {
9501   for (; parms; parms = TREE_CHAIN (parms))
9502     {
9503       if (dependent_type_p (TREE_TYPE (parms)))
9504         continue;
9505       if (!VOID_TYPE_P (TREE_TYPE (parms))
9506           && complete_type_or_else (TREE_TYPE (parms), parms))
9507         {
9508           relayout_decl (parms);
9509           DECL_ARG_TYPE (parms) = type_passed_as (TREE_TYPE (parms));
9510         }
9511       else
9512         /* grokparms or complete_type_or_else will have already issued
9513            an error.  */
9514         TREE_TYPE (parms) = error_mark_node;
9515     }
9516 }
9517
9518 /* Returns nonzero if T is a local variable.  */
9519
9520 int
9521 local_variable_p (const_tree t)
9522 {
9523   if ((TREE_CODE (t) == VAR_DECL
9524        /* A VAR_DECL with a context that is a _TYPE is a static data
9525           member.  */
9526        && !TYPE_P (CP_DECL_CONTEXT (t))
9527        /* Any other non-local variable must be at namespace scope.  */
9528        && !DECL_NAMESPACE_SCOPE_P (t))
9529       || (TREE_CODE (t) == PARM_DECL))
9530     return 1;
9531
9532   return 0;
9533 }
9534
9535 /* Like local_variable_p, but suitable for use as a tree-walking
9536    function.  */
9537
9538 static tree
9539 local_variable_p_walkfn (tree *tp, int *walk_subtrees,
9540                          void *data ATTRIBUTE_UNUSED)
9541 {
9542   if (local_variable_p (*tp) && !DECL_ARTIFICIAL (*tp))
9543     return *tp;
9544   else if (TYPE_P (*tp))
9545     *walk_subtrees = 0;
9546
9547   return NULL_TREE;
9548 }
9549
9550
9551 /* Check that ARG, which is a default-argument expression for a
9552    parameter DECL, is valid.  Returns ARG, or ERROR_MARK_NODE, if
9553    something goes wrong.  DECL may also be a _TYPE node, rather than a
9554    DECL, if there is no DECL available.  */
9555
9556 tree
9557 check_default_argument (tree decl, tree arg)
9558 {
9559   tree var;
9560   tree decl_type;
9561
9562   if (TREE_CODE (arg) == DEFAULT_ARG)
9563     /* We get a DEFAULT_ARG when looking at an in-class declaration
9564        with a default argument.  Ignore the argument for now; we'll
9565        deal with it after the class is complete.  */
9566     return arg;
9567
9568   if (TYPE_P (decl))
9569     {
9570       decl_type = decl;
9571       decl = NULL_TREE;
9572     }
9573   else
9574     decl_type = TREE_TYPE (decl);
9575
9576   if (arg == error_mark_node
9577       || decl == error_mark_node
9578       || TREE_TYPE (arg) == error_mark_node
9579       || decl_type == error_mark_node)
9580     /* Something already went wrong.  There's no need to check
9581        further.  */
9582     return error_mark_node;
9583
9584   /* [dcl.fct.default]
9585
9586      A default argument expression is implicitly converted to the
9587      parameter type.  */
9588   if (!TREE_TYPE (arg)
9589       || !can_convert_arg (decl_type, TREE_TYPE (arg), arg, LOOKUP_NORMAL))
9590     {
9591       if (decl)
9592         error ("default argument for %q#D has type %qT",
9593                decl, TREE_TYPE (arg));
9594       else
9595         error ("default argument for parameter of type %qT has type %qT",
9596                decl_type, TREE_TYPE (arg));
9597
9598       return error_mark_node;
9599     }
9600
9601   /* [dcl.fct.default]
9602
9603      Local variables shall not be used in default argument
9604      expressions.
9605
9606      The keyword `this' shall not be used in a default argument of a
9607      member function.  */
9608   var = cp_walk_tree_without_duplicates (&arg, local_variable_p_walkfn, NULL);
9609   if (var)
9610     {
9611       error ("default argument %qE uses local variable %qD", arg, var);
9612       return error_mark_node;
9613     }
9614
9615   /* All is well.  */
9616   return arg;
9617 }
9618
9619 /* Returns a deprecated type used within TYPE, or NULL_TREE if none.  */
9620
9621 static tree
9622 type_is_deprecated (tree type)
9623 {
9624   enum tree_code code;
9625   if (TREE_DEPRECATED (type))
9626     return type;
9627   if (TYPE_NAME (type)
9628       && TREE_DEPRECATED (TYPE_NAME (type)))
9629     return type;
9630
9631   code = TREE_CODE (type);
9632
9633   if (code == POINTER_TYPE || code == REFERENCE_TYPE
9634       || code == OFFSET_TYPE || code == FUNCTION_TYPE
9635       || code == METHOD_TYPE || code == ARRAY_TYPE)
9636     return type_is_deprecated (TREE_TYPE (type));
9637
9638   if (TYPE_PTRMEMFUNC_P (type))
9639     return type_is_deprecated
9640       (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
9641
9642   return NULL_TREE;
9643 }
9644
9645 /* Decode the list of parameter types for a function type.
9646    Given the list of things declared inside the parens,
9647    return a list of types.
9648
9649    If this parameter does not end with an ellipsis, we append
9650    void_list_node.
9651
9652    *PARMS is set to the chain of PARM_DECLs created.  */
9653
9654 static tree
9655 grokparms (tree parmlist, tree *parms)
9656 {
9657   tree result = NULL_TREE;
9658   tree decls = NULL_TREE;
9659   tree parm;
9660   int any_error = 0;
9661
9662   for (parm = parmlist; parm != NULL_TREE; parm = TREE_CHAIN (parm))
9663     {
9664       tree type = NULL_TREE;
9665       tree init = TREE_PURPOSE (parm);
9666       tree decl = TREE_VALUE (parm);
9667       const char *errmsg;
9668
9669       if (parm == void_list_node)
9670         break;
9671
9672       if (! decl || TREE_TYPE (decl) == error_mark_node)
9673         continue;
9674
9675       type = TREE_TYPE (decl);
9676       if (VOID_TYPE_P (type))
9677         {
9678           if (same_type_p (type, void_type_node)
9679               && DECL_SELF_REFERENCE_P (type)
9680               && !DECL_NAME (decl) && !result && TREE_CHAIN (parm) == void_list_node)
9681             /* this is a parmlist of `(void)', which is ok.  */
9682             break;
9683           cxx_incomplete_type_error (decl, type);
9684           /* It's not a good idea to actually create parameters of
9685              type `void'; other parts of the compiler assume that a
9686              void type terminates the parameter list.  */
9687           type = error_mark_node;
9688           TREE_TYPE (decl) = error_mark_node;
9689         }
9690
9691       if (type != error_mark_node
9692           && TYPE_FOR_JAVA (type)
9693           && MAYBE_CLASS_TYPE_P (type))
9694         {
9695           error ("parameter %qD has Java class type", decl);
9696           type = error_mark_node;
9697           TREE_TYPE (decl) = error_mark_node;
9698           init = NULL_TREE;
9699         }
9700
9701       if (type != error_mark_node
9702           && (errmsg = targetm.invalid_parameter_type (type)))
9703         {
9704           error (errmsg);
9705           type = error_mark_node;
9706           TREE_TYPE (decl) = error_mark_node;
9707         }
9708
9709       if (type != error_mark_node)
9710         {
9711           if (deprecated_state != DEPRECATED_SUPPRESS)
9712             {
9713               tree deptype = type_is_deprecated (type);
9714               if (deptype)
9715                 warn_deprecated_use (deptype, NULL_TREE);
9716             }
9717
9718           /* Top-level qualifiers on the parameters are
9719              ignored for function types.  */
9720           type = cp_build_qualified_type (type, 0);
9721           if (TREE_CODE (type) == METHOD_TYPE)
9722             {
9723               error ("parameter %qD invalidly declared method type", decl);
9724               type = build_pointer_type (type);
9725               TREE_TYPE (decl) = type;
9726             }
9727           else if (abstract_virtuals_error (decl, type))
9728             any_error = 1;  /* Seems like a good idea.  */
9729           else if (POINTER_TYPE_P (type))
9730             {
9731               /* [dcl.fct]/6, parameter types cannot contain pointers
9732                  (references) to arrays of unknown bound.  */
9733               tree t = TREE_TYPE (type);
9734               int ptr = TYPE_PTR_P (type);
9735
9736               while (1)
9737                 {
9738                   if (TYPE_PTR_P (t))
9739                     ptr = 1;
9740                   else if (TREE_CODE (t) != ARRAY_TYPE)
9741                     break;
9742                   else if (!TYPE_DOMAIN (t))
9743                     break;
9744                   t = TREE_TYPE (t);
9745                 }
9746               if (TREE_CODE (t) == ARRAY_TYPE)
9747                 error ("parameter %qD includes %s to array of unknown "
9748                        "bound %qT",
9749                        decl, ptr ? "pointer" : "reference", t);
9750             }
9751
9752           if (any_error)
9753             init = NULL_TREE;
9754           else if (init && !processing_template_decl)
9755             init = check_default_argument (decl, init);
9756         }
9757
9758       if (TREE_CODE (decl) == PARM_DECL
9759           && FUNCTION_PARAMETER_PACK_P (decl)
9760           && TREE_CHAIN (parm)
9761           && TREE_CHAIN (parm) != void_list_node)
9762         error ("parameter packs must be at the end of the parameter list");
9763
9764       TREE_CHAIN (decl) = decls;
9765       decls = decl;
9766       result = tree_cons (init, type, result);
9767     }
9768   decls = nreverse (decls);
9769   result = nreverse (result);
9770   if (parm)
9771     result = chainon (result, void_list_node);
9772   *parms = decls;
9773
9774   return result;
9775 }
9776
9777 \f
9778 /* D is a constructor or overloaded `operator='.
9779
9780    Let T be the class in which D is declared. Then, this function
9781    returns:
9782
9783    -1 if D's is an ill-formed constructor or copy assignment operator
9784       whose first parameter is of type `T'.
9785    0  if D is not a copy constructor or copy assignment
9786       operator.
9787    1  if D is a copy constructor or copy assignment operator whose
9788       first parameter is a reference to const qualified T.
9789    2  if D is a copy constructor or copy assignment operator whose
9790       first parameter is a reference to non-const qualified T.
9791
9792    This function can be used as a predicate. Positive values indicate
9793    a copy constructor and nonzero values indicate a copy assignment
9794    operator.  */
9795
9796 int
9797 copy_fn_p (const_tree d)
9798 {
9799   tree args;
9800   tree arg_type;
9801   int result = 1;
9802
9803   gcc_assert (DECL_FUNCTION_MEMBER_P (d));
9804
9805   if (TREE_CODE (d) == TEMPLATE_DECL
9806       || (DECL_TEMPLATE_INFO (d)
9807           && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
9808     /* Instantiations of template member functions are never copy
9809        functions.  Note that member functions of templated classes are
9810        represented as template functions internally, and we must
9811        accept those as copy functions.  */
9812     return 0;
9813
9814   args = FUNCTION_FIRST_USER_PARMTYPE (d);
9815   if (!args)
9816     return 0;
9817
9818   arg_type = TREE_VALUE (args);
9819   if (arg_type == error_mark_node)
9820     return 0;
9821
9822   if (TYPE_MAIN_VARIANT (arg_type) == DECL_CONTEXT (d))
9823     {
9824       /* Pass by value copy assignment operator.  */
9825       result = -1;
9826     }
9827   else if (TREE_CODE (arg_type) == REFERENCE_TYPE
9828            && !TYPE_REF_IS_RVALUE (arg_type)
9829            && TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)) == DECL_CONTEXT (d))
9830     {
9831       if (CP_TYPE_CONST_P (TREE_TYPE (arg_type)))
9832         result = 2;
9833     }
9834   else
9835     return 0;
9836
9837   args = TREE_CHAIN (args);
9838
9839   if (args && args != void_list_node && !TREE_PURPOSE (args))
9840     /* There are more non-optional args.  */
9841     return 0;
9842
9843   return result;
9844 }
9845
9846 /* D is a constructor or overloaded `operator='.
9847
9848    Let T be the class in which D is declared. Then, this function
9849    returns true when D is a move constructor or move assignment
9850    operator, false otherwise.  */
9851
9852 bool
9853 move_fn_p (const_tree d)
9854 {
9855   tree args;
9856   tree arg_type;
9857   bool result = false;
9858
9859   gcc_assert (DECL_FUNCTION_MEMBER_P (d));
9860
9861   if (cxx_dialect == cxx98)
9862     /* There are no move constructors if we are in C++98 mode.  */
9863     return false;
9864
9865   if (TREE_CODE (d) == TEMPLATE_DECL
9866       || (DECL_TEMPLATE_INFO (d)
9867          && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
9868     /* Instantiations of template member functions are never copy
9869        functions.  Note that member functions of templated classes are
9870        represented as template functions internally, and we must
9871        accept those as copy functions.  */
9872     return 0;
9873
9874   args = FUNCTION_FIRST_USER_PARMTYPE (d);
9875   if (!args)
9876     return 0;
9877
9878   arg_type = TREE_VALUE (args);
9879   if (arg_type == error_mark_node)
9880     return 0;
9881
9882   if (TREE_CODE (arg_type) == REFERENCE_TYPE
9883       && TYPE_REF_IS_RVALUE (arg_type)
9884       && same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)),
9885                       DECL_CONTEXT (d)))
9886     result = true;
9887
9888   args = TREE_CHAIN (args);
9889
9890   if (args && args != void_list_node && !TREE_PURPOSE (args))
9891     /* There are more non-optional args.  */
9892     return false;
9893
9894   return result;
9895 }
9896
9897 /* Remember any special properties of member function DECL.  */
9898
9899 void
9900 grok_special_member_properties (tree decl)
9901 {
9902   tree class_type;
9903
9904   if (!DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
9905     return;
9906
9907   class_type = DECL_CONTEXT (decl);
9908   if (DECL_CONSTRUCTOR_P (decl))
9909     {
9910       int ctor = copy_fn_p (decl);
9911
9912       if (!DECL_ARTIFICIAL (decl))
9913         TYPE_HAS_USER_CONSTRUCTOR (class_type) = 1;
9914
9915       if (ctor > 0)
9916         {
9917           /* [class.copy]
9918
9919              A non-template constructor for class X is a copy
9920              constructor if its first parameter is of type X&, const
9921              X&, volatile X& or const volatile X&, and either there
9922              are no other parameters or else all other parameters have
9923              default arguments.  */
9924           TYPE_HAS_INIT_REF (class_type) = 1;
9925           if (!DECL_DEFAULTED_FN (decl))
9926             TYPE_HAS_COMPLEX_INIT_REF (class_type) = 1;
9927           if (ctor > 1)
9928             TYPE_HAS_CONST_INIT_REF (class_type) = 1;
9929         }
9930       else if (sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (decl)))
9931         {
9932           TYPE_HAS_DEFAULT_CONSTRUCTOR (class_type) = 1;
9933           if (TREE_CODE (decl) == TEMPLATE_DECL || !DECL_DEFAULTED_FN (decl))
9934             TYPE_HAS_COMPLEX_DFLT (class_type) = 1;
9935         }
9936       else if (is_list_ctor (decl))
9937         TYPE_HAS_LIST_CTOR (class_type) = 1;
9938     }
9939   else if (DECL_OVERLOADED_OPERATOR_P (decl) == NOP_EXPR)
9940     {
9941       /* [class.copy]
9942
9943          A non-template assignment operator for class X is a copy
9944          assignment operator if its parameter is of type X, X&, const
9945          X&, volatile X& or const volatile X&.  */
9946
9947       int assop = copy_fn_p (decl);
9948
9949       if (assop)
9950         {
9951           TYPE_HAS_ASSIGN_REF (class_type) = 1;
9952           if (!DECL_DEFAULTED_FN (decl))
9953             TYPE_HAS_COMPLEX_ASSIGN_REF (class_type) = 1;
9954           if (assop != 1)
9955             TYPE_HAS_CONST_ASSIGN_REF (class_type) = 1;
9956         }
9957     }
9958 }
9959
9960 /* Check a constructor DECL has the correct form.  Complains
9961    if the class has a constructor of the form X(X).  */
9962
9963 int
9964 grok_ctor_properties (const_tree ctype, const_tree decl)
9965 {
9966   int ctor_parm = copy_fn_p (decl);
9967
9968   if (ctor_parm < 0)
9969     {
9970       /* [class.copy]
9971
9972          A declaration of a constructor for a class X is ill-formed if
9973          its first parameter is of type (optionally cv-qualified) X
9974          and either there are no other parameters or else all other
9975          parameters have default arguments.
9976
9977          We *don't* complain about member template instantiations that
9978          have this form, though; they can occur as we try to decide
9979          what constructor to use during overload resolution.  Since
9980          overload resolution will never prefer such a constructor to
9981          the non-template copy constructor (which is either explicitly
9982          or implicitly defined), there's no need to worry about their
9983          existence.  Theoretically, they should never even be
9984          instantiated, but that's hard to forestall.  */
9985       error ("invalid constructor; you probably meant %<%T (const %T&)%>",
9986                 ctype, ctype);
9987       return 0;
9988     }
9989
9990   return 1;
9991 }
9992
9993 /* An operator with this code is unary, but can also be binary.  */
9994
9995 static int
9996 ambi_op_p (enum tree_code code)
9997 {
9998   return (code == INDIRECT_REF
9999           || code == ADDR_EXPR
10000           || code == UNARY_PLUS_EXPR
10001           || code == NEGATE_EXPR
10002           || code == PREINCREMENT_EXPR
10003           || code == PREDECREMENT_EXPR);
10004 }
10005
10006 /* An operator with this name can only be unary.  */
10007
10008 static int
10009 unary_op_p (enum tree_code code)
10010 {
10011   return (code == TRUTH_NOT_EXPR
10012           || code == BIT_NOT_EXPR
10013           || code == COMPONENT_REF
10014           || code == TYPE_EXPR);
10015 }
10016
10017 /* DECL is a declaration for an overloaded operator.  If COMPLAIN is true,
10018    errors are issued for invalid declarations.  */
10019
10020 bool
10021 grok_op_properties (tree decl, bool complain)
10022 {
10023   tree argtypes = TYPE_ARG_TYPES (TREE_TYPE (decl));
10024   tree argtype;
10025   int methodp = (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE);
10026   tree name = DECL_NAME (decl);
10027   enum tree_code operator_code;
10028   int arity;
10029   bool ellipsis_p;
10030   tree class_type;
10031
10032   /* Count the number of arguments and check for ellipsis.  */
10033   for (argtype = argtypes, arity = 0;
10034        argtype && argtype != void_list_node;
10035        argtype = TREE_CHAIN (argtype))
10036     ++arity;
10037   ellipsis_p = !argtype;
10038
10039   class_type = DECL_CONTEXT (decl);
10040   if (class_type && !CLASS_TYPE_P (class_type))
10041     class_type = NULL_TREE;
10042
10043   if (DECL_CONV_FN_P (decl))
10044     operator_code = TYPE_EXPR;
10045   else
10046     do
10047       {
10048 #define DEF_OPERATOR(NAME, CODE, MANGLING, ARITY, ASSN_P)       \
10049         if (ansi_opname (CODE) == name)                         \
10050           {                                                     \
10051             operator_code = (CODE);                             \
10052             break;                                              \
10053           }                                                     \
10054         else if (ansi_assopname (CODE) == name)                 \
10055           {                                                     \
10056             operator_code = (CODE);                             \
10057             DECL_ASSIGNMENT_OPERATOR_P (decl) = 1;              \
10058             break;                                              \
10059           }
10060
10061 #include "operators.def"
10062 #undef DEF_OPERATOR
10063
10064         gcc_unreachable ();
10065       }
10066     while (0);
10067   gcc_assert (operator_code != MAX_TREE_CODES);
10068   SET_OVERLOADED_OPERATOR_CODE (decl, operator_code);
10069
10070   if (class_type)
10071     switch (operator_code)
10072       {
10073       case NEW_EXPR:
10074         TYPE_HAS_NEW_OPERATOR (class_type) = 1;
10075         break;
10076
10077       case DELETE_EXPR:
10078         TYPE_GETS_DELETE (class_type) |= 1;
10079         break;
10080
10081       case VEC_NEW_EXPR:
10082         TYPE_HAS_ARRAY_NEW_OPERATOR (class_type) = 1;
10083         break;
10084
10085       case VEC_DELETE_EXPR:
10086         TYPE_GETS_DELETE (class_type) |= 2;
10087         break;
10088
10089       default:
10090         break;
10091       }
10092
10093     /* [basic.std.dynamic.allocation]/1:
10094
10095        A program is ill-formed if an allocation function is declared
10096        in a namespace scope other than global scope or declared static
10097        in global scope.
10098
10099        The same also holds true for deallocation functions.  */
10100   if (operator_code == NEW_EXPR || operator_code == VEC_NEW_EXPR
10101       || operator_code == DELETE_EXPR || operator_code == VEC_DELETE_EXPR)
10102     {
10103       if (DECL_NAMESPACE_SCOPE_P (decl))
10104         {
10105           if (CP_DECL_CONTEXT (decl) != global_namespace)
10106             {
10107               error ("%qD may not be declared within a namespace", decl);
10108               return false;
10109             }
10110           else if (!TREE_PUBLIC (decl))
10111             {
10112               error ("%qD may not be declared as static", decl);
10113               return false;
10114             }
10115         }
10116     }
10117
10118   if (operator_code == NEW_EXPR || operator_code == VEC_NEW_EXPR)
10119     {
10120       TREE_TYPE (decl) = coerce_new_type (TREE_TYPE (decl));
10121       DECL_IS_OPERATOR_NEW (decl) = 1;
10122     }
10123   else if (operator_code == DELETE_EXPR || operator_code == VEC_DELETE_EXPR)
10124     TREE_TYPE (decl) = coerce_delete_type (TREE_TYPE (decl));
10125   else
10126     {
10127       /* An operator function must either be a non-static member function
10128          or have at least one parameter of a class, a reference to a class,
10129          an enumeration, or a reference to an enumeration.  13.4.0.6 */
10130       if (! methodp || DECL_STATIC_FUNCTION_P (decl))
10131         {
10132           if (operator_code == TYPE_EXPR
10133               || operator_code == CALL_EXPR
10134               || operator_code == COMPONENT_REF
10135               || operator_code == ARRAY_REF
10136               || operator_code == NOP_EXPR)
10137             {
10138               error ("%qD must be a nonstatic member function", decl);
10139               return false;
10140             }
10141           else
10142             {
10143               tree p;
10144
10145               if (DECL_STATIC_FUNCTION_P (decl))
10146                 {
10147                   error ("%qD must be either a non-static member "
10148                          "function or a non-member function", decl);
10149                   return false;
10150                 }
10151
10152               for (p = argtypes; p && p != void_list_node; p = TREE_CHAIN (p))
10153                 {
10154                   tree arg = non_reference (TREE_VALUE (p));
10155                   if (arg == error_mark_node)
10156                     return false;
10157
10158                   /* MAYBE_CLASS_TYPE_P, rather than CLASS_TYPE_P, is used
10159                      because these checks are performed even on
10160                      template functions.  */
10161                   if (MAYBE_CLASS_TYPE_P (arg)
10162                       || TREE_CODE (arg) == ENUMERAL_TYPE)
10163                     break;
10164                 }
10165
10166               if (!p || p == void_list_node)
10167                 {
10168                   if (complain)
10169                     error ("%qD must have an argument of class or "
10170                            "enumerated type", decl);
10171                   return false;
10172                 }
10173             }
10174         }
10175
10176       /* There are no restrictions on the arguments to an overloaded
10177          "operator ()".  */
10178       if (operator_code == CALL_EXPR)
10179         return true;
10180
10181       /* Warn about conversion operators that will never be used.  */
10182       if (IDENTIFIER_TYPENAME_P (name)
10183           && ! DECL_TEMPLATE_INFO (decl)
10184           && warn_conversion
10185           /* Warn only declaring the function; there is no need to
10186              warn again about out-of-class definitions.  */
10187           && class_type == current_class_type)
10188         {
10189           tree t = TREE_TYPE (name);
10190           int ref = (TREE_CODE (t) == REFERENCE_TYPE);
10191           const char *what = 0;
10192
10193           if (ref)
10194             t = TYPE_MAIN_VARIANT (TREE_TYPE (t));
10195
10196           if (TREE_CODE (t) == VOID_TYPE)
10197             what = "void";
10198           else if (class_type)
10199             {
10200               if (t == class_type)
10201                 what = "the same type";
10202               /* Don't force t to be complete here.  */
10203               else if (MAYBE_CLASS_TYPE_P (t)
10204                        && COMPLETE_TYPE_P (t)
10205                        && DERIVED_FROM_P (t, class_type))
10206                 what = "a base class";
10207             }
10208
10209           if (what)
10210             warning (OPT_Wconversion, "conversion to %s%s will never use a type "
10211                      "conversion operator",
10212                      ref ? "a reference to " : "", what);
10213         }
10214
10215       if (operator_code == COND_EXPR)
10216         {
10217           /* 13.4.0.3 */
10218           error ("ISO C++ prohibits overloading operator ?:");
10219           return false;
10220         }
10221       else if (ellipsis_p)
10222         {
10223           error ("%qD must not have variable number of arguments", decl);
10224           return false;
10225         }
10226       else if (ambi_op_p (operator_code))
10227         {
10228           if (arity == 1)
10229             /* We pick the one-argument operator codes by default, so
10230                we don't have to change anything.  */
10231             ;
10232           else if (arity == 2)
10233             {
10234               /* If we thought this was a unary operator, we now know
10235                  it to be a binary operator.  */
10236               switch (operator_code)
10237                 {
10238                 case INDIRECT_REF:
10239                   operator_code = MULT_EXPR;
10240                   break;
10241
10242                 case ADDR_EXPR:
10243                   operator_code = BIT_AND_EXPR;
10244                   break;
10245
10246                 case UNARY_PLUS_EXPR:
10247                   operator_code = PLUS_EXPR;
10248                   break;
10249
10250                 case NEGATE_EXPR:
10251                   operator_code = MINUS_EXPR;
10252                   break;
10253
10254                 case PREINCREMENT_EXPR:
10255                   operator_code = POSTINCREMENT_EXPR;
10256                   break;
10257
10258                 case PREDECREMENT_EXPR:
10259                   operator_code = POSTDECREMENT_EXPR;
10260                   break;
10261
10262                 default:
10263                   gcc_unreachable ();
10264                 }
10265
10266               SET_OVERLOADED_OPERATOR_CODE (decl, operator_code);
10267
10268               if ((operator_code == POSTINCREMENT_EXPR
10269                    || operator_code == POSTDECREMENT_EXPR)
10270                   && ! processing_template_decl
10271                   && ! same_type_p (TREE_VALUE (TREE_CHAIN (argtypes)), integer_type_node))
10272                 {
10273                   if (methodp)
10274                     error ("postfix %qD must take %<int%> as its argument",
10275                            decl);
10276                   else
10277                     error ("postfix %qD must take %<int%> as its second "
10278                            "argument", decl);
10279                   return false;
10280                 }
10281             }
10282           else
10283             {
10284               if (methodp)
10285                 error ("%qD must take either zero or one argument", decl);
10286               else
10287                 error ("%qD must take either one or two arguments", decl);
10288               return false;
10289             }
10290
10291           /* More Effective C++ rule 6.  */
10292           if (warn_ecpp
10293               && (operator_code == POSTINCREMENT_EXPR
10294                   || operator_code == POSTDECREMENT_EXPR
10295                   || operator_code == PREINCREMENT_EXPR
10296                   || operator_code == PREDECREMENT_EXPR))
10297             {
10298               tree arg = TREE_VALUE (argtypes);
10299               tree ret = TREE_TYPE (TREE_TYPE (decl));
10300               if (methodp || TREE_CODE (arg) == REFERENCE_TYPE)
10301                 arg = TREE_TYPE (arg);
10302               arg = TYPE_MAIN_VARIANT (arg);
10303               if (operator_code == PREINCREMENT_EXPR
10304                   || operator_code == PREDECREMENT_EXPR)
10305                 {
10306                   if (TREE_CODE (ret) != REFERENCE_TYPE
10307                       || !same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (ret)),
10308                                        arg))
10309                     warning (OPT_Weffc__, "prefix %qD should return %qT", decl,
10310                              build_reference_type (arg));
10311                 }
10312               else
10313                 {
10314                   if (!same_type_p (TYPE_MAIN_VARIANT (ret), arg))
10315                     warning (OPT_Weffc__, "postfix %qD should return %qT", decl, arg);
10316                 }
10317             }
10318         }
10319       else if (unary_op_p (operator_code))
10320         {
10321           if (arity != 1)
10322             {
10323               if (methodp)
10324                 error ("%qD must take %<void%>", decl);
10325               else
10326                 error ("%qD must take exactly one argument", decl);
10327               return false;
10328             }
10329         }
10330       else /* if (binary_op_p (operator_code)) */
10331         {
10332           if (arity != 2)
10333             {
10334               if (methodp)
10335                 error ("%qD must take exactly one argument", decl);
10336               else
10337                 error ("%qD must take exactly two arguments", decl);
10338               return false;
10339             }
10340
10341           /* More Effective C++ rule 7.  */
10342           if (warn_ecpp
10343               && (operator_code == TRUTH_ANDIF_EXPR
10344                   || operator_code == TRUTH_ORIF_EXPR
10345                   || operator_code == COMPOUND_EXPR))
10346             warning (OPT_Weffc__, "user-defined %qD always evaluates both arguments",
10347                      decl);
10348         }
10349
10350       /* Effective C++ rule 23.  */
10351       if (warn_ecpp
10352           && arity == 2
10353           && !DECL_ASSIGNMENT_OPERATOR_P (decl)
10354           && (operator_code == PLUS_EXPR
10355               || operator_code == MINUS_EXPR
10356               || operator_code == TRUNC_DIV_EXPR
10357               || operator_code == MULT_EXPR
10358               || operator_code == TRUNC_MOD_EXPR)
10359           && TREE_CODE (TREE_TYPE (TREE_TYPE (decl))) == REFERENCE_TYPE)
10360         warning (OPT_Weffc__, "%qD should return by value", decl);
10361
10362       /* [over.oper]/8 */
10363       for (; argtypes && argtypes != void_list_node;
10364           argtypes = TREE_CHAIN (argtypes))
10365         if (TREE_PURPOSE (argtypes))
10366           {
10367             TREE_PURPOSE (argtypes) = NULL_TREE;
10368             if (operator_code == POSTINCREMENT_EXPR
10369                 || operator_code == POSTDECREMENT_EXPR)
10370               {
10371                 pedwarn (input_location, OPT_pedantic, "%qD cannot have default arguments", 
10372                          decl);
10373               }
10374             else
10375               {
10376                 error ("%qD cannot have default arguments", decl);
10377                 return false;
10378               }
10379           }
10380     }
10381   return true;
10382 }
10383 \f
10384 /* Return a string giving the keyword associate with CODE.  */
10385
10386 static const char *
10387 tag_name (enum tag_types code)
10388 {
10389   switch (code)
10390     {
10391     case record_type:
10392       return "struct";
10393     case class_type:
10394       return "class";
10395     case union_type:
10396       return "union";
10397     case enum_type:
10398       return "enum";
10399     case typename_type:
10400       return "typename";
10401     default:
10402       gcc_unreachable ();
10403     }
10404 }
10405
10406 /* Name lookup in an elaborated-type-specifier (after the keyword
10407    indicated by TAG_CODE) has found the TYPE_DECL DECL.  If the
10408    elaborated-type-specifier is invalid, issue a diagnostic and return
10409    error_mark_node; otherwise, return the *_TYPE to which it referred.
10410    If ALLOW_TEMPLATE_P is true, TYPE may be a class template.  */
10411
10412 tree
10413 check_elaborated_type_specifier (enum tag_types tag_code,
10414                                  tree decl,
10415                                  bool allow_template_p)
10416 {
10417   tree type;
10418
10419   /* In the case of:
10420
10421        struct S { struct S *p; };
10422
10423      name lookup will find the TYPE_DECL for the implicit "S::S"
10424      typedef.  Adjust for that here.  */
10425   if (DECL_SELF_REFERENCE_P (decl))
10426     decl = TYPE_NAME (TREE_TYPE (decl));
10427
10428   type = TREE_TYPE (decl);
10429
10430   /* Check TEMPLATE_TYPE_PARM first because DECL_IMPLICIT_TYPEDEF_P
10431      is false for this case as well.  */
10432   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
10433     {
10434       error ("using template type parameter %qT after %qs",
10435              type, tag_name (tag_code));
10436       return error_mark_node;
10437     }
10438   /*   [dcl.type.elab]
10439
10440        If the identifier resolves to a typedef-name or a template
10441        type-parameter, the elaborated-type-specifier is ill-formed.
10442
10443      In other words, the only legitimate declaration to use in the
10444      elaborated type specifier is the implicit typedef created when
10445      the type is declared.  */
10446   else if (!DECL_IMPLICIT_TYPEDEF_P (decl)
10447            && tag_code != typename_type)
10448     {
10449       error ("using typedef-name %qD after %qs", decl, tag_name (tag_code));
10450       error ("%q+D has a previous declaration here", decl);
10451       return error_mark_node;
10452     }
10453   else if (TREE_CODE (type) != RECORD_TYPE
10454            && TREE_CODE (type) != UNION_TYPE
10455            && tag_code != enum_type
10456            && tag_code != typename_type)
10457     {
10458       error ("%qT referred to as %qs", type, tag_name (tag_code));
10459       error ("%q+T has a previous declaration here", type);
10460       return error_mark_node;
10461     }
10462   else if (TREE_CODE (type) != ENUMERAL_TYPE
10463            && tag_code == enum_type)
10464     {
10465       error ("%qT referred to as enum", type);
10466       error ("%q+T has a previous declaration here", type);
10467       return error_mark_node;
10468     }
10469   else if (!allow_template_p
10470            && TREE_CODE (type) == RECORD_TYPE
10471            && CLASSTYPE_IS_TEMPLATE (type))
10472     {
10473       /* If a class template appears as elaborated type specifier
10474          without a template header such as:
10475
10476            template <class T> class C {};
10477            void f(class C);             // No template header here
10478
10479          then the required template argument is missing.  */
10480       error ("template argument required for %<%s %T%>",
10481              tag_name (tag_code),
10482              DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)));
10483       return error_mark_node;
10484     }
10485
10486   return type;
10487 }
10488
10489 /* Lookup NAME in elaborate type specifier in scope according to
10490    SCOPE and issue diagnostics if necessary.
10491    Return *_TYPE node upon success, NULL_TREE when the NAME is not
10492    found, and ERROR_MARK_NODE for type error.  */
10493
10494 static tree
10495 lookup_and_check_tag (enum tag_types tag_code, tree name,
10496                       tag_scope scope, bool template_header_p)
10497 {
10498   tree t;
10499   tree decl;
10500   if (scope == ts_global)
10501     {
10502       /* First try ordinary name lookup, ignoring hidden class name
10503          injected via friend declaration.  */
10504       decl = lookup_name_prefer_type (name, 2);
10505       /* If that fails, the name will be placed in the smallest
10506          non-class, non-function-prototype scope according to 3.3.1/5.
10507          We may already have a hidden name declared as friend in this
10508          scope.  So lookup again but not ignoring hidden names.
10509          If we find one, that name will be made visible rather than
10510          creating a new tag.  */
10511       if (!decl)
10512         decl = lookup_type_scope (name, ts_within_enclosing_non_class);
10513     }
10514   else
10515     decl = lookup_type_scope (name, scope);
10516
10517   if (decl && DECL_CLASS_TEMPLATE_P (decl))
10518     decl = DECL_TEMPLATE_RESULT (decl);
10519
10520   if (decl && TREE_CODE (decl) == TYPE_DECL)
10521     {
10522       /* Look for invalid nested type:
10523            class C {
10524              class C {};
10525            };  */
10526       if (scope == ts_current && DECL_SELF_REFERENCE_P (decl))
10527         {
10528           error ("%qD has the same name as the class in which it is "
10529                  "declared",
10530                  decl);
10531           return error_mark_node;
10532         }
10533
10534       /* Two cases we need to consider when deciding if a class
10535          template is allowed as an elaborated type specifier:
10536          1. It is a self reference to its own class.
10537          2. It comes with a template header.
10538
10539          For example:
10540
10541            template <class T> class C {
10542              class C *c1;               // DECL_SELF_REFERENCE_P is true
10543              class D;
10544            };
10545            template <class U> class C; // template_header_p is true
10546            template <class T> class C<T>::D {
10547              class C *c2;               // DECL_SELF_REFERENCE_P is true
10548            };  */
10549
10550       t = check_elaborated_type_specifier (tag_code,
10551                                            decl,
10552                                            template_header_p
10553                                            | DECL_SELF_REFERENCE_P (decl));
10554       return t;
10555     }
10556   else if (decl && TREE_CODE (decl) == TREE_LIST)
10557     {
10558       error ("reference to %qD is ambiguous", name);
10559       print_candidates (decl);
10560       return error_mark_node;
10561     }
10562   else
10563     return NULL_TREE;
10564 }
10565
10566 /* Get the struct, enum or union (TAG_CODE says which) with tag NAME.
10567    Define the tag as a forward-reference if it is not defined.
10568
10569    If a declaration is given, process it here, and report an error if
10570    multiple declarations are not identical.
10571
10572    SCOPE is TS_CURRENT when this is also a definition.  Only look in
10573    the current frame for the name (since C++ allows new names in any
10574    scope.)  It is TS_WITHIN_ENCLOSING_NON_CLASS if this is a friend
10575    declaration.  Only look beginning from the current scope outward up
10576    till the nearest non-class scope.  Otherwise it is TS_GLOBAL.
10577
10578    TEMPLATE_HEADER_P is true when this declaration is preceded by
10579    a set of template parameters.  */
10580
10581 tree
10582 xref_tag (enum tag_types tag_code, tree name,
10583           tag_scope scope, bool template_header_p)
10584 {
10585   enum tree_code code;
10586   tree t;
10587   tree context = NULL_TREE;
10588
10589   timevar_push (TV_NAME_LOOKUP);
10590
10591   gcc_assert (TREE_CODE (name) == IDENTIFIER_NODE);
10592
10593   switch (tag_code)
10594     {
10595     case record_type:
10596     case class_type:
10597       code = RECORD_TYPE;
10598       break;
10599     case union_type:
10600       code = UNION_TYPE;
10601       break;
10602     case enum_type:
10603       code = ENUMERAL_TYPE;
10604       break;
10605     default:
10606       gcc_unreachable ();
10607     }
10608
10609   /* In case of anonymous name, xref_tag is only called to
10610      make type node and push name.  Name lookup is not required.  */
10611   if (ANON_AGGRNAME_P (name))
10612     t = NULL_TREE;
10613   else
10614     t = lookup_and_check_tag  (tag_code, name,
10615                                scope, template_header_p);
10616
10617   if (t == error_mark_node)
10618     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
10619
10620   if (scope != ts_current && t && current_class_type
10621       && template_class_depth (current_class_type)
10622       && template_header_p)
10623     {
10624       /* Since SCOPE is not TS_CURRENT, we are not looking at a
10625          definition of this tag.  Since, in addition, we are currently
10626          processing a (member) template declaration of a template
10627          class, we must be very careful; consider:
10628
10629            template <class X>
10630            struct S1
10631
10632            template <class U>
10633            struct S2
10634            { template <class V>
10635            friend struct S1; };
10636
10637          Here, the S2::S1 declaration should not be confused with the
10638          outer declaration.  In particular, the inner version should
10639          have a template parameter of level 2, not level 1.  This
10640          would be particularly important if the member declaration
10641          were instead:
10642
10643            template <class V = U> friend struct S1;
10644
10645          say, when we should tsubst into `U' when instantiating
10646          S2.  On the other hand, when presented with:
10647
10648            template <class T>
10649            struct S1 {
10650              template <class U>
10651              struct S2 {};
10652              template <class U>
10653              friend struct S2;
10654            };
10655
10656          we must find the inner binding eventually.  We
10657          accomplish this by making sure that the new type we
10658          create to represent this declaration has the right
10659          TYPE_CONTEXT.  */
10660       context = TYPE_CONTEXT (t);
10661       t = NULL_TREE;
10662     }
10663
10664   if (! t)
10665     {
10666       /* If no such tag is yet defined, create a forward-reference node
10667          and record it as the "definition".
10668          When a real declaration of this type is found,
10669          the forward-reference will be altered into a real type.  */
10670       if (code == ENUMERAL_TYPE)
10671         {
10672           error ("use of enum %q#D without previous declaration", name);
10673           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
10674         }
10675       else
10676         {
10677           t = make_class_type (code);
10678           TYPE_CONTEXT (t) = context;
10679           t = pushtag (name, t, scope);
10680         }
10681     }
10682   else
10683     {
10684       if (template_header_p && MAYBE_CLASS_TYPE_P (t))
10685         {
10686           if (!redeclare_class_template (t, current_template_parms))
10687             POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
10688         }
10689       else if (!processing_template_decl
10690                && CLASS_TYPE_P (t)
10691                && CLASSTYPE_IS_TEMPLATE (t))
10692         {
10693           error ("redeclaration of %qT as a non-template", t);
10694           error ("previous declaration %q+D", t);
10695           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
10696         }
10697
10698       /* Make injected friend class visible.  */
10699       if (scope != ts_within_enclosing_non_class
10700           && hidden_name_p (TYPE_NAME (t)))
10701         {
10702           DECL_ANTICIPATED (TYPE_NAME (t)) = 0;
10703           DECL_FRIEND_P (TYPE_NAME (t)) = 0;
10704
10705           if (TYPE_TEMPLATE_INFO (t))
10706             {
10707               DECL_ANTICIPATED (TYPE_TI_TEMPLATE (t)) = 0;
10708               DECL_FRIEND_P (TYPE_TI_TEMPLATE (t)) = 0;
10709             }
10710         }
10711     }
10712
10713   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
10714 }
10715
10716 tree
10717 xref_tag_from_type (tree old, tree id, tag_scope scope)
10718 {
10719   enum tag_types tag_kind;
10720
10721   if (TREE_CODE (old) == RECORD_TYPE)
10722     tag_kind = (CLASSTYPE_DECLARED_CLASS (old) ? class_type : record_type);
10723   else
10724     tag_kind  = union_type;
10725
10726   if (id == NULL_TREE)
10727     id = TYPE_IDENTIFIER (old);
10728
10729   return xref_tag (tag_kind, id, scope, false);
10730 }
10731
10732 /* Create the binfo hierarchy for REF with (possibly NULL) base list
10733    BASE_LIST.  For each element on BASE_LIST the TREE_PURPOSE is an
10734    access_* node, and the TREE_VALUE is the type of the base-class.
10735    Non-NULL TREE_TYPE indicates virtual inheritance.  
10736  
10737    Returns true if the binfo hierarchy was successfully created,
10738    false if an error was detected. */
10739
10740 bool
10741 xref_basetypes (tree ref, tree base_list)
10742 {
10743   tree *basep;
10744   tree binfo, base_binfo;
10745   unsigned max_vbases = 0; /* Maximum direct & indirect virtual bases.  */
10746   unsigned max_bases = 0;  /* Maximum direct bases.  */
10747   int i;
10748   tree default_access;
10749   tree igo_prev; /* Track Inheritance Graph Order.  */
10750
10751   if (ref == error_mark_node)
10752     return false;
10753
10754   /* The base of a derived class is private by default, all others are
10755      public.  */
10756   default_access = (TREE_CODE (ref) == RECORD_TYPE
10757                     && CLASSTYPE_DECLARED_CLASS (ref)
10758                     ? access_private_node : access_public_node);
10759
10760   /* First, make sure that any templates in base-classes are
10761      instantiated.  This ensures that if we call ourselves recursively
10762      we do not get confused about which classes are marked and which
10763      are not.  */
10764   basep = &base_list;
10765   while (*basep)
10766     {
10767       tree basetype = TREE_VALUE (*basep);
10768
10769       if (!(processing_template_decl && uses_template_parms (basetype))
10770           && !complete_type_or_else (basetype, NULL))
10771         /* An incomplete type.  Remove it from the list.  */
10772         *basep = TREE_CHAIN (*basep);
10773       else
10774         {
10775           max_bases++;
10776           if (TREE_TYPE (*basep))
10777             max_vbases++;
10778           if (CLASS_TYPE_P (basetype))
10779             max_vbases += VEC_length (tree, CLASSTYPE_VBASECLASSES (basetype));
10780           basep = &TREE_CHAIN (*basep);
10781         }
10782     }
10783
10784   TYPE_MARKED_P (ref) = 1;
10785
10786   /* The binfo slot should be empty, unless this is an (ill-formed)
10787      redefinition.  */
10788   gcc_assert (!TYPE_BINFO (ref) || TYPE_SIZE (ref));
10789   gcc_assert (TYPE_MAIN_VARIANT (ref) == ref);
10790
10791   binfo = make_tree_binfo (max_bases);
10792
10793   TYPE_BINFO (ref) = binfo;
10794   BINFO_OFFSET (binfo) = size_zero_node;
10795   BINFO_TYPE (binfo) = ref;
10796
10797   /* Apply base-class info set up to the variants of this type.  */
10798   fixup_type_variants (ref);
10799
10800   if (max_bases)
10801     {
10802       BINFO_BASE_ACCESSES (binfo) = VEC_alloc (tree, gc, max_bases);
10803       /* An aggregate cannot have baseclasses.  */
10804       CLASSTYPE_NON_AGGREGATE (ref) = 1;
10805
10806       if (TREE_CODE (ref) == UNION_TYPE)
10807         {
10808           error ("derived union %qT invalid", ref);
10809           return false;
10810         }
10811     }
10812
10813   if (max_bases > 1)
10814     {
10815       if (TYPE_FOR_JAVA (ref))
10816         {
10817           error ("Java class %qT cannot have multiple bases", ref);
10818           return false;
10819         }
10820     }
10821
10822   if (max_vbases)
10823     {
10824       CLASSTYPE_VBASECLASSES (ref) = VEC_alloc (tree, gc, max_vbases);
10825
10826       if (TYPE_FOR_JAVA (ref))
10827         {
10828           error ("Java class %qT cannot have virtual bases", ref);
10829           return false;
10830         }
10831     }
10832
10833   for (igo_prev = binfo; base_list; base_list = TREE_CHAIN (base_list))
10834     {
10835       tree access = TREE_PURPOSE (base_list);
10836       int via_virtual = TREE_TYPE (base_list) != NULL_TREE;
10837       tree basetype = TREE_VALUE (base_list);
10838
10839       if (access == access_default_node)
10840         access = default_access;
10841
10842       if (PACK_EXPANSION_P (basetype))
10843         basetype = PACK_EXPANSION_PATTERN (basetype);
10844       if (TREE_CODE (basetype) == TYPE_DECL)
10845         basetype = TREE_TYPE (basetype);
10846       if (!MAYBE_CLASS_TYPE_P (basetype) || TREE_CODE (basetype) == UNION_TYPE)
10847         {
10848           error ("base type %qT fails to be a struct or class type",
10849                  basetype);
10850           return false;
10851         }
10852
10853       if (TYPE_FOR_JAVA (basetype) && (current_lang_depth () == 0))
10854         TYPE_FOR_JAVA (ref) = 1;
10855
10856       base_binfo = NULL_TREE;
10857       if (CLASS_TYPE_P (basetype) && !dependent_type_p (basetype))
10858         {
10859           base_binfo = TYPE_BINFO (basetype);
10860           /* The original basetype could have been a typedef'd type.  */
10861           basetype = BINFO_TYPE (base_binfo);
10862
10863           /* Inherit flags from the base.  */
10864           TYPE_HAS_NEW_OPERATOR (ref)
10865             |= TYPE_HAS_NEW_OPERATOR (basetype);
10866           TYPE_HAS_ARRAY_NEW_OPERATOR (ref)
10867             |= TYPE_HAS_ARRAY_NEW_OPERATOR (basetype);
10868           TYPE_GETS_DELETE (ref) |= TYPE_GETS_DELETE (basetype);
10869           TYPE_HAS_CONVERSION (ref) |= TYPE_HAS_CONVERSION (basetype);
10870           CLASSTYPE_DIAMOND_SHAPED_P (ref)
10871             |= CLASSTYPE_DIAMOND_SHAPED_P (basetype);
10872           CLASSTYPE_REPEATED_BASE_P (ref)
10873             |= CLASSTYPE_REPEATED_BASE_P (basetype);
10874         }
10875
10876       /* We must do this test after we've seen through a typedef
10877          type.  */
10878       if (TYPE_MARKED_P (basetype))
10879         {
10880           if (basetype == ref)
10881             error ("recursive type %qT undefined", basetype);
10882           else
10883             error ("duplicate base type %qT invalid", basetype);
10884           return false;
10885         }
10886
10887       if (PACK_EXPANSION_P (TREE_VALUE (base_list)))
10888         /* Regenerate the pack expansion for the bases. */
10889         basetype = make_pack_expansion (basetype);
10890
10891       TYPE_MARKED_P (basetype) = 1;
10892
10893       base_binfo = copy_binfo (base_binfo, basetype, ref,
10894                                &igo_prev, via_virtual);
10895       if (!BINFO_INHERITANCE_CHAIN (base_binfo))
10896         BINFO_INHERITANCE_CHAIN (base_binfo) = binfo;
10897
10898       BINFO_BASE_APPEND (binfo, base_binfo);
10899       BINFO_BASE_ACCESS_APPEND (binfo, access);
10900     }
10901
10902   if (VEC_space (tree, CLASSTYPE_VBASECLASSES (ref), 1))
10903     /* If we have space in the vbase vector, we must have shared at
10904        least one of them, and are therefore diamond shaped.  */
10905     CLASSTYPE_DIAMOND_SHAPED_P (ref) = 1;
10906
10907   /* Unmark all the types.  */
10908   for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
10909     TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
10910   TYPE_MARKED_P (ref) = 0;
10911
10912   /* Now see if we have a repeated base type.  */
10913   if (!CLASSTYPE_REPEATED_BASE_P (ref))
10914     {
10915       for (base_binfo = binfo; base_binfo;
10916            base_binfo = TREE_CHAIN (base_binfo))
10917         {
10918           if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
10919             {
10920               CLASSTYPE_REPEATED_BASE_P (ref) = 1;
10921               break;
10922             }
10923           TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 1;
10924         }
10925       for (base_binfo = binfo; base_binfo;
10926            base_binfo = TREE_CHAIN (base_binfo))
10927         if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
10928           TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
10929         else
10930           break;
10931     }
10932
10933   return true;
10934 }
10935
10936 \f
10937 /* Begin compiling the definition of an enumeration type.
10938    NAME is its name, 
10939
10940    UNDERLYING_TYPE is the type that will be used as the storage for
10941    the enumeration type. This should be NULL_TREE if no storage type
10942    was specified.
10943
10944    SCOPED_ENUM_P is true if this is a scoped enumeration type.
10945
10946    Returns the type object, as yet incomplete.
10947    Also records info about it so that build_enumerator
10948    may be used to declare the individual values as they are read.  */
10949
10950 tree
10951 start_enum (tree name, tree underlying_type, bool scoped_enum_p)
10952 {
10953   tree enumtype;
10954
10955   gcc_assert (TREE_CODE (name) == IDENTIFIER_NODE);
10956
10957   /* If this is the real definition for a previous forward reference,
10958      fill in the contents in the same object that used to be the
10959      forward reference.  */
10960
10961   enumtype = lookup_and_check_tag (enum_type, name,
10962                                    /*tag_scope=*/ts_current,
10963                                    /*template_header_p=*/false);
10964
10965   if (enumtype != NULL_TREE && TREE_CODE (enumtype) == ENUMERAL_TYPE)
10966     {
10967       error_at (input_location, "multiple definition of %q#T", enumtype);
10968       error_at (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
10969                 "previous definition here");
10970       /* Clear out TYPE_VALUES, and start again.  */
10971       TYPE_VALUES (enumtype) = NULL_TREE;
10972     }
10973   else
10974     {
10975       /* In case of error, make a dummy enum to allow parsing to
10976          continue.  */
10977       if (enumtype == error_mark_node)
10978         name = make_anon_name ();
10979
10980       enumtype = make_node (ENUMERAL_TYPE);
10981       enumtype = pushtag (name, enumtype, /*tag_scope=*/ts_current);
10982     }
10983
10984   if (enumtype == error_mark_node)
10985     return enumtype;
10986
10987   if (scoped_enum_p)
10988     {
10989       SET_SCOPED_ENUM_P (enumtype, 1);
10990       begin_scope (sk_scoped_enum, enumtype);
10991
10992       /* [C++0x dcl.enum]p5: 
10993
10994           If not explicitly specified, the underlying type of a scoped
10995           enumeration type is int.  */
10996       if (!underlying_type)
10997         underlying_type = integer_type_node;
10998     }
10999
11000   if (underlying_type)
11001     {
11002       if (CP_INTEGRAL_TYPE_P (underlying_type))
11003         {
11004           TYPE_MIN_VALUE (enumtype) = TYPE_MIN_VALUE (underlying_type);
11005           TYPE_MAX_VALUE (enumtype) = TYPE_MAX_VALUE (underlying_type);
11006           TYPE_SIZE (enumtype) = TYPE_SIZE (underlying_type);
11007           TYPE_SIZE_UNIT (enumtype) = TYPE_SIZE_UNIT (underlying_type);
11008           SET_TYPE_MODE (enumtype, TYPE_MODE (underlying_type));
11009           TYPE_PRECISION (enumtype) = TYPE_PRECISION (underlying_type);
11010           TYPE_ALIGN (enumtype) = TYPE_ALIGN (underlying_type);
11011           TYPE_USER_ALIGN (enumtype) = TYPE_USER_ALIGN (underlying_type);
11012           TYPE_UNSIGNED (enumtype) = TYPE_UNSIGNED (underlying_type);
11013           ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
11014         }
11015       else if (!dependent_type_p (underlying_type))
11016         error ("underlying type %<%T%> of %<%T%> must be an integral type", 
11017                underlying_type, enumtype);
11018     }
11019
11020   return enumtype;
11021 }
11022
11023 /* After processing and defining all the values of an enumeration type,
11024    install their decls in the enumeration type and finish it off.
11025    ENUMTYPE is the type object and VALUES a list of name-value pairs.  */
11026
11027 void
11028 finish_enum (tree enumtype)
11029 {
11030   tree values;
11031   tree decl;
11032   tree minnode;
11033   tree maxnode;
11034   tree value;
11035   tree t;
11036   bool unsignedp;
11037   bool use_short_enum;
11038   int lowprec;
11039   int highprec;
11040   int precision;
11041   unsigned int itk;
11042   tree underlying_type = NULL_TREE;
11043   bool fixed_underlying_type_p 
11044     = ENUM_UNDERLYING_TYPE (enumtype) != NULL_TREE;
11045
11046   /* We built up the VALUES in reverse order.  */
11047   TYPE_VALUES (enumtype) = nreverse (TYPE_VALUES (enumtype));
11048
11049   /* For an enum defined in a template, just set the type of the values;
11050      all further processing is postponed until the template is
11051      instantiated.  We need to set the type so that tsubst of a CONST_DECL
11052      works.  */
11053   if (processing_template_decl)
11054     {
11055       for (values = TYPE_VALUES (enumtype);
11056            values;
11057            values = TREE_CHAIN (values))
11058         TREE_TYPE (TREE_VALUE (values)) = enumtype;
11059       if (at_function_scope_p ())
11060         add_stmt (build_min (TAG_DEFN, enumtype));
11061       if (SCOPED_ENUM_P (enumtype))
11062         finish_scope ();
11063       return;
11064     }
11065
11066   /* Determine the minimum and maximum values of the enumerators.  */
11067   if (TYPE_VALUES (enumtype))
11068     {
11069       minnode = maxnode = NULL_TREE;
11070
11071       for (values = TYPE_VALUES (enumtype);
11072            values;
11073            values = TREE_CHAIN (values))
11074         {
11075           decl = TREE_VALUE (values);
11076
11077           /* [dcl.enum]: Following the closing brace of an enum-specifier,
11078              each enumerator has the type of its enumeration.  Prior to the
11079              closing brace, the type of each enumerator is the type of its
11080              initializing value.  */
11081           TREE_TYPE (decl) = enumtype;
11082
11083           /* Update the minimum and maximum values, if appropriate.  */
11084           value = DECL_INITIAL (decl);
11085           if (value == error_mark_node)
11086             value = integer_zero_node;
11087           /* Figure out what the minimum and maximum values of the
11088              enumerators are.  */
11089           if (!minnode)
11090             minnode = maxnode = value;
11091           else if (tree_int_cst_lt (maxnode, value))
11092             maxnode = value;
11093           else if (tree_int_cst_lt (value, minnode))
11094             minnode = value;
11095         }
11096     }
11097   else
11098     /* [dcl.enum]
11099        
11100        If the enumerator-list is empty, the underlying type is as if
11101        the enumeration had a single enumerator with value 0.  */
11102     minnode = maxnode = integer_zero_node;
11103
11104   /* Compute the number of bits require to represent all values of the
11105      enumeration.  We must do this before the type of MINNODE and
11106      MAXNODE are transformed, since tree_int_cst_min_precision relies
11107      on the TREE_TYPE of the value it is passed.  */
11108   unsignedp = tree_int_cst_sgn (minnode) >= 0;
11109   lowprec = tree_int_cst_min_precision (minnode, unsignedp);
11110   highprec = tree_int_cst_min_precision (maxnode, unsignedp);
11111   precision = MAX (lowprec, highprec);
11112
11113   if (!fixed_underlying_type_p)
11114     {
11115       /* Determine the underlying type of the enumeration.
11116
11117          [dcl.enum]
11118
11119          The underlying type of an enumeration is an integral type that
11120          can represent all the enumerator values defined in the
11121          enumeration.  It is implementation-defined which integral type is
11122          used as the underlying type for an enumeration except that the
11123          underlying type shall not be larger than int unless the value of
11124          an enumerator cannot fit in an int or unsigned int.
11125
11126          We use "int" or an "unsigned int" as the underlying type, even if
11127          a smaller integral type would work, unless the user has
11128          explicitly requested that we use the smallest possible type.  The
11129          user can request that for all enumerations with a command line
11130          flag, or for just one enumeration with an attribute.  */
11131
11132       use_short_enum = flag_short_enums
11133         || lookup_attribute ("packed", TYPE_ATTRIBUTES (enumtype));
11134
11135       for (itk = (use_short_enum ? itk_char : itk_int);
11136            itk != itk_none;
11137            itk++)
11138         {
11139           underlying_type = integer_types[itk];
11140           if (TYPE_PRECISION (underlying_type) >= precision
11141               && TYPE_UNSIGNED (underlying_type) == unsignedp)
11142             break;
11143         }
11144       if (itk == itk_none)
11145         {
11146           /* DR 377
11147
11148              IF no integral type can represent all the enumerator values, the
11149              enumeration is ill-formed.  */
11150           error ("no integral type can represent all of the enumerator values "
11151                  "for %qT", enumtype);
11152           precision = TYPE_PRECISION (long_long_integer_type_node);
11153           underlying_type = integer_types[itk_unsigned_long_long];
11154         }
11155
11156       /* [dcl.enum]
11157
11158          The value of sizeof() applied to an enumeration type, an object
11159          of an enumeration type, or an enumerator, is the value of sizeof()
11160          applied to the underlying type.  */
11161       TYPE_SIZE (enumtype) = TYPE_SIZE (underlying_type);
11162       TYPE_SIZE_UNIT (enumtype) = TYPE_SIZE_UNIT (underlying_type);
11163       SET_TYPE_MODE (enumtype, TYPE_MODE (underlying_type));
11164       TYPE_ALIGN (enumtype) = TYPE_ALIGN (underlying_type);
11165       TYPE_USER_ALIGN (enumtype) = TYPE_USER_ALIGN (underlying_type);
11166       TYPE_UNSIGNED (enumtype) = TYPE_UNSIGNED (underlying_type);
11167
11168       /* Set the underlying type of the enumeration type to the
11169          computed enumeration type, restricted to the enumerator
11170          values. */
11171       ENUM_UNDERLYING_TYPE (enumtype)
11172         = build_distinct_type_copy (underlying_type);
11173       set_min_and_max_values_for_integral_type 
11174         (ENUM_UNDERLYING_TYPE (enumtype), precision, unsignedp);
11175     }
11176   else
11177     underlying_type = ENUM_UNDERLYING_TYPE (enumtype);
11178
11179   /* Compute the minimum and maximum values for the type.
11180
11181      [dcl.enum]
11182
11183      For an enumeration where emin is the smallest enumerator and emax
11184      is the largest, the values of the enumeration are the values of the
11185      underlying type in the range bmin to bmax, where bmin and bmax are,
11186      respectively, the smallest and largest values of the smallest bit-
11187      field that can store emin and emax.  */
11188   
11189   /* The middle-end currently assumes that types with TYPE_PRECISION
11190      narrower than their underlying type are suitably zero or sign
11191      extended to fill their mode.  g++ doesn't make these guarantees.
11192      Until the middle-end can represent such paradoxical types, we
11193      set the TYPE_PRECISION to the width of the underlying type.  */
11194   TYPE_PRECISION (enumtype) = TYPE_PRECISION (underlying_type);
11195   
11196   set_min_and_max_values_for_integral_type (enumtype, precision, unsignedp);
11197   
11198   /* Convert each of the enumerators to the type of the underlying
11199      type of the enumeration.  */
11200   for (values = TYPE_VALUES (enumtype); values; values = TREE_CHAIN (values))
11201     {
11202       location_t saved_location;
11203
11204       decl = TREE_VALUE (values);
11205       saved_location = input_location;
11206       input_location = DECL_SOURCE_LOCATION (decl);
11207       if (fixed_underlying_type_p)
11208         /* If the enumeration type has a fixed underlying type, we
11209            already checked all of the enumerator values.  */
11210         value = DECL_INITIAL (decl);
11211       else
11212         value = perform_implicit_conversion (underlying_type,
11213                                              DECL_INITIAL (decl),
11214                                              tf_warning_or_error);
11215       input_location = saved_location;
11216
11217       /* Do not clobber shared ints.  */
11218       value = copy_node (value);
11219
11220       TREE_TYPE (value) = enumtype;
11221       DECL_INITIAL (decl) = value;
11222     }
11223
11224   /* Fix up all variant types of this enum type.  */
11225   for (t = TYPE_MAIN_VARIANT (enumtype); t; t = TYPE_NEXT_VARIANT (t))
11226     {
11227       TYPE_VALUES (t) = TYPE_VALUES (enumtype);
11228       TYPE_MIN_VALUE (t) = TYPE_MIN_VALUE (enumtype);
11229       TYPE_MAX_VALUE (t) = TYPE_MAX_VALUE (enumtype);
11230       TYPE_SIZE (t) = TYPE_SIZE (enumtype);
11231       TYPE_SIZE_UNIT (t) = TYPE_SIZE_UNIT (enumtype);
11232       SET_TYPE_MODE (t, TYPE_MODE (enumtype));
11233       TYPE_PRECISION (t) = TYPE_PRECISION (enumtype);
11234       TYPE_ALIGN (t) = TYPE_ALIGN (enumtype);
11235       TYPE_USER_ALIGN (t) = TYPE_USER_ALIGN (enumtype);
11236       TYPE_UNSIGNED (t) = TYPE_UNSIGNED (enumtype);
11237       ENUM_UNDERLYING_TYPE (t) = ENUM_UNDERLYING_TYPE (enumtype);
11238     }
11239
11240   /* Finish up the scope of a scoped enumeration.  */
11241   if (SCOPED_ENUM_P (enumtype))
11242     finish_scope ();
11243
11244   /* Finish debugging output for this type.  */
11245   rest_of_type_compilation (enumtype, namespace_bindings_p ());
11246 }
11247
11248 /* Build and install a CONST_DECL for an enumeration constant of the
11249    enumeration type ENUMTYPE whose NAME and VALUE (if any) are provided.
11250    Assignment of sequential values by default is handled here.  */
11251
11252 void
11253 build_enumerator (tree name, tree value, tree enumtype)
11254 {
11255   tree decl;
11256   tree context;
11257   tree type;
11258
11259   /* If the VALUE was erroneous, pretend it wasn't there; that will
11260      result in the enum being assigned the next value in sequence.  */
11261   if (value == error_mark_node)
11262     value = NULL_TREE;
11263
11264   /* Remove no-op casts from the value.  */
11265   if (value)
11266     STRIP_TYPE_NOPS (value);
11267
11268   if (! processing_template_decl)
11269     {
11270       /* Validate and default VALUE.  */
11271       if (value != NULL_TREE)
11272         {
11273           value = integral_constant_value (value);
11274
11275           if (TREE_CODE (value) == INTEGER_CST)
11276             {
11277               value = perform_integral_promotions (value);
11278               constant_expression_warning (value);
11279             }
11280           else
11281             {
11282               error ("enumerator value for %qD is not an integer constant", name);
11283               value = NULL_TREE;
11284             }
11285         }
11286
11287       /* Default based on previous value.  */
11288       if (value == NULL_TREE)
11289         {
11290           if (TYPE_VALUES (enumtype))
11291             {
11292               HOST_WIDE_INT hi;
11293               unsigned HOST_WIDE_INT lo;
11294               tree prev_value;
11295               bool overflowed;
11296
11297               /* The next value is the previous value plus one.
11298                  add_double doesn't know the type of the target expression,
11299                  so we must check with int_fits_type_p as well.  */
11300               prev_value = DECL_INITIAL (TREE_VALUE (TYPE_VALUES (enumtype)));
11301               if (error_operand_p (prev_value))
11302                 value = error_mark_node;
11303               else
11304                 {
11305                   overflowed = add_double (TREE_INT_CST_LOW (prev_value),
11306                                            TREE_INT_CST_HIGH (prev_value),
11307                                            1, 0, &lo, &hi);
11308                   value = build_int_cst_wide (TREE_TYPE (prev_value), lo, hi);
11309                   overflowed
11310                     |= !int_fits_type_p (value, TREE_TYPE (prev_value));
11311
11312                   if (overflowed)
11313                     {
11314                       error ("overflow in enumeration values at %qD", name);
11315                       value = error_mark_node;
11316                     }
11317                 }
11318             }
11319           else
11320             value = integer_zero_node;
11321         }
11322
11323       /* Remove no-op casts from the value.  */
11324       STRIP_TYPE_NOPS (value);
11325
11326       /* If the underlying type of the enum is fixed, check whether
11327          the enumerator values fits in the underlying type.  If it
11328          does not fit, the program is ill-formed [C++0x dcl.enum].  */
11329       if (ENUM_UNDERLYING_TYPE (enumtype)
11330           && value
11331           && TREE_CODE (value) == INTEGER_CST
11332           && !int_fits_type_p (value, ENUM_UNDERLYING_TYPE (enumtype)))
11333         {
11334           error ("enumerator value %E is too large for underlying type %<%T%>",
11335                  value, ENUM_UNDERLYING_TYPE (enumtype));
11336
11337           /* Silently convert the value so that we can continue.  */
11338           value = perform_implicit_conversion (ENUM_UNDERLYING_TYPE (enumtype),
11339                                                value, tf_none);
11340         }
11341     }
11342
11343   /* C++ associates enums with global, function, or class declarations.  */
11344   context = current_scope ();
11345
11346   /* Build the actual enumeration constant.  Note that the enumeration
11347      constants have the underlying type of the enum (if it is fixed)
11348      or the type of their initializer (if the underlying type of the
11349      enum is not fixed):
11350
11351       [ C++0x dcl.enum ]
11352
11353         If the underlying type is fixed, the type of each enumerator
11354         prior to the closing brace is the underlying type; if the
11355         initializing value of an enumerator cannot be represented by
11356         the underlying type, the program is ill-formed. If the
11357         underlying type is not fixed, the type of each enumerator is
11358         the type of its initializing value.
11359
11360     If the underlying type is not fixed, it will be computed by
11361     finish_enum and we will reset the type of this enumerator.  Of
11362     course, if we're processing a template, there may be no value.  */
11363   type = value ? TREE_TYPE (value) : NULL_TREE;
11364
11365   if (context && context == current_class_type)
11366     /* This enum declaration is local to the class.  We need the full
11367        lang_decl so that we can record DECL_CLASS_CONTEXT, for example.  */
11368     decl = build_lang_decl (CONST_DECL, name, type);
11369   else
11370     /* It's a global enum, or it's local to a function.  (Note local to
11371       a function could mean local to a class method.  */
11372     decl = build_decl (input_location, CONST_DECL, name, type);
11373
11374   DECL_CONTEXT (decl) = FROB_CONTEXT (context);
11375   TREE_CONSTANT (decl) = 1;
11376   TREE_READONLY (decl) = 1;
11377   DECL_INITIAL (decl) = value;
11378
11379   if (context && context == current_class_type && !SCOPED_ENUM_P (enumtype))
11380     /* In something like `struct S { enum E { i = 7 }; };' we put `i'
11381        on the TYPE_FIELDS list for `S'.  (That's so that you can say
11382        things like `S::i' later.)  */
11383     finish_member_declaration (decl);
11384   else
11385     pushdecl (decl);
11386
11387   /* Add this enumeration constant to the list for this type.  */
11388   TYPE_VALUES (enumtype) = tree_cons (name, decl, TYPE_VALUES (enumtype));
11389 }
11390
11391 /* Look for an enumerator with the given NAME within the enumeration
11392    type ENUMTYPE.  This routine is used primarily for qualified name
11393    lookup into an enumerator in C++0x, e.g.,
11394
11395      enum class Color { Red, Green, Blue };
11396
11397      Color color = Color::Red;
11398
11399    Returns the value corresponding to the enumerator, or
11400    NULL_TREE if no such enumerator was found.  */
11401 tree
11402 lookup_enumerator (tree enumtype, tree name)
11403 {
11404   tree e;
11405   gcc_assert (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE);
11406
11407   e = purpose_member (name, TYPE_VALUES (enumtype));
11408   return e? TREE_VALUE (e) : NULL_TREE;
11409 }
11410
11411 \f
11412 /* We're defining DECL.  Make sure that it's type is OK.  */
11413
11414 static void
11415 check_function_type (tree decl, tree current_function_parms)
11416 {
11417   tree fntype = TREE_TYPE (decl);
11418   tree return_type = complete_type (TREE_TYPE (fntype));
11419
11420   /* In a function definition, arg types must be complete.  */
11421   require_complete_types_for_parms (current_function_parms);
11422
11423   if (dependent_type_p (return_type))
11424     return;
11425   if (!COMPLETE_OR_VOID_TYPE_P (return_type)
11426       || (TYPE_FOR_JAVA (return_type) && MAYBE_CLASS_TYPE_P (return_type)))
11427     {
11428       tree args = TYPE_ARG_TYPES (fntype);
11429
11430       if (!COMPLETE_OR_VOID_TYPE_P (return_type))
11431         error ("return type %q#T is incomplete", return_type);
11432       else
11433         error ("return type has Java class type %q#T", return_type);
11434
11435       /* Make it return void instead.  */
11436       if (TREE_CODE (fntype) == METHOD_TYPE)
11437         fntype = build_method_type_directly (TREE_TYPE (TREE_VALUE (args)),
11438                                              void_type_node,
11439                                              TREE_CHAIN (args));
11440       else
11441         fntype = build_function_type (void_type_node, args);
11442       TREE_TYPE (decl)
11443         = build_exception_variant (fntype,
11444                                    TYPE_RAISES_EXCEPTIONS (TREE_TYPE (decl)));
11445     }
11446   else
11447     abstract_virtuals_error (decl, TREE_TYPE (fntype));
11448 }
11449
11450 /* Create the FUNCTION_DECL for a function definition.
11451    DECLSPECS and DECLARATOR are the parts of the declaration;
11452    they describe the function's name and the type it returns,
11453    but twisted together in a fashion that parallels the syntax of C.
11454
11455    FLAGS is a bitwise or of SF_PRE_PARSED (indicating that the
11456    DECLARATOR is really the DECL for the function we are about to
11457    process and that DECLSPECS should be ignored), SF_INCLASS_INLINE
11458    indicating that the function is an inline defined in-class.
11459
11460    This function creates a binding context for the function body
11461    as well as setting up the FUNCTION_DECL in current_function_decl.
11462
11463    For C++, we must first check whether that datum makes any sense.
11464    For example, "class A local_a(1,2);" means that variable local_a
11465    is an aggregate of type A, which should have a constructor
11466    applied to it with the argument list [1, 2].
11467
11468    On entry, DECL_INITIAL (decl1) should be NULL_TREE or error_mark_node,
11469    or may be a BLOCK if the function has been defined previously
11470    in this translation unit.  On exit, DECL_INITIAL (decl1) will be
11471    error_mark_node if the function has never been defined, or
11472    a BLOCK if the function has been defined somewhere.  */
11473
11474 void
11475 start_preparsed_function (tree decl1, tree attrs, int flags)
11476 {
11477   tree ctype = NULL_TREE;
11478   tree fntype;
11479   tree restype;
11480   int doing_friend = 0;
11481   struct cp_binding_level *bl;
11482   tree current_function_parms;
11483   struct c_fileinfo *finfo
11484     = get_fileinfo (LOCATION_FILE (DECL_SOURCE_LOCATION (decl1)));
11485   bool honor_interface;
11486
11487   /* Sanity check.  */
11488   gcc_assert (TREE_CODE (TREE_VALUE (void_list_node)) == VOID_TYPE);
11489   gcc_assert (TREE_CHAIN (void_list_node) == NULL_TREE);
11490
11491   fntype = TREE_TYPE (decl1);
11492   if (TREE_CODE (fntype) == METHOD_TYPE)
11493     ctype = TYPE_METHOD_BASETYPE (fntype);
11494
11495   /* ISO C++ 11.4/5.  A friend function defined in a class is in
11496      the (lexical) scope of the class in which it is defined.  */
11497   if (!ctype && DECL_FRIEND_P (decl1))
11498     {
11499       ctype = DECL_FRIEND_CONTEXT (decl1);
11500
11501       /* CTYPE could be null here if we're dealing with a template;
11502          for example, `inline friend float foo()' inside a template
11503          will have no CTYPE set.  */
11504       if (ctype && TREE_CODE (ctype) != RECORD_TYPE)
11505         ctype = NULL_TREE;
11506       else
11507         doing_friend = 1;
11508     }
11509
11510   if (DECL_DECLARED_INLINE_P (decl1)
11511       && lookup_attribute ("noinline", attrs))
11512     warning (0, "inline function %q+D given attribute noinline", decl1);
11513
11514   /* Handle gnu_inline attribute.  */
11515   if (GNU_INLINE_P (decl1))
11516     {
11517       DECL_EXTERNAL (decl1) = 1;
11518       DECL_NOT_REALLY_EXTERN (decl1) = 0;
11519       DECL_INTERFACE_KNOWN (decl1) = 1;
11520       DECL_DISREGARD_INLINE_LIMITS (decl1) = 1;
11521     }
11522
11523   if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl1))
11524     /* This is a constructor, we must ensure that any default args
11525        introduced by this definition are propagated to the clones
11526        now. The clones are used directly in overload resolution.  */
11527     adjust_clone_args (decl1);
11528
11529   /* Sometimes we don't notice that a function is a static member, and
11530      build a METHOD_TYPE for it.  Fix that up now.  */
11531   if (ctype != NULL_TREE && DECL_STATIC_FUNCTION_P (decl1)
11532       && TREE_CODE (TREE_TYPE (decl1)) == METHOD_TYPE)
11533     {
11534       revert_static_member_fn (decl1);
11535       ctype = NULL_TREE;
11536     }
11537
11538   /* Set up current_class_type, and enter the scope of the class, if
11539      appropriate.  */
11540   if (ctype)
11541     push_nested_class (ctype);
11542   else if (DECL_STATIC_FUNCTION_P (decl1))
11543     push_nested_class (DECL_CONTEXT (decl1));
11544
11545   /* Now that we have entered the scope of the class, we must restore
11546      the bindings for any template parameters surrounding DECL1, if it
11547      is an inline member template.  (Order is important; consider the
11548      case where a template parameter has the same name as a field of
11549      the class.)  It is not until after this point that
11550      PROCESSING_TEMPLATE_DECL is guaranteed to be set up correctly.  */
11551   if (flags & SF_INCLASS_INLINE)
11552     maybe_begin_member_template_processing (decl1);
11553
11554   /* Effective C++ rule 15.  */
11555   if (warn_ecpp
11556       && DECL_OVERLOADED_OPERATOR_P (decl1) == NOP_EXPR
11557       && TREE_CODE (TREE_TYPE (fntype)) == VOID_TYPE)
11558     warning (OPT_Weffc__, "%<operator=%> should return a reference to %<*this%>");
11559
11560   /* Make the init_value nonzero so pushdecl knows this is not tentative.
11561      error_mark_node is replaced below (in poplevel) with the BLOCK.  */
11562   if (!DECL_INITIAL (decl1))
11563     DECL_INITIAL (decl1) = error_mark_node;
11564
11565   /* This function exists in static storage.
11566      (This does not mean `static' in the C sense!)  */
11567   TREE_STATIC (decl1) = 1;
11568
11569   /* We must call push_template_decl after current_class_type is set
11570      up.  (If we are processing inline definitions after exiting a
11571      class scope, current_class_type will be NULL_TREE until set above
11572      by push_nested_class.)  */
11573   if (processing_template_decl)
11574     {
11575       /* FIXME: Handle error_mark_node more gracefully.  */
11576       tree newdecl1 = push_template_decl (decl1);
11577       if (newdecl1 != error_mark_node)
11578         decl1 = newdecl1;
11579     }
11580
11581   /* We are now in the scope of the function being defined.  */
11582   current_function_decl = decl1;
11583
11584   /* Save the parm names or decls from this function's declarator
11585      where store_parm_decls will find them.  */
11586   current_function_parms = DECL_ARGUMENTS (decl1);
11587
11588   /* Make sure the parameter and return types are reasonable.  When
11589      you declare a function, these types can be incomplete, but they
11590      must be complete when you define the function.  */
11591   check_function_type (decl1, current_function_parms);
11592
11593   /* Build the return declaration for the function.  */
11594   restype = TREE_TYPE (fntype);
11595   if (DECL_RESULT (decl1) == NULL_TREE)
11596     {
11597       tree resdecl;
11598
11599       resdecl = build_decl (input_location, RESULT_DECL, 0, restype);
11600       DECL_ARTIFICIAL (resdecl) = 1;
11601       DECL_IGNORED_P (resdecl) = 1;
11602       DECL_RESULT (decl1) = resdecl;
11603
11604       cp_apply_type_quals_to_decl (cp_type_quals (restype), resdecl);
11605     }
11606
11607   /* Let the user know we're compiling this function.  */
11608   announce_function (decl1);
11609
11610   /* Record the decl so that the function name is defined.
11611      If we already have a decl for this name, and it is a FUNCTION_DECL,
11612      use the old decl.  */
11613   if (!processing_template_decl && !(flags & SF_PRE_PARSED))
11614     {
11615       /* A specialization is not used to guide overload resolution.  */
11616       if (!DECL_FUNCTION_MEMBER_P (decl1)
11617           && !(DECL_USE_TEMPLATE (decl1) &&
11618                PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl1))))
11619         {
11620           tree olddecl = pushdecl (decl1);
11621
11622           if (olddecl == error_mark_node)
11623             /* If something went wrong when registering the declaration,
11624                use DECL1; we have to have a FUNCTION_DECL to use when
11625                parsing the body of the function.  */
11626             ;
11627           else
11628             {
11629               /* Otherwise, OLDDECL is either a previous declaration
11630                  of the same function or DECL1 itself.  */
11631
11632               if (warn_missing_declarations
11633                   && olddecl == decl1
11634                   && !DECL_MAIN_P (decl1)
11635                   && TREE_PUBLIC (decl1)
11636                   && !DECL_DECLARED_INLINE_P (decl1))
11637                 {
11638                   tree context;
11639
11640                   /* Check whether DECL1 is in an anonymous
11641                      namespace.  */
11642                   for (context = DECL_CONTEXT (decl1);
11643                        context;
11644                        context = DECL_CONTEXT (context))
11645                     {
11646                       if (TREE_CODE (context) == NAMESPACE_DECL
11647                           && DECL_NAME (context) == NULL_TREE)
11648                         break;
11649                     }
11650
11651                   if (context == NULL)
11652                     warning (OPT_Wmissing_declarations,
11653                              "no previous declaration for %q+D", decl1);
11654                 }
11655
11656               decl1 = olddecl;
11657             }
11658         }
11659       else
11660         {
11661           /* We need to set the DECL_CONTEXT.  */
11662           if (!DECL_CONTEXT (decl1) && DECL_TEMPLATE_INFO (decl1))
11663             DECL_CONTEXT (decl1) = DECL_CONTEXT (DECL_TI_TEMPLATE (decl1));
11664         }
11665       fntype = TREE_TYPE (decl1);
11666
11667       /* If #pragma weak applies, mark the decl appropriately now.
11668          The pragma only applies to global functions.  Because
11669          determining whether or not the #pragma applies involves
11670          computing the mangled name for the declaration, we cannot
11671          apply the pragma until after we have merged this declaration
11672          with any previous declarations; if the original declaration
11673          has a linkage specification, that specification applies to
11674          the definition as well, and may affect the mangled name.  */
11675       if (!DECL_CONTEXT (decl1))
11676         maybe_apply_pragma_weak (decl1);
11677     }
11678
11679   /* Reset this in case the call to pushdecl changed it.  */
11680   current_function_decl = decl1;
11681
11682   gcc_assert (DECL_INITIAL (decl1));
11683
11684   /* This function may already have been parsed, in which case just
11685      return; our caller will skip over the body without parsing.  */
11686   if (DECL_INITIAL (decl1) != error_mark_node)
11687     return;
11688
11689   /* Initialize RTL machinery.  We cannot do this until
11690      CURRENT_FUNCTION_DECL and DECL_RESULT are set up.  We do this
11691      even when processing a template; this is how we get
11692      CFUN set up, and our per-function variables initialized.
11693      FIXME factor out the non-RTL stuff.  */
11694   bl = current_binding_level;
11695   allocate_struct_function (decl1, processing_template_decl);
11696
11697   /* Initialize the language data structures.  Whenever we start
11698      a new function, we destroy temporaries in the usual way.  */
11699   cfun->language = GGC_CNEW (struct language_function);
11700   current_stmt_tree ()->stmts_are_full_exprs_p = 1;
11701   current_binding_level = bl;
11702
11703   /* Even though we're inside a function body, we still don't want to
11704      call expand_expr to calculate the size of a variable-sized array.
11705      We haven't necessarily assigned RTL to all variables yet, so it's
11706      not safe to try to expand expressions involving them.  */
11707   cfun->dont_save_pending_sizes_p = 1;
11708
11709   /* Start the statement-tree, start the tree now.  */
11710   DECL_SAVED_TREE (decl1) = push_stmt_list ();
11711
11712   /* If we are (erroneously) defining a function that we have already
11713      defined before, wipe out what we knew before.  */
11714   if (!DECL_PENDING_INLINE_P (decl1))
11715     DECL_SAVED_FUNCTION_DATA (decl1) = NULL;
11716
11717   if (ctype && !doing_friend && !DECL_STATIC_FUNCTION_P (decl1))
11718     {
11719       /* We know that this was set up by `grokclassfn'.  We do not
11720          wait until `store_parm_decls', since evil parse errors may
11721          never get us to that point.  Here we keep the consistency
11722          between `current_class_type' and `current_class_ptr'.  */
11723       tree t = DECL_ARGUMENTS (decl1);
11724
11725       gcc_assert (t != NULL_TREE && TREE_CODE (t) == PARM_DECL);
11726       gcc_assert (TREE_CODE (TREE_TYPE (t)) == POINTER_TYPE);
11727
11728       cp_function_chain->x_current_class_ref
11729         = cp_build_indirect_ref (t, NULL, tf_warning_or_error);
11730       cp_function_chain->x_current_class_ptr = t;
11731
11732       /* Constructors and destructors need to know whether they're "in
11733          charge" of initializing virtual base classes.  */
11734       t = TREE_CHAIN (t);
11735       if (DECL_HAS_IN_CHARGE_PARM_P (decl1))
11736         {
11737           current_in_charge_parm = t;
11738           t = TREE_CHAIN (t);
11739         }
11740       if (DECL_HAS_VTT_PARM_P (decl1))
11741         {
11742           gcc_assert (DECL_NAME (t) == vtt_parm_identifier);
11743           current_vtt_parm = t;
11744         }
11745     }
11746
11747   honor_interface = (!DECL_TEMPLATE_INSTANTIATION (decl1)
11748                      /* Implicitly-defined methods (like the
11749                         destructor for a class in which no destructor
11750                         is explicitly declared) must not be defined
11751                         until their definition is needed.  So, we
11752                         ignore interface specifications for
11753                         compiler-generated functions.  */
11754                      && !DECL_ARTIFICIAL (decl1));
11755
11756   if (DECL_INTERFACE_KNOWN (decl1))
11757     {
11758       tree ctx = decl_function_context (decl1);
11759
11760       if (DECL_NOT_REALLY_EXTERN (decl1))
11761         DECL_EXTERNAL (decl1) = 0;
11762
11763       if (ctx != NULL_TREE && DECL_DECLARED_INLINE_P (ctx)
11764           && TREE_PUBLIC (ctx))
11765         /* This is a function in a local class in an extern inline
11766            function.  */
11767         comdat_linkage (decl1);
11768     }
11769   /* If this function belongs to an interface, it is public.
11770      If it belongs to someone else's interface, it is also external.
11771      This only affects inlines and template instantiations.  */
11772   else if (!finfo->interface_unknown && honor_interface)
11773     {
11774       if (DECL_DECLARED_INLINE_P (decl1)
11775           || DECL_TEMPLATE_INSTANTIATION (decl1)
11776           || processing_template_decl)
11777         {
11778           DECL_EXTERNAL (decl1)
11779             = (finfo->interface_only
11780                || (DECL_DECLARED_INLINE_P (decl1)
11781                    && ! flag_implement_inlines
11782                    && !DECL_VINDEX (decl1)));
11783
11784           /* For WIN32 we also want to put these in linkonce sections.  */
11785           maybe_make_one_only (decl1);
11786         }
11787       else
11788         DECL_EXTERNAL (decl1) = 0;
11789       DECL_INTERFACE_KNOWN (decl1) = 1;
11790       /* If this function is in an interface implemented in this file,
11791          make sure that the back end knows to emit this function
11792          here.  */
11793       if (!DECL_EXTERNAL (decl1))
11794         mark_needed (decl1);
11795     }
11796   else if (finfo->interface_unknown && finfo->interface_only
11797            && honor_interface)
11798     {
11799       /* If MULTIPLE_SYMBOL_SPACES is defined and we saw a #pragma
11800          interface, we will have both finfo->interface_unknown and
11801          finfo->interface_only set.  In that case, we don't want to
11802          use the normal heuristics because someone will supply a
11803          #pragma implementation elsewhere, and deducing it here would
11804          produce a conflict.  */
11805       comdat_linkage (decl1);
11806       DECL_EXTERNAL (decl1) = 0;
11807       DECL_INTERFACE_KNOWN (decl1) = 1;
11808       DECL_DEFER_OUTPUT (decl1) = 1;
11809     }
11810   else
11811     {
11812       /* This is a definition, not a reference.
11813          So clear DECL_EXTERNAL, unless this is a GNU extern inline.  */
11814       if (!GNU_INLINE_P (decl1))
11815         DECL_EXTERNAL (decl1) = 0;
11816
11817       if ((DECL_DECLARED_INLINE_P (decl1)
11818            || DECL_TEMPLATE_INSTANTIATION (decl1))
11819           && ! DECL_INTERFACE_KNOWN (decl1)
11820           /* Don't try to defer nested functions for now.  */
11821           && ! decl_function_context (decl1))
11822         DECL_DEFER_OUTPUT (decl1) = 1;
11823       else
11824         DECL_INTERFACE_KNOWN (decl1) = 1;
11825     }
11826
11827   /* Determine the ELF visibility attribute for the function.  We must not
11828      do this before calling "pushdecl", as we must allow "duplicate_decls"
11829      to merge any attributes appropriately.  We also need to wait until
11830      linkage is set.  */
11831   if (!DECL_CLONED_FUNCTION_P (decl1))
11832     determine_visibility (decl1);
11833
11834   begin_scope (sk_function_parms, decl1);
11835
11836   ++function_depth;
11837
11838   if (DECL_DESTRUCTOR_P (decl1)
11839       || (DECL_CONSTRUCTOR_P (decl1)
11840           && targetm.cxx.cdtor_returns_this ()))
11841     {
11842       cdtor_label = build_decl (input_location, 
11843                                 LABEL_DECL, NULL_TREE, NULL_TREE);
11844       DECL_CONTEXT (cdtor_label) = current_function_decl;
11845     }
11846
11847   start_fname_decls ();
11848
11849   store_parm_decls (current_function_parms);
11850 }
11851
11852
11853 /* Like start_preparsed_function, except that instead of a
11854    FUNCTION_DECL, this function takes DECLSPECS and DECLARATOR.
11855
11856    Returns 1 on success.  If the DECLARATOR is not suitable for a function
11857    (it defines a datum instead), we return 0, which tells
11858    yyparse to report a parse error.  */
11859
11860 int
11861 start_function (cp_decl_specifier_seq *declspecs,
11862                 const cp_declarator *declarator,
11863                 tree attrs)
11864 {
11865   tree decl1;
11866
11867   decl1 = grokdeclarator (declarator, declspecs, FUNCDEF, 1, &attrs);
11868   if (decl1 == error_mark_node)
11869     return 0;
11870   /* If the declarator is not suitable for a function definition,
11871      cause a syntax error.  */
11872   if (decl1 == NULL_TREE || TREE_CODE (decl1) != FUNCTION_DECL)
11873     {
11874       error ("invalid function declaration");
11875       return 0;
11876     }
11877
11878   if (DECL_MAIN_P (decl1))
11879     /* main must return int.  grokfndecl should have corrected it
11880        (and issued a diagnostic) if the user got it wrong.  */
11881     gcc_assert (same_type_p (TREE_TYPE (TREE_TYPE (decl1)),
11882                              integer_type_node));
11883
11884   start_preparsed_function (decl1, attrs, /*flags=*/SF_DEFAULT);
11885
11886   return 1;
11887 }
11888 \f
11889 /* Returns true iff an EH_SPEC_BLOCK should be created in the body of
11890    FN.  */
11891
11892 static bool
11893 use_eh_spec_block (tree fn)
11894 {
11895   return (flag_exceptions && flag_enforce_eh_specs
11896           && !processing_template_decl
11897           && TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn))
11898           /* We insert the EH_SPEC_BLOCK only in the original
11899              function; then, it is copied automatically to the
11900              clones.  */
11901           && !DECL_CLONED_FUNCTION_P (fn)
11902           /* Implicitly-generated constructors and destructors have
11903              exception specifications.  However, those specifications
11904              are the union of the possible exceptions specified by the
11905              constructors/destructors for bases and members, so no
11906              unallowed exception will ever reach this function.  By
11907              not creating the EH_SPEC_BLOCK we save a little memory,
11908              and we avoid spurious warnings about unreachable
11909              code.  */
11910           && !DECL_ARTIFICIAL (fn));
11911 }
11912
11913 /* Store the parameter declarations into the current function declaration.
11914    This is called after parsing the parameter declarations, before
11915    digesting the body of the function.
11916
11917    Also install to binding contour return value identifier, if any.  */
11918
11919 static void
11920 store_parm_decls (tree current_function_parms)
11921 {
11922   tree fndecl = current_function_decl;
11923   tree parm;
11924
11925   /* This is a chain of any other decls that came in among the parm
11926      declarations.  If a parm is declared with  enum {foo, bar} x;
11927      then CONST_DECLs for foo and bar are put here.  */
11928   tree nonparms = NULL_TREE;
11929
11930   if (current_function_parms)
11931     {
11932       /* This case is when the function was defined with an ANSI prototype.
11933          The parms already have decls, so we need not do anything here
11934          except record them as in effect
11935          and complain if any redundant old-style parm decls were written.  */
11936
11937       tree specparms = current_function_parms;
11938       tree next;
11939
11940       /* Must clear this because it might contain TYPE_DECLs declared
11941              at class level.  */
11942       current_binding_level->names = NULL;
11943
11944       /* If we're doing semantic analysis, then we'll call pushdecl
11945              for each of these.  We must do them in reverse order so that
11946              they end in the correct forward order.  */
11947       specparms = nreverse (specparms);
11948
11949       for (parm = specparms; parm; parm = next)
11950         {
11951           next = TREE_CHAIN (parm);
11952           if (TREE_CODE (parm) == PARM_DECL)
11953             {
11954               if (DECL_NAME (parm) == NULL_TREE
11955                   || TREE_CODE (parm) != VOID_TYPE)
11956                 pushdecl (parm);
11957               else
11958                 error ("parameter %qD declared void", parm);
11959             }
11960           else
11961             {
11962               /* If we find an enum constant or a type tag,
11963                  put it aside for the moment.  */
11964               TREE_CHAIN (parm) = NULL_TREE;
11965               nonparms = chainon (nonparms, parm);
11966             }
11967         }
11968
11969       /* Get the decls in their original chain order and record in the
11970          function.  This is all and only the PARM_DECLs that were
11971          pushed into scope by the loop above.  */
11972       DECL_ARGUMENTS (fndecl) = getdecls ();
11973     }
11974   else
11975     DECL_ARGUMENTS (fndecl) = NULL_TREE;
11976
11977   /* Now store the final chain of decls for the arguments
11978      as the decl-chain of the current lexical scope.
11979      Put the enumerators in as well, at the front so that
11980      DECL_ARGUMENTS is not modified.  */
11981   current_binding_level->names = chainon (nonparms, DECL_ARGUMENTS (fndecl));
11982
11983   if (use_eh_spec_block (current_function_decl))
11984     current_eh_spec_block = begin_eh_spec_block ();
11985 }
11986
11987 \f
11988 /* We have finished doing semantic analysis on DECL, but have not yet
11989    generated RTL for its body.  Save away our current state, so that
11990    when we want to generate RTL later we know what to do.  */
11991
11992 static void
11993 save_function_data (tree decl)
11994 {
11995   struct language_function *f;
11996
11997   /* Save the language-specific per-function data so that we can
11998      get it back when we really expand this function.  */
11999   gcc_assert (!DECL_PENDING_INLINE_P (decl));
12000
12001   /* Make a copy.  */
12002   f = GGC_NEW (struct language_function);
12003   memcpy (f, cp_function_chain, sizeof (struct language_function));
12004   DECL_SAVED_FUNCTION_DATA (decl) = f;
12005
12006   /* Clear out the bits we don't need.  */
12007   f->base.x_stmt_tree.x_cur_stmt_list = NULL_TREE;
12008   f->bindings = NULL;
12009   f->x_local_names = NULL;
12010 }
12011
12012
12013 /* Set the return value of the constructor (if present).  */
12014
12015 static void
12016 finish_constructor_body (void)
12017 {
12018   tree val;
12019   tree exprstmt;
12020
12021   if (targetm.cxx.cdtor_returns_this ()
12022       && (! TYPE_FOR_JAVA (current_class_type)))
12023     {
12024       /* Any return from a constructor will end up here.  */
12025       add_stmt (build_stmt (input_location, LABEL_EXPR, cdtor_label));
12026
12027       val = DECL_ARGUMENTS (current_function_decl);
12028       val = build2 (MODIFY_EXPR, TREE_TYPE (val),
12029                     DECL_RESULT (current_function_decl), val);
12030       /* Return the address of the object.  */
12031       exprstmt = build_stmt (input_location, RETURN_EXPR, val);
12032       add_stmt (exprstmt);
12033     }
12034 }
12035
12036 /* Do all the processing for the beginning of a destructor; set up the
12037    vtable pointers and cleanups for bases and members.  */
12038
12039 static void
12040 begin_destructor_body (void)
12041 {
12042   tree compound_stmt;
12043
12044   /* If the CURRENT_CLASS_TYPE is incomplete, we will have already
12045      issued an error message.  We still want to try to process the
12046      body of the function, but initialize_vtbl_ptrs will crash if
12047      TYPE_BINFO is NULL.  */
12048   if (COMPLETE_TYPE_P (current_class_type))
12049     {
12050       compound_stmt = begin_compound_stmt (0);
12051       /* Make all virtual function table pointers in non-virtual base
12052          classes point to CURRENT_CLASS_TYPE's virtual function
12053          tables.  */
12054       initialize_vtbl_ptrs (current_class_ptr);
12055       finish_compound_stmt (compound_stmt);
12056
12057       /* And insert cleanups for our bases and members so that they
12058          will be properly destroyed if we throw.  */
12059       push_base_cleanups ();
12060     }
12061 }
12062
12063 /* At the end of every destructor we generate code to delete the object if
12064    necessary.  Do that now.  */
12065
12066 static void
12067 finish_destructor_body (void)
12068 {
12069   tree exprstmt;
12070
12071   /* Any return from a destructor will end up here; that way all base
12072      and member cleanups will be run when the function returns.  */
12073   add_stmt (build_stmt (input_location, LABEL_EXPR, cdtor_label));
12074
12075   /* In a virtual destructor, we must call delete.  */
12076   if (DECL_VIRTUAL_P (current_function_decl))
12077     {
12078       tree if_stmt;
12079       tree virtual_size = cxx_sizeof (current_class_type);
12080
12081       /* [class.dtor]
12082
12083       At the point of definition of a virtual destructor (including
12084       an implicit definition), non-placement operator delete shall
12085       be looked up in the scope of the destructor's class and if
12086       found shall be accessible and unambiguous.  */
12087       exprstmt = build_op_delete_call(DELETE_EXPR, current_class_ptr,
12088                                       virtual_size,
12089                                       /*global_p=*/false,
12090                                       /*placement=*/NULL_TREE,
12091                                       /*alloc_fn=*/NULL_TREE);
12092
12093       if_stmt = begin_if_stmt ();
12094       finish_if_stmt_cond (build2 (BIT_AND_EXPR, integer_type_node,
12095                                    current_in_charge_parm,
12096                                    integer_one_node),
12097                            if_stmt);
12098       finish_expr_stmt (exprstmt);
12099       finish_then_clause (if_stmt);
12100       finish_if_stmt (if_stmt);
12101     }
12102
12103   if (targetm.cxx.cdtor_returns_this ())
12104     {
12105       tree val;
12106
12107       val = DECL_ARGUMENTS (current_function_decl);
12108       val = build2 (MODIFY_EXPR, TREE_TYPE (val),
12109                     DECL_RESULT (current_function_decl), val);
12110       /* Return the address of the object.  */
12111       exprstmt = build_stmt (input_location, RETURN_EXPR, val);
12112       add_stmt (exprstmt);
12113     }
12114 }
12115
12116 /* Do the necessary processing for the beginning of a function body, which
12117    in this case includes member-initializers, but not the catch clauses of
12118    a function-try-block.  Currently, this means opening a binding level
12119    for the member-initializers (in a ctor) and member cleanups (in a dtor).  */
12120
12121 tree
12122 begin_function_body (void)
12123 {
12124   tree stmt;
12125
12126   if (! FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
12127     return NULL_TREE;
12128
12129   if (processing_template_decl)
12130     /* Do nothing now.  */;
12131   else
12132     /* Always keep the BLOCK node associated with the outermost pair of
12133        curly braces of a function.  These are needed for correct
12134        operation of dwarfout.c.  */
12135     keep_next_level (true);
12136
12137   stmt = begin_compound_stmt (BCS_FN_BODY);
12138
12139   if (processing_template_decl)
12140     /* Do nothing now.  */;
12141   else if (DECL_DESTRUCTOR_P (current_function_decl))
12142     begin_destructor_body ();
12143
12144   return stmt;
12145 }
12146
12147 /* Do the processing for the end of a function body.  Currently, this means
12148    closing out the cleanups for fully-constructed bases and members, and in
12149    the case of the destructor, deleting the object if desired.  Again, this
12150    is only meaningful for [cd]tors, since they are the only functions where
12151    there is a significant distinction between the main body and any
12152    function catch clauses.  Handling, say, main() return semantics here
12153    would be wrong, as flowing off the end of a function catch clause for
12154    main() would also need to return 0.  */
12155
12156 void
12157 finish_function_body (tree compstmt)
12158 {
12159   if (compstmt == NULL_TREE)
12160     return;
12161
12162   /* Close the block.  */
12163   finish_compound_stmt (compstmt);
12164
12165   if (processing_template_decl)
12166     /* Do nothing now.  */;
12167   else if (DECL_CONSTRUCTOR_P (current_function_decl))
12168     finish_constructor_body ();
12169   else if (DECL_DESTRUCTOR_P (current_function_decl))
12170     finish_destructor_body ();
12171 }
12172
12173 /* Given a function, returns the BLOCK corresponding to the outermost level
12174    of curly braces, skipping the artificial block created for constructor
12175    initializers.  */
12176
12177 tree
12178 outer_curly_brace_block (tree fndecl)
12179 {
12180   tree block = BLOCK_SUBBLOCKS (DECL_INITIAL (fndecl));
12181   if (FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
12182     /* Skip the artificial function body block.  */
12183     block = BLOCK_SUBBLOCKS (block);
12184   return block;
12185 }
12186
12187 /* Finish up a function declaration and compile that function
12188    all the way to assembler language output.  The free the storage
12189    for the function definition.
12190
12191    FLAGS is a bitwise or of the following values:
12192      2 - INCLASS_INLINE
12193        We just finished processing the body of an in-class inline
12194        function definition.  (This processing will have taken place
12195        after the class definition is complete.)  */
12196
12197 tree
12198 finish_function (int flags)
12199 {
12200   tree fndecl = current_function_decl;
12201   tree fntype, ctype = NULL_TREE;
12202   int inclass_inline = (flags & 2) != 0;
12203   int nested;
12204
12205   /* When we get some parse errors, we can end up without a
12206      current_function_decl, so cope.  */
12207   if (fndecl == NULL_TREE)
12208     return error_mark_node;
12209
12210   gcc_assert (!defer_mark_used_calls);
12211   defer_mark_used_calls = true;
12212
12213   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
12214       && DECL_VIRTUAL_P (fndecl)
12215       && !processing_template_decl)
12216     {
12217       tree fnclass = DECL_CONTEXT (fndecl);
12218       if (fndecl == CLASSTYPE_KEY_METHOD (fnclass))
12219         keyed_classes = tree_cons (NULL_TREE, fnclass, keyed_classes);
12220     }
12221
12222   nested = function_depth > 1;
12223   fntype = TREE_TYPE (fndecl);
12224
12225   /*  TREE_READONLY (fndecl) = 1;
12226       This caused &foo to be of type ptr-to-const-function
12227       which then got a warning when stored in a ptr-to-function variable.  */
12228
12229   gcc_assert (building_stmt_tree ());
12230   /* The current function is being defined, so its DECL_INITIAL should
12231      be set, and unless there's a multiple definition, it should be
12232      error_mark_node.  */
12233   gcc_assert (DECL_INITIAL (fndecl) == error_mark_node);
12234
12235   /* For a cloned function, we've already got all the code we need;
12236      there's no need to add any extra bits.  */
12237   if (!DECL_CLONED_FUNCTION_P (fndecl))
12238     {
12239       if (DECL_MAIN_P (current_function_decl))
12240         {
12241           tree stmt;
12242
12243           /* Make it so that `main' always returns 0 by default (or
12244              1 for VMS).  */
12245 #if VMS_TARGET
12246           stmt = finish_return_stmt (integer_one_node);
12247 #else
12248           stmt = finish_return_stmt (integer_zero_node);
12249 #endif
12250           /* Hack.  We don't want the middle-end to warn that this
12251              return is unreachable, so put the statement on the
12252              special line 0.  */
12253           {
12254             location_t linezero = linemap_line_start (line_table, 0, 1);
12255             SET_EXPR_LOCATION (stmt, linezero);
12256           }
12257         }
12258
12259       if (use_eh_spec_block (current_function_decl))
12260         finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
12261                               (TREE_TYPE (current_function_decl)),
12262                               current_eh_spec_block);
12263     }
12264
12265   /* If we're saving up tree structure, tie off the function now.  */
12266   DECL_SAVED_TREE (fndecl) = pop_stmt_list (DECL_SAVED_TREE (fndecl));
12267
12268   finish_fname_decls ();
12269
12270   /* If this function can't throw any exceptions, remember that.  */
12271   if (!processing_template_decl
12272       && !cp_function_chain->can_throw
12273       && !flag_non_call_exceptions
12274       && !DECL_REPLACEABLE_P (fndecl))
12275     TREE_NOTHROW (fndecl) = 1;
12276
12277   /* This must come after expand_function_end because cleanups might
12278      have declarations (from inline functions) that need to go into
12279      this function's blocks.  */
12280
12281   /* If the current binding level isn't the outermost binding level
12282      for this function, either there is a bug, or we have experienced
12283      syntax errors and the statement tree is malformed.  */
12284   if (current_binding_level->kind != sk_function_parms)
12285     {
12286       /* Make sure we have already experienced errors.  */
12287       gcc_assert (errorcount);
12288
12289       /* Throw away the broken statement tree and extra binding
12290          levels.  */
12291       DECL_SAVED_TREE (fndecl) = alloc_stmt_list ();
12292
12293       while (current_binding_level->kind != sk_function_parms)
12294         {
12295           if (current_binding_level->kind == sk_class)
12296             pop_nested_class ();
12297           else
12298             poplevel (0, 0, 0);
12299         }
12300     }
12301   poplevel (1, 0, 1);
12302
12303   /* Statements should always be full-expressions at the outermost set
12304      of curly braces for a function.  */
12305   gcc_assert (stmts_are_full_exprs_p ());
12306
12307   /* Set up the named return value optimization, if we can.  Candidate
12308      variables are selected in check_return_expr.  */
12309   if (current_function_return_value)
12310     {
12311       tree r = current_function_return_value;
12312       tree outer;
12313
12314       if (r != error_mark_node
12315           /* This is only worth doing for fns that return in memory--and
12316              simpler, since we don't have to worry about promoted modes.  */
12317           && aggregate_value_p (TREE_TYPE (TREE_TYPE (fndecl)), fndecl)
12318           /* Only allow this for variables declared in the outer scope of
12319              the function so we know that their lifetime always ends with a
12320              return; see g++.dg/opt/nrv6.C.  We could be more flexible if
12321              we were to do this optimization in tree-ssa.  */
12322           && (outer = outer_curly_brace_block (fndecl))
12323           && chain_member (r, BLOCK_VARS (outer)))
12324         finalize_nrv (&DECL_SAVED_TREE (fndecl), r, DECL_RESULT (fndecl));
12325
12326       current_function_return_value = NULL_TREE;
12327     }
12328
12329   /* Remember that we were in class scope.  */
12330   if (current_class_name)
12331     ctype = current_class_type;
12332
12333   /* Must mark the RESULT_DECL as being in this function.  */
12334   DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
12335
12336   /* Set the BLOCK_SUPERCONTEXT of the outermost function scope to point
12337      to the FUNCTION_DECL node itself.  */
12338   BLOCK_SUPERCONTEXT (DECL_INITIAL (fndecl)) = fndecl;
12339
12340   /* Save away current state, if appropriate.  */
12341   if (!processing_template_decl)
12342     save_function_data (fndecl);
12343
12344   /* Complain if there's just no return statement.  */
12345   if (warn_return_type
12346       && TREE_CODE (TREE_TYPE (fntype)) != VOID_TYPE
12347       && !dependent_type_p (TREE_TYPE (fntype))
12348       && !current_function_returns_value && !current_function_returns_null
12349       /* Don't complain if we abort or throw.  */
12350       && !current_function_returns_abnormally
12351       && !DECL_NAME (DECL_RESULT (fndecl))
12352       && !TREE_NO_WARNING (fndecl)
12353       /* Structor return values (if any) are set by the compiler.  */
12354       && !DECL_CONSTRUCTOR_P (fndecl)
12355       && !DECL_DESTRUCTOR_P (fndecl))
12356     {
12357       warning (OPT_Wreturn_type,
12358                "no return statement in function returning non-void");
12359       TREE_NO_WARNING (fndecl) = 1;
12360     }
12361
12362   /* Store the end of the function, so that we get good line number
12363      info for the epilogue.  */
12364   cfun->function_end_locus = input_location;
12365
12366   /* Genericize before inlining.  */
12367   if (!processing_template_decl)
12368     {
12369       struct language_function *f = DECL_SAVED_FUNCTION_DATA (fndecl);
12370       invoke_plugin_callbacks (PLUGIN_CXX_CP_PRE_GENERICIZE, fndecl);
12371       cp_genericize (fndecl);
12372       /* Clear out the bits we don't need.  */
12373       f->x_current_class_ptr = NULL;
12374       f->x_current_class_ref = NULL;
12375       f->x_eh_spec_block = NULL;
12376       f->x_in_charge_parm = NULL;
12377       f->x_vtt_parm = NULL;
12378       f->x_return_value = NULL;
12379       f->bindings = NULL;
12380       f->extern_decl_map = NULL;
12381     }
12382   /* Clear out the bits we don't need.  */
12383   local_names = NULL;
12384
12385   /* We're leaving the context of this function, so zap cfun.  It's still in
12386      DECL_STRUCT_FUNCTION, and we'll restore it in tree_rest_of_compilation.  */
12387   set_cfun (NULL);
12388   current_function_decl = NULL;
12389
12390   /* If this is an in-class inline definition, we may have to pop the
12391      bindings for the template parameters that we added in
12392      maybe_begin_member_template_processing when start_function was
12393      called.  */
12394   if (inclass_inline)
12395     maybe_end_member_template_processing ();
12396
12397   /* Leave the scope of the class.  */
12398   if (ctype)
12399     pop_nested_class ();
12400
12401   --function_depth;
12402
12403   /* Clean up.  */
12404   if (! nested)
12405     /* Let the error reporting routines know that we're outside a
12406        function.  For a nested function, this value is used in
12407        cxx_pop_function_context and then reset via pop_function_context.  */
12408     current_function_decl = NULL_TREE;
12409
12410   defer_mark_used_calls = false;
12411   if (deferred_mark_used_calls)
12412     {
12413       unsigned int i;
12414       tree decl;
12415
12416       for (i = 0; VEC_iterate (tree, deferred_mark_used_calls, i, decl); i++)
12417         mark_used (decl);
12418       VEC_free (tree, gc, deferred_mark_used_calls);
12419     }
12420
12421   return fndecl;
12422 }
12423 \f
12424 /* Create the FUNCTION_DECL for a function definition.
12425    DECLSPECS and DECLARATOR are the parts of the declaration;
12426    they describe the return type and the name of the function,
12427    but twisted together in a fashion that parallels the syntax of C.
12428
12429    This function creates a binding context for the function body
12430    as well as setting up the FUNCTION_DECL in current_function_decl.
12431
12432    Returns a FUNCTION_DECL on success.
12433
12434    If the DECLARATOR is not suitable for a function (it defines a datum
12435    instead), we return 0, which tells yyparse to report a parse error.
12436
12437    May return void_type_node indicating that this method is actually
12438    a friend.  See grokfield for more details.
12439
12440    Came here with a `.pushlevel' .
12441
12442    DO NOT MAKE ANY CHANGES TO THIS CODE WITHOUT MAKING CORRESPONDING
12443    CHANGES TO CODE IN `grokfield'.  */
12444
12445 tree
12446 start_method (cp_decl_specifier_seq *declspecs,
12447               const cp_declarator *declarator, tree attrlist)
12448 {
12449   tree fndecl = grokdeclarator (declarator, declspecs, MEMFUNCDEF, 0,
12450                                 &attrlist);
12451
12452   if (fndecl == error_mark_node)
12453     return error_mark_node;
12454
12455   if (fndecl == NULL || TREE_CODE (fndecl) != FUNCTION_DECL)
12456     {
12457       error ("invalid member function declaration");
12458       return error_mark_node;
12459     }
12460
12461   if (attrlist)
12462     cplus_decl_attributes (&fndecl, attrlist, 0);
12463
12464   /* Pass friends other than inline friend functions back.  */
12465   if (fndecl == void_type_node)
12466     return fndecl;
12467
12468   if (DECL_IN_AGGR_P (fndecl))
12469     {
12470       if (DECL_CONTEXT (fndecl)
12471           && TREE_CODE (DECL_CONTEXT (fndecl)) != NAMESPACE_DECL)
12472         error ("%qD is already defined in class %qT", fndecl,
12473                DECL_CONTEXT (fndecl));
12474       return error_mark_node;
12475     }
12476
12477   check_template_shadow (fndecl);
12478
12479   DECL_DECLARED_INLINE_P (fndecl) = 1;
12480   DECL_NO_INLINE_WARNING_P (fndecl) = 1;
12481
12482   /* We process method specializations in finish_struct_1.  */
12483   if (processing_template_decl && !DECL_TEMPLATE_SPECIALIZATION (fndecl))
12484     {
12485       fndecl = push_template_decl (fndecl);
12486       if (fndecl == error_mark_node)
12487         return fndecl;
12488     }
12489
12490   if (! DECL_FRIEND_P (fndecl))
12491     {
12492       if (TREE_CHAIN (fndecl))
12493         {
12494           fndecl = copy_node (fndecl);
12495           TREE_CHAIN (fndecl) = NULL_TREE;
12496         }
12497     }
12498
12499   cp_finish_decl (fndecl, NULL_TREE, false, NULL_TREE, 0);
12500
12501   /* Make a place for the parms.  */
12502   begin_scope (sk_function_parms, fndecl);
12503
12504   DECL_IN_AGGR_P (fndecl) = 1;
12505   return fndecl;
12506 }
12507
12508 /* Go through the motions of finishing a function definition.
12509    We don't compile this method until after the whole class has
12510    been processed.
12511
12512    FINISH_METHOD must return something that looks as though it
12513    came from GROKFIELD (since we are defining a method, after all).
12514
12515    This is called after parsing the body of the function definition.
12516    STMTS is the chain of statements that makes up the function body.
12517
12518    DECL is the ..._DECL that `start_method' provided.  */
12519
12520 tree
12521 finish_method (tree decl)
12522 {
12523   tree fndecl = decl;
12524   tree old_initial;
12525
12526   tree link;
12527
12528   if (decl == void_type_node)
12529     return decl;
12530
12531   old_initial = DECL_INITIAL (fndecl);
12532
12533   /* Undo the level for the parms (from start_method).
12534      This is like poplevel, but it causes nothing to be
12535      saved.  Saving information here confuses symbol-table
12536      output routines.  Besides, this information will
12537      be correctly output when this method is actually
12538      compiled.  */
12539
12540   /* Clear out the meanings of the local variables of this level;
12541      also record in each decl which block it belongs to.  */
12542
12543   for (link = current_binding_level->names; link; link = TREE_CHAIN (link))
12544     {
12545       if (DECL_NAME (link) != NULL_TREE)
12546         pop_binding (DECL_NAME (link), link);
12547       gcc_assert (TREE_CODE (link) != FUNCTION_DECL);
12548       DECL_CONTEXT (link) = NULL_TREE;
12549     }
12550
12551   poplevel (0, 0, 0);
12552
12553   DECL_INITIAL (fndecl) = old_initial;
12554
12555   return decl;
12556 }
12557 \f
12558
12559 /* VAR is a VAR_DECL.  If its type is incomplete, remember VAR so that
12560    we can lay it out later, when and if its type becomes complete.  */
12561
12562 void
12563 maybe_register_incomplete_var (tree var)
12564 {
12565   gcc_assert (TREE_CODE (var) == VAR_DECL);
12566
12567   /* Keep track of variables with incomplete types.  */
12568   if (!processing_template_decl && TREE_TYPE (var) != error_mark_node
12569       && DECL_EXTERNAL (var))
12570     {
12571       tree inner_type = TREE_TYPE (var);
12572
12573       while (TREE_CODE (inner_type) == ARRAY_TYPE)
12574         inner_type = TREE_TYPE (inner_type);
12575       inner_type = TYPE_MAIN_VARIANT (inner_type);
12576
12577       if ((!COMPLETE_TYPE_P (inner_type) && CLASS_TYPE_P (inner_type))
12578           /* RTTI TD entries are created while defining the type_info.  */
12579           || (TYPE_LANG_SPECIFIC (inner_type)
12580               && TYPE_BEING_DEFINED (inner_type)))
12581         incomplete_vars = tree_cons (inner_type, var, incomplete_vars);
12582     }
12583 }
12584
12585 /* Called when a class type (given by TYPE) is defined.  If there are
12586    any existing VAR_DECLs whose type has been completed by this
12587    declaration, update them now.  */
12588
12589 void
12590 complete_vars (tree type)
12591 {
12592   tree *list = &incomplete_vars;
12593
12594   gcc_assert (CLASS_TYPE_P (type));
12595   while (*list)
12596     {
12597       if (same_type_p (type, TREE_PURPOSE (*list)))
12598         {
12599           tree var = TREE_VALUE (*list);
12600           tree type = TREE_TYPE (var);
12601           /* Complete the type of the variable.  The VAR_DECL itself
12602              will be laid out in expand_expr.  */
12603           complete_type (type);
12604           cp_apply_type_quals_to_decl (cp_type_quals (type), var);
12605           /* Remove this entry from the list.  */
12606           *list = TREE_CHAIN (*list);
12607         }
12608       else
12609         list = &TREE_CHAIN (*list);
12610     }
12611
12612   /* Check for pending declarations which may have abstract type.  */
12613   complete_type_check_abstract (type);
12614 }
12615
12616 /* If DECL is of a type which needs a cleanup, build and return an
12617    expression to perform that cleanup here.  Return NULL_TREE if no
12618    cleanup need be done.  */
12619
12620 tree
12621 cxx_maybe_build_cleanup (tree decl)
12622 {
12623   tree type;
12624   tree attr;
12625   tree cleanup;
12626
12627   /* Assume no cleanup is required.  */
12628   cleanup = NULL_TREE;
12629
12630   if (error_operand_p (decl))
12631     return cleanup;
12632
12633   /* Handle "__attribute__((cleanup))".  We run the cleanup function
12634      before the destructor since the destructor is what actually
12635      terminates the lifetime of the object.  */
12636   attr = lookup_attribute ("cleanup", DECL_ATTRIBUTES (decl));
12637   if (attr)
12638     {
12639       tree id;
12640       tree fn;
12641       tree arg;
12642
12643       /* Get the name specified by the user for the cleanup function.  */
12644       id = TREE_VALUE (TREE_VALUE (attr));
12645       /* Look up the name to find the cleanup function to call.  It is
12646          important to use lookup_name here because that is what is
12647          used in c-common.c:handle_cleanup_attribute when performing
12648          initial checks on the attribute.  Note that those checks
12649          include ensuring that the function found is not an overloaded
12650          function, or an object with an overloaded call operator,
12651          etc.; we can rely on the fact that the function found is an
12652          ordinary FUNCTION_DECL.  */
12653       fn = lookup_name (id);
12654       arg = build_address (decl);
12655       mark_used (decl);
12656       cleanup = cp_build_function_call (fn, build_tree_list (NULL_TREE,
12657                                                              arg),
12658                                         tf_warning_or_error);
12659     }
12660   /* Handle ordinary C++ destructors.  */
12661   type = TREE_TYPE (decl);
12662   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
12663     {
12664       int flags = LOOKUP_NORMAL|LOOKUP_DESTRUCTOR;
12665       bool has_vbases = (TREE_CODE (type) == RECORD_TYPE
12666                          && CLASSTYPE_VBASECLASSES (type));
12667       tree addr;
12668       tree call;
12669
12670       if (TREE_CODE (type) == ARRAY_TYPE)
12671         addr = decl;
12672       else
12673         addr = build_address (decl);
12674
12675       /* Optimize for space over speed here.  */
12676       if (!has_vbases || flag_expensive_optimizations)
12677         flags |= LOOKUP_NONVIRTUAL;
12678
12679       call = build_delete (TREE_TYPE (addr), addr,
12680                            sfk_complete_destructor, flags, 0);
12681       if (cleanup)
12682         cleanup = build_compound_expr (input_location, cleanup, call);
12683       else
12684         cleanup = call;
12685     }
12686
12687   return cleanup;
12688 }
12689 \f
12690 /* When a stmt has been parsed, this function is called.  */
12691
12692 void
12693 finish_stmt (void)
12694 {
12695 }
12696
12697 /* DECL was originally constructed as a non-static member function,
12698    but turned out to be static.  Update it accordingly.  */
12699
12700 void
12701 revert_static_member_fn (tree decl)
12702 {
12703   tree tmp;
12704   tree function = TREE_TYPE (decl);
12705   tree args = TYPE_ARG_TYPES (function);
12706
12707   if (cp_type_quals (TREE_TYPE (TREE_VALUE (args)))
12708       != TYPE_UNQUALIFIED)
12709     error ("static member function %q#D declared with type qualifiers", decl);
12710
12711   args = TREE_CHAIN (args);
12712   tmp = build_function_type (TREE_TYPE (function), args);
12713   tmp = build_qualified_type (tmp, cp_type_quals (function));
12714   tmp = build_exception_variant (tmp,
12715                                  TYPE_RAISES_EXCEPTIONS (function));
12716   TREE_TYPE (decl) = tmp;
12717   if (DECL_ARGUMENTS (decl))
12718     DECL_ARGUMENTS (decl) = TREE_CHAIN (DECL_ARGUMENTS (decl));
12719   DECL_STATIC_FUNCTION_P (decl) = 1;
12720 }
12721
12722 /* Return which tree structure is used by T, or TS_CP_GENERIC if T is
12723    one of the language-independent trees.  */
12724
12725 enum cp_tree_node_structure_enum
12726 cp_tree_node_structure (union lang_tree_node * t)
12727 {
12728   switch (TREE_CODE (&t->generic))
12729     {
12730     case DEFAULT_ARG:           return TS_CP_DEFAULT_ARG;
12731     case IDENTIFIER_NODE:       return TS_CP_IDENTIFIER;
12732     case OVERLOAD:              return TS_CP_OVERLOAD;
12733     case TEMPLATE_PARM_INDEX:   return TS_CP_TPI;
12734     case PTRMEM_CST:            return TS_CP_PTRMEM;
12735     case BASELINK:              return TS_CP_BASELINK;
12736     case STATIC_ASSERT:         return TS_CP_STATIC_ASSERT;
12737     case ARGUMENT_PACK_SELECT:  return TS_CP_ARGUMENT_PACK_SELECT;
12738     case TRAIT_EXPR:            return TS_CP_TRAIT_EXPR;
12739     default:                    return TS_CP_GENERIC;
12740     }
12741 }
12742
12743 /* Build the void_list_node (void_type_node having been created).  */
12744 tree
12745 build_void_list_node (void)
12746 {
12747   tree t = build_tree_list (NULL_TREE, void_type_node);
12748   return t;
12749 }
12750
12751 bool
12752 cp_missing_noreturn_ok_p (tree decl)
12753 {
12754   /* A missing noreturn is ok for the `main' function.  */
12755   return DECL_MAIN_P (decl);
12756 }
12757
12758 /* Return the COMDAT group into which DECL should be placed.  */
12759
12760 tree
12761 cxx_comdat_group (tree decl)
12762 {
12763   tree name;
12764
12765   /* Virtual tables, construction virtual tables, and virtual table
12766      tables all go in a single COMDAT group, named after the primary
12767      virtual table.  */
12768   if (TREE_CODE (decl) == VAR_DECL && DECL_VTABLE_OR_VTT_P (decl))
12769     name = DECL_ASSEMBLER_NAME (CLASSTYPE_VTABLES (DECL_CONTEXT (decl)));
12770   /* For all other DECLs, the COMDAT group is the mangled name of the
12771      declaration itself.  */
12772   else
12773     {
12774       while (DECL_THUNK_P (decl))
12775         {
12776           /* If TARGET_USE_LOCAL_THUNK_ALIAS_P, use_thunk puts the thunk
12777              into the same section as the target function.  In that case
12778              we must return target's name.  */
12779           tree target = THUNK_TARGET (decl);
12780           if (TARGET_USE_LOCAL_THUNK_ALIAS_P (target)
12781               && DECL_SECTION_NAME (target) != NULL
12782               && DECL_ONE_ONLY (target))
12783             decl = target;
12784           else
12785             break;
12786         }
12787       name = DECL_ASSEMBLER_NAME (decl);
12788     }
12789
12790   return name;
12791 }
12792
12793 #include "gt-cp-decl.h"