OSDN Git Service

PR c++/54198
[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, 2010, 2011, 2012
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 "flags.h"
37 #include "cp-tree.h"
38 #include "tree-iterator.h"
39 #include "tree-inline.h"
40 #include "decl.h"
41 #include "intl.h"
42 #include "toplev.h"
43 #include "hashtab.h"
44 #include "tm_p.h"
45 #include "target.h"
46 #include "c-family/c-common.h"
47 #include "c-family/c-objc.h"
48 #include "c-family/c-pragma.h"
49 #include "diagnostic.h"
50 #include "intl.h"
51 #include "debug.h"
52 #include "timevar.h"
53 #include "pointer-set.h"
54 #include "splay-tree.h"
55 #include "plugin.h"
56
57 /* Possible cases of bad specifiers type used by bad_specifiers. */
58 enum bad_spec_place {
59   BSP_VAR,    /* variable */
60   BSP_PARM,   /* parameter */
61   BSP_TYPE,   /* type */
62   BSP_FIELD   /* field */
63 };
64
65 static tree grokparms (tree parmlist, tree *);
66 static const char *redeclaration_error_message (tree, tree);
67
68 static int decl_jump_unsafe (tree);
69 static void require_complete_types_for_parms (tree);
70 static int ambi_op_p (enum tree_code);
71 static int unary_op_p (enum tree_code);
72 static void push_local_name (tree);
73 static tree grok_reference_init (tree, tree, tree, int);
74 static tree grokvardecl (tree, tree, const cp_decl_specifier_seq *,
75                          int, int, tree);
76 static int check_static_variable_definition (tree, tree);
77 static void record_unknown_type (tree, const char *);
78 static tree builtin_function_1 (tree, tree, bool);
79 static tree build_library_fn_1 (tree, enum tree_code, tree);
80 static int member_function_or_else (tree, tree, enum overload_flags);
81 static void bad_specifiers (tree, enum bad_spec_place, int, int, int, int,
82                             int);
83 static void check_for_uninitialized_const_var (tree);
84 static hashval_t typename_hash (const void *);
85 static int typename_compare (const void *, const void *);
86 static tree local_variable_p_walkfn (tree *, int *, void *);
87 static tree record_builtin_java_type (const char *, int);
88 static const char *tag_name (enum tag_types);
89 static tree lookup_and_check_tag (enum tag_types, tree, tag_scope, bool);
90 static int walk_namespaces_r (tree, walk_namespaces_fn, void *);
91 static void maybe_deduce_size_from_array_init (tree, tree);
92 static void layout_var_decl (tree);
93 static tree check_initializer (tree, tree, int, VEC(tree,gc) **);
94 static void make_rtl_for_nonlocal_decl (tree, tree, const char *);
95 static void save_function_data (tree);
96 static void copy_type_enum (tree , tree);
97 static void check_function_type (tree, tree);
98 static void finish_constructor_body (void);
99 static void begin_destructor_body (void);
100 static void finish_destructor_body (void);
101 static void record_key_method_defined (tree);
102 static tree create_array_type_for_decl (tree, tree, tree);
103 static tree get_atexit_node (void);
104 static tree get_dso_handle_node (void);
105 static tree start_cleanup_fn (void);
106 static void end_cleanup_fn (void);
107 static tree cp_make_fname_decl (location_t, tree, int);
108 static void initialize_predefined_identifiers (void);
109 static tree check_special_function_return_type
110         (special_function_kind, tree, tree);
111 static tree push_cp_library_fn (enum tree_code, tree);
112 static tree build_cp_library_fn (tree, enum tree_code, tree);
113 static void store_parm_decls (tree);
114 static void initialize_local_var (tree, tree);
115 static void expand_static_init (tree, tree);
116
117 /* The following symbols are subsumed in the cp_global_trees array, and
118    listed here individually for documentation purposes.
119
120    C++ extensions
121         tree wchar_decl_node;
122
123         tree vtable_entry_type;
124         tree delta_type_node;
125         tree __t_desc_type_node;
126
127         tree class_type_node;
128         tree unknown_type_node;
129
130    Array type `vtable_entry_type[]'
131
132         tree vtbl_type_node;
133         tree vtbl_ptr_type_node;
134
135    Namespaces,
136
137         tree std_node;
138         tree abi_node;
139
140    A FUNCTION_DECL which can call `abort'.  Not necessarily the
141    one that the user will declare, but sufficient to be called
142    by routines that want to abort the program.
143
144         tree abort_fndecl;
145
146    The FUNCTION_DECL for the default `::operator delete'.
147
148         tree global_delete_fndecl;
149
150    Used by RTTI
151         tree type_info_type_node, tinfo_decl_id, tinfo_decl_type;
152         tree tinfo_var_id;  */
153
154 tree cp_global_trees[CPTI_MAX];
155
156 /* Indicates that there is a type value in some namespace, although
157    that is not necessarily in scope at the moment.  */
158
159 tree global_type_node;
160
161 /* The node that holds the "name" of the global scope.  */
162 tree global_scope_name;
163
164 #define local_names cp_function_chain->x_local_names
165
166 /* A list of objects which have constructors or destructors
167    which reside in the global scope.  The decl is stored in
168    the TREE_VALUE slot and the initializer is stored
169    in the TREE_PURPOSE slot.  */
170 tree static_aggregates;
171
172 /* -- end of C++ */
173
174 /* A node for the integer constant 2.  */
175
176 tree integer_two_node;
177
178 /* Used only for jumps to as-yet undefined labels, since jumps to
179    defined labels can have their validity checked immediately.  */
180
181 struct GTY((chain_next ("%h.next"))) named_label_use_entry {
182   struct named_label_use_entry *next;
183   /* The binding level to which this entry is *currently* attached.
184      This is initially the binding level in which the goto appeared,
185      but is modified as scopes are closed.  */
186   cp_binding_level *binding_level;
187   /* The head of the names list that was current when the goto appeared,
188      or the inner scope popped.  These are the decls that will *not* be
189      skipped when jumping to the label.  */
190   tree names_in_scope;
191   /* The location of the goto, for error reporting.  */
192   location_t o_goto_locus;
193   /* True if an OpenMP structured block scope has been closed since
194      the goto appeared.  This means that the branch from the label will
195      illegally exit an OpenMP scope.  */
196   bool in_omp_scope;
197 };
198
199 /* A list of all LABEL_DECLs in the function that have names.  Here so
200    we can clear out their names' definitions at the end of the
201    function, and so we can check the validity of jumps to these labels.  */
202
203 struct GTY(()) named_label_entry {
204   /* The decl itself.  */
205   tree label_decl;
206
207   /* The binding level to which the label is *currently* attached.
208      This is initially set to the binding level in which the label
209      is defined, but is modified as scopes are closed.  */
210   cp_binding_level *binding_level;
211   /* The head of the names list that was current when the label was
212      defined, or the inner scope popped.  These are the decls that will
213      be skipped when jumping to the label.  */
214   tree names_in_scope;
215   /* A vector of all decls from all binding levels that would be
216      crossed by a backward branch to the label.  */
217   VEC(tree,gc) *bad_decls;
218
219   /* A list of uses of the label, before the label is defined.  */
220   struct named_label_use_entry *uses;
221
222   /* The following bits are set after the label is defined, and are
223      updated as scopes are popped.  They indicate that a backward jump
224      to the label will illegally enter a scope of the given flavor.  */
225   bool in_try_scope;
226   bool in_catch_scope;
227   bool in_omp_scope;
228 };
229
230 #define named_labels cp_function_chain->x_named_labels
231 \f
232 /* The number of function bodies which we are currently processing.
233    (Zero if we are at namespace scope, one inside the body of a
234    function, two inside the body of a function in a local class, etc.)  */
235 int function_depth;
236
237 /* To avoid unwanted recursion, finish_function defers all mark_used calls
238    encountered during its execution until it finishes.  */
239 bool defer_mark_used_calls;
240 VEC(tree, gc) *deferred_mark_used_calls;
241
242 /* States indicating how grokdeclarator() should handle declspecs marked
243    with __attribute__((deprecated)).  An object declared as
244    __attribute__((deprecated)) suppresses warnings of uses of other
245    deprecated items.  */
246 enum deprecated_states deprecated_state = DEPRECATED_NORMAL;
247
248 \f
249 /* A list of VAR_DECLs whose type was incomplete at the time the
250    variable was declared.  */
251
252 typedef struct GTY(()) incomplete_var_d {
253   tree decl;
254   tree incomplete_type;
255 } incomplete_var;
256
257 DEF_VEC_O(incomplete_var);
258 DEF_VEC_ALLOC_O(incomplete_var,gc);
259
260 static GTY(()) VEC(incomplete_var,gc) *incomplete_vars;
261 \f
262 /* Returns the kind of template specialization we are currently
263    processing, given that it's declaration contained N_CLASS_SCOPES
264    explicit scope qualifications.  */
265
266 tmpl_spec_kind
267 current_tmpl_spec_kind (int n_class_scopes)
268 {
269   int n_template_parm_scopes = 0;
270   int seen_specialization_p = 0;
271   int innermost_specialization_p = 0;
272   cp_binding_level *b;
273
274   /* Scan through the template parameter scopes.  */
275   for (b = current_binding_level;
276        b->kind == sk_template_parms;
277        b = b->level_chain)
278     {
279       /* If we see a specialization scope inside a parameter scope,
280          then something is wrong.  That corresponds to a declaration
281          like:
282
283             template <class T> template <> ...
284
285          which is always invalid since [temp.expl.spec] forbids the
286          specialization of a class member template if the enclosing
287          class templates are not explicitly specialized as well.  */
288       if (b->explicit_spec_p)
289         {
290           if (n_template_parm_scopes == 0)
291             innermost_specialization_p = 1;
292           else
293             seen_specialization_p = 1;
294         }
295       else if (seen_specialization_p == 1)
296         return tsk_invalid_member_spec;
297
298       ++n_template_parm_scopes;
299     }
300
301   /* Handle explicit instantiations.  */
302   if (processing_explicit_instantiation)
303     {
304       if (n_template_parm_scopes != 0)
305         /* We've seen a template parameter list during an explicit
306            instantiation.  For example:
307
308              template <class T> template void f(int);
309
310            This is erroneous.  */
311         return tsk_invalid_expl_inst;
312       else
313         return tsk_expl_inst;
314     }
315
316   if (n_template_parm_scopes < n_class_scopes)
317     /* We've not seen enough template headers to match all the
318        specialized classes present.  For example:
319
320          template <class T> void R<T>::S<T>::f(int);
321
322        This is invalid; there needs to be one set of template
323        parameters for each class.  */
324     return tsk_insufficient_parms;
325   else if (n_template_parm_scopes == n_class_scopes)
326     /* We're processing a non-template declaration (even though it may
327        be a member of a template class.)  For example:
328
329          template <class T> void S<T>::f(int);
330
331        The `class T' matches the `S<T>', leaving no template headers
332        corresponding to the `f'.  */
333     return tsk_none;
334   else if (n_template_parm_scopes > n_class_scopes + 1)
335     /* We've got too many template headers.  For example:
336
337          template <> template <class T> void f (T);
338
339        There need to be more enclosing classes.  */
340     return tsk_excessive_parms;
341   else
342     /* This must be a template.  It's of the form:
343
344          template <class T> template <class U> void S<T>::f(U);
345
346        This is a specialization if the innermost level was a
347        specialization; otherwise it's just a definition of the
348        template.  */
349     return innermost_specialization_p ? tsk_expl_spec : tsk_template;
350 }
351
352 /* Exit the current scope.  */
353
354 void
355 finish_scope (void)
356 {
357   poplevel (0, 0, 0);
358 }
359
360 /* When a label goes out of scope, check to see if that label was used
361    in a valid manner, and issue any appropriate warnings or errors.  */
362
363 static void
364 pop_label (tree label, tree old_value)
365 {
366   if (!processing_template_decl)
367     {
368       if (DECL_INITIAL (label) == NULL_TREE)
369         {
370           location_t location;
371
372           error ("label %q+D used but not defined", label);
373           location = input_location; /* FIXME want (input_filename, (line)0) */
374           /* Avoid crashing later.  */
375           define_label (location, DECL_NAME (label));
376         }
377       else 
378         warn_for_unused_label (label);
379     }
380
381   SET_IDENTIFIER_LABEL_VALUE (DECL_NAME (label), old_value);
382 }
383
384 /* At the end of a function, all labels declared within the function
385    go out of scope.  BLOCK is the top-level block for the
386    function.  */
387
388 static int
389 pop_labels_1 (void **slot, void *data)
390 {
391   struct named_label_entry *ent = (struct named_label_entry *) *slot;
392   tree block = (tree) data;
393
394   pop_label (ent->label_decl, NULL_TREE);
395
396   /* Put the labels into the "variables" of the top-level block,
397      so debugger can see them.  */
398   DECL_CHAIN (ent->label_decl) = BLOCK_VARS (block);
399   BLOCK_VARS (block) = ent->label_decl;
400
401   htab_clear_slot (named_labels, slot);
402
403   return 1;
404 }
405
406 static void
407 pop_labels (tree block)
408 {
409   if (named_labels)
410     {
411       htab_traverse (named_labels, pop_labels_1, block);
412       named_labels = NULL;
413     }
414 }
415
416 /* At the end of a block with local labels, restore the outer definition.  */
417
418 static void
419 pop_local_label (tree label, tree old_value)
420 {
421   struct named_label_entry dummy;
422   void **slot;
423
424   pop_label (label, old_value);
425
426   dummy.label_decl = label;
427   slot = htab_find_slot (named_labels, &dummy, NO_INSERT);
428   htab_clear_slot (named_labels, slot);
429 }
430
431 /* The following two routines are used to interface to Objective-C++.
432    The binding level is purposely treated as an opaque type.  */
433
434 void *
435 objc_get_current_scope (void)
436 {
437   return current_binding_level;
438 }
439
440 /* The following routine is used by the NeXT-style SJLJ exceptions;
441    variables get marked 'volatile' so as to not be clobbered by
442    _setjmp()/_longjmp() calls.  All variables in the current scope,
443    as well as parent scopes up to (but not including) ENCLOSING_BLK
444    shall be thusly marked.  */
445
446 void
447 objc_mark_locals_volatile (void *enclosing_blk)
448 {
449   cp_binding_level *scope;
450
451   for (scope = current_binding_level;
452        scope && scope != enclosing_blk;
453        scope = scope->level_chain)
454     {
455       tree decl;
456
457       for (decl = scope->names; decl; decl = TREE_CHAIN (decl))
458         objc_volatilize_decl (decl);
459
460       /* Do not climb up past the current function.  */
461       if (scope->kind == sk_function_parms)
462         break;
463     }
464 }
465
466 /* Update data for defined and undefined labels when leaving a scope.  */
467
468 static int
469 poplevel_named_label_1 (void **slot, void *data)
470 {
471   struct named_label_entry *ent = (struct named_label_entry *) *slot;
472   cp_binding_level *bl = (cp_binding_level *) data;
473   cp_binding_level *obl = bl->level_chain;
474
475   if (ent->binding_level == bl)
476     {
477       tree decl;
478
479       /* ENT->NAMES_IN_SCOPE may contain a mixture of DECLs and
480          TREE_LISTs representing OVERLOADs, so be careful.  */
481       for (decl = ent->names_in_scope; decl; decl = (DECL_P (decl)
482                                                      ? DECL_CHAIN (decl)
483                                                      : TREE_CHAIN (decl)))
484         if (decl_jump_unsafe (decl))
485           VEC_safe_push (tree, gc, ent->bad_decls, decl);
486
487       ent->binding_level = obl;
488       ent->names_in_scope = obl->names;
489       switch (bl->kind)
490         {
491         case sk_try:
492           ent->in_try_scope = true;
493           break;
494         case sk_catch:
495           ent->in_catch_scope = true;
496           break;
497         case sk_omp:
498           ent->in_omp_scope = true;
499           break;
500         default:
501           break;
502         }
503     }
504   else if (ent->uses)
505     {
506       struct named_label_use_entry *use;
507
508       for (use = ent->uses; use ; use = use->next)
509         if (use->binding_level == bl)
510           {
511             use->binding_level = obl;
512             use->names_in_scope = obl->names;
513             if (bl->kind == sk_omp)
514               use->in_omp_scope = true;
515           }
516     }
517
518   return 1;
519 }
520
521 /* Saved errorcount to avoid -Wunused-but-set-{parameter,variable} warnings
522    when errors were reported, except for -Werror-unused-but-set-*.  */
523 static int unused_but_set_errorcount;
524
525 /* Exit a binding level.
526    Pop the level off, and restore the state of the identifier-decl mappings
527    that were in effect when this level was entered.
528
529    If KEEP == 1, this level had explicit declarations, so
530    and create a "block" (a BLOCK node) for the level
531    to record its declarations and subblocks for symbol table output.
532
533    If FUNCTIONBODY is nonzero, this level is the body of a function,
534    so create a block as if KEEP were set and also clear out all
535    label names.
536
537    If REVERSE is nonzero, reverse the order of decls before putting
538    them into the BLOCK.  */
539
540 tree
541 poplevel (int keep, int reverse, int functionbody)
542 {
543   tree link;
544   /* The chain of decls was accumulated in reverse order.
545      Put it into forward order, just for cleanliness.  */
546   tree decls;
547   tree subblocks;
548   tree block;
549   tree decl;
550   int leaving_for_scope;
551   scope_kind kind;
552   unsigned ix;
553   cp_label_binding *label_bind;
554
555   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
556  restart:
557
558   block = NULL_TREE;
559
560   gcc_assert (current_binding_level->kind != sk_class);
561
562   if (current_binding_level->kind == sk_cleanup)
563     functionbody = 0;
564   subblocks = functionbody >= 0 ? current_binding_level->blocks : 0;
565
566   gcc_assert (!VEC_length(cp_class_binding,
567                           current_binding_level->class_shadowed));
568
569   /* We used to use KEEP == 2 to indicate that the new block should go
570      at the beginning of the list of blocks at this binding level,
571      rather than the end.  This hack is no longer used.  */
572   gcc_assert (keep == 0 || keep == 1);
573
574   if (current_binding_level->keep)
575     keep = 1;
576
577   /* Any uses of undefined labels, and any defined labels, now operate
578      under constraints of next binding contour.  */
579   if (cfun && !functionbody && named_labels)
580     htab_traverse (named_labels, poplevel_named_label_1,
581                    current_binding_level);
582
583   /* Get the decls in the order they were written.
584      Usually current_binding_level->names is in reverse order.
585      But parameter decls were previously put in forward order.  */
586
587   if (reverse)
588     current_binding_level->names
589       = decls = nreverse (current_binding_level->names);
590   else
591     decls = current_binding_level->names;
592
593   /* If there were any declarations or structure tags in that level,
594      or if this level is a function body,
595      create a BLOCK to record them for the life of this function.  */
596   block = NULL_TREE;
597   if (keep == 1 || functionbody)
598     block = make_node (BLOCK);
599   if (block != NULL_TREE)
600     {
601       BLOCK_VARS (block) = decls;
602       BLOCK_SUBBLOCKS (block) = subblocks;
603     }
604
605   /* In each subblock, record that this is its superior.  */
606   if (keep >= 0)
607     for (link = subblocks; link; link = BLOCK_CHAIN (link))
608       BLOCK_SUPERCONTEXT (link) = block;
609
610   /* We still support the old for-scope rules, whereby the variables
611      in a for-init statement were in scope after the for-statement
612      ended.  We only use the new rules if flag_new_for_scope is
613      nonzero.  */
614   leaving_for_scope
615     = current_binding_level->kind == sk_for && flag_new_for_scope == 1;
616
617   /* Before we remove the declarations first check for unused variables.  */
618   if ((warn_unused_variable || warn_unused_but_set_variable)
619       && !processing_template_decl)
620     for (decl = getdecls (); decl; decl = TREE_CHAIN (decl))
621       if (TREE_CODE (decl) == VAR_DECL
622           && (! TREE_USED (decl) || !DECL_READ_P (decl))
623           && ! DECL_IN_SYSTEM_HEADER (decl)
624           && DECL_NAME (decl) && ! DECL_ARTIFICIAL (decl)
625           && TREE_TYPE (decl) != error_mark_node
626           && (!CLASS_TYPE_P (TREE_TYPE (decl))
627               || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl))))
628         {
629           if (! TREE_USED (decl))
630             warning (OPT_Wunused_variable, "unused variable %q+D", decl);
631           else if (DECL_CONTEXT (decl) == current_function_decl
632                    && TREE_CODE (TREE_TYPE (decl)) != REFERENCE_TYPE
633                    && errorcount == unused_but_set_errorcount)
634             {
635               warning (OPT_Wunused_but_set_variable,
636                        "variable %q+D set but not used", decl); 
637               unused_but_set_errorcount = errorcount;
638             }
639         }
640
641   /* Remove declarations for all the DECLs in this level.  */
642   for (link = decls; link; link = TREE_CHAIN (link))
643     {
644       if (leaving_for_scope && TREE_CODE (link) == VAR_DECL
645           /* It's hard to make this ARM compatibility hack play nicely with
646              lambdas, and it really isn't necessary in C++11 mode.  */
647           && cxx_dialect < cxx0x
648           && DECL_NAME (link))
649         {
650           tree name = DECL_NAME (link);
651           cxx_binding *ob;
652           tree ns_binding;
653
654           ob = outer_binding (name,
655                               IDENTIFIER_BINDING (name),
656                               /*class_p=*/true);
657           if (!ob)
658             ns_binding = IDENTIFIER_NAMESPACE_VALUE (name);
659           else
660             ns_binding = NULL_TREE;
661
662           if (ob && ob->scope == current_binding_level->level_chain)
663             /* We have something like:
664
665                  int i;
666                  for (int i; ;);
667
668                and we are leaving the `for' scope.  There's no reason to
669                keep the binding of the inner `i' in this case.  */
670             pop_binding (name, link);
671           else if ((ob && (TREE_CODE (ob->value) == TYPE_DECL))
672                    || (ns_binding && TREE_CODE (ns_binding) == TYPE_DECL))
673             /* Here, we have something like:
674
675                  typedef int I;
676
677                  void f () {
678                    for (int I; ;);
679                  }
680
681                We must pop the for-scope binding so we know what's a
682                type and what isn't.  */
683             pop_binding (name, link);
684           else
685             {
686               /* Mark this VAR_DECL as dead so that we can tell we left it
687                  there only for backward compatibility.  */
688               DECL_DEAD_FOR_LOCAL (link) = 1;
689
690               /* Keep track of what should have happened when we
691                  popped the binding.  */
692               if (ob && ob->value)
693                 {
694                   SET_DECL_SHADOWED_FOR_VAR (link, ob->value);
695                   DECL_HAS_SHADOWED_FOR_VAR_P (link) = 1;
696                 }
697
698               /* Add it to the list of dead variables in the next
699                  outermost binding to that we can remove these when we
700                  leave that binding.  */
701               VEC_safe_push (tree, gc,
702                              current_binding_level->level_chain->dead_vars_from_for,
703                              link);
704
705               /* Although we don't pop the cxx_binding, we do clear
706                  its SCOPE since the scope is going away now.  */
707               IDENTIFIER_BINDING (name)->scope
708                 = current_binding_level->level_chain;
709             }
710         }
711       else
712         {
713           tree name;
714
715           /* Remove the binding.  */
716           decl = link;
717
718           if (TREE_CODE (decl) == TREE_LIST)
719             decl = TREE_VALUE (decl);
720           name = decl;
721
722           if (TREE_CODE (name) == OVERLOAD)
723             name = OVL_FUNCTION (name);
724
725           gcc_assert (DECL_P (name));
726           pop_binding (DECL_NAME (name), decl);
727         }
728     }
729
730   /* Remove declarations for any `for' variables from inner scopes
731      that we kept around.  */
732   FOR_EACH_VEC_ELT_REVERSE (tree, current_binding_level->dead_vars_from_for,
733                             ix, decl)
734     pop_binding (DECL_NAME (decl), decl);
735
736   /* Restore the IDENTIFIER_TYPE_VALUEs.  */
737   for (link = current_binding_level->type_shadowed;
738        link; link = TREE_CHAIN (link))
739     SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (link), TREE_VALUE (link));
740
741   /* Restore the IDENTIFIER_LABEL_VALUEs for local labels.  */
742   FOR_EACH_VEC_ELT_REVERSE (cp_label_binding,
743                             current_binding_level->shadowed_labels,
744                             ix, label_bind)
745     pop_local_label (label_bind->label, label_bind->prev_value);
746
747   /* There may be OVERLOADs (wrapped in TREE_LISTs) on the BLOCK_VARs
748      list if a `using' declaration put them there.  The debugging
749      back ends won't understand OVERLOAD, so we remove them here.
750      Because the BLOCK_VARS are (temporarily) shared with
751      CURRENT_BINDING_LEVEL->NAMES we must do this fixup after we have
752      popped all the bindings.  */
753   if (block)
754     {
755       tree* d;
756
757       for (d = &BLOCK_VARS (block); *d; )
758         {
759           if (TREE_CODE (*d) == TREE_LIST)
760             *d = TREE_CHAIN (*d);
761           else
762             d = &DECL_CHAIN (*d);
763         }
764     }
765
766   /* If the level being exited is the top level of a function,
767      check over all the labels.  */
768   if (functionbody)
769     {
770       /* Since this is the top level block of a function, the vars are
771          the function's parameters.  Don't leave them in the BLOCK
772          because they are found in the FUNCTION_DECL instead.  */
773       BLOCK_VARS (block) = 0;
774       pop_labels (block);
775     }
776
777   kind = current_binding_level->kind;
778   if (kind == sk_cleanup)
779     {
780       tree stmt;
781
782       /* If this is a temporary binding created for a cleanup, then we'll
783          have pushed a statement list level.  Pop that, create a new
784          BIND_EXPR for the block, and insert it into the stream.  */
785       stmt = pop_stmt_list (current_binding_level->statement_list);
786       stmt = c_build_bind_expr (input_location, block, stmt);
787       add_stmt (stmt);
788     }
789
790   leave_scope ();
791   if (functionbody)
792     {
793       /* The current function is being defined, so its DECL_INITIAL
794          should be error_mark_node.  */
795       gcc_assert (DECL_INITIAL (current_function_decl) == error_mark_node);
796       DECL_INITIAL (current_function_decl) = block;
797     }
798   else if (block)
799     current_binding_level->blocks
800       = block_chainon (current_binding_level->blocks, block);
801
802   /* If we did not make a block for the level just exited,
803      any blocks made for inner levels
804      (since they cannot be recorded as subblocks in that level)
805      must be carried forward so they will later become subblocks
806      of something else.  */
807   else if (subblocks)
808     current_binding_level->blocks
809       = block_chainon (current_binding_level->blocks, subblocks);
810
811   /* Each and every BLOCK node created here in `poplevel' is important
812      (e.g. for proper debugging information) so if we created one
813      earlier, mark it as "used".  */
814   if (block)
815     TREE_USED (block) = 1;
816
817   /* All temporary bindings created for cleanups are popped silently.  */
818   if (kind == sk_cleanup)
819     goto restart;
820
821   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
822   return block;
823 }
824
825 /* Walk all the namespaces contained NAMESPACE, including NAMESPACE
826    itself, calling F for each.  The DATA is passed to F as well.  */
827
828 static int
829 walk_namespaces_r (tree name_space, walk_namespaces_fn f, void* data)
830 {
831   int result = 0;
832   tree current = NAMESPACE_LEVEL (name_space)->namespaces;
833
834   result |= (*f) (name_space, data);
835
836   for (; current; current = DECL_CHAIN (current))
837     result |= walk_namespaces_r (current, f, data);
838
839   return result;
840 }
841
842 /* Walk all the namespaces, calling F for each.  The DATA is passed to
843    F as well.  */
844
845 int
846 walk_namespaces (walk_namespaces_fn f, void* data)
847 {
848   return walk_namespaces_r (global_namespace, f, data);
849 }
850
851 /* Call wrapup_globals_declarations for the globals in NAMESPACE.  If
852    DATA is non-NULL, this is the last time we will call
853    wrapup_global_declarations for this NAMESPACE.  */
854
855 int
856 wrapup_globals_for_namespace (tree name_space, void* data)
857 {
858   cp_binding_level *level = NAMESPACE_LEVEL (name_space);
859   VEC(tree,gc) *statics = level->static_decls;
860   tree *vec = VEC_address (tree, statics);
861   int len = VEC_length (tree, statics);
862   int last_time = (data != 0);
863
864   if (last_time)
865     {
866       check_global_declarations (vec, len);
867       emit_debug_global_declarations (vec, len);
868       return 0;
869     }
870
871   /* Write out any globals that need to be output.  */
872   return wrapup_global_declarations (vec, len);
873 }
874
875 \f
876 /* In C++, you don't have to write `struct S' to refer to `S'; you
877    can just use `S'.  We accomplish this by creating a TYPE_DECL as
878    if the user had written `typedef struct S S'.  Create and return
879    the TYPE_DECL for TYPE.  */
880
881 tree
882 create_implicit_typedef (tree name, tree type)
883 {
884   tree decl;
885
886   decl = build_decl (input_location, TYPE_DECL, name, type);
887   DECL_ARTIFICIAL (decl) = 1;
888   /* There are other implicit type declarations, like the one *within*
889      a class that allows you to write `S::S'.  We must distinguish
890      amongst these.  */
891   SET_DECL_IMPLICIT_TYPEDEF_P (decl);
892   TYPE_NAME (type) = decl;
893   TYPE_STUB_DECL (type) = decl;
894
895   return decl;
896 }
897
898 /* Remember a local name for name-mangling purposes.  */
899
900 static void
901 push_local_name (tree decl)
902 {
903   size_t i, nelts;
904   tree t, name;
905
906   timevar_start (TV_NAME_LOOKUP);
907
908   name = DECL_NAME (decl);
909
910   nelts = VEC_length (tree, local_names);
911   for (i = 0; i < nelts; i++)
912     {
913       t = VEC_index (tree, local_names, i);
914       if (DECL_NAME (t) == name)
915         {
916           if (!DECL_LANG_SPECIFIC (decl))
917             retrofit_lang_decl (decl);
918           DECL_LANG_SPECIFIC (decl)->u.base.u2sel = 1;
919           if (DECL_LANG_SPECIFIC (t))
920             DECL_DISCRIMINATOR (decl) = DECL_DISCRIMINATOR (t) + 1;
921           else
922             DECL_DISCRIMINATOR (decl) = 1;
923
924           VEC_replace (tree, local_names, i, decl);
925           timevar_stop (TV_NAME_LOOKUP);
926           return;
927         }
928     }
929
930   VEC_safe_push (tree, gc, local_names, decl);
931   timevar_stop (TV_NAME_LOOKUP);
932 }
933 \f
934 /* Subroutine of duplicate_decls: return truthvalue of whether
935    or not types of these decls match.
936
937    For C++, we must compare the parameter list so that `int' can match
938    `int&' in a parameter position, but `int&' is not confused with
939    `const int&'.  */
940
941 int
942 decls_match (tree newdecl, tree olddecl)
943 {
944   int types_match;
945
946   if (newdecl == olddecl)
947     return 1;
948
949   if (TREE_CODE (newdecl) != TREE_CODE (olddecl))
950     /* If the two DECLs are not even the same kind of thing, we're not
951        interested in their types.  */
952     return 0;
953
954   gcc_assert (DECL_P (newdecl));
955
956   if (TREE_CODE (newdecl) == FUNCTION_DECL)
957     {
958       tree f1 = TREE_TYPE (newdecl);
959       tree f2 = TREE_TYPE (olddecl);
960       tree p1 = TYPE_ARG_TYPES (f1);
961       tree p2 = TYPE_ARG_TYPES (f2);
962       tree r2;
963
964       /* Specializations of different templates are different functions
965          even if they have the same type.  */
966       tree t1 = (DECL_USE_TEMPLATE (newdecl)
967                  ? DECL_TI_TEMPLATE (newdecl)
968                  : NULL_TREE);
969       tree t2 = (DECL_USE_TEMPLATE (olddecl)
970                  ? DECL_TI_TEMPLATE (olddecl)
971                  : NULL_TREE);
972       if (t1 != t2)
973         return 0;
974
975       if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
976           && ! (DECL_EXTERN_C_P (newdecl)
977                 && DECL_EXTERN_C_P (olddecl)))
978         return 0;
979
980 #ifdef NO_IMPLICIT_EXTERN_C
981       /* A new declaration doesn't match a built-in one unless it
982          is also extern "C".  */
983       if (DECL_IS_BUILTIN (olddecl)
984           && DECL_EXTERN_C_P (olddecl) && !DECL_EXTERN_C_P (newdecl))
985         return 0;
986 #endif
987
988       if (TREE_CODE (f1) != TREE_CODE (f2))
989         return 0;
990
991       /* A declaration with deduced return type should use its pre-deduction
992          type for declaration matching.  */
993       if (FNDECL_USED_AUTO (olddecl))
994         r2 = DECL_STRUCT_FUNCTION (olddecl)->language->x_auto_return_pattern;
995       else
996         r2 = TREE_TYPE (f2);
997
998       if (same_type_p (TREE_TYPE (f1), r2))
999         {
1000           if (!prototype_p (f2) && DECL_EXTERN_C_P (olddecl)
1001               && (DECL_BUILT_IN (olddecl)
1002 #ifndef NO_IMPLICIT_EXTERN_C
1003                   || (DECL_IN_SYSTEM_HEADER (newdecl) && !DECL_CLASS_SCOPE_P (newdecl))
1004                   || (DECL_IN_SYSTEM_HEADER (olddecl) && !DECL_CLASS_SCOPE_P (olddecl))
1005 #endif
1006               ))
1007             {
1008               types_match = self_promoting_args_p (p1);
1009               if (p1 == void_list_node)
1010                 TREE_TYPE (newdecl) = TREE_TYPE (olddecl);
1011             }
1012 #ifndef NO_IMPLICIT_EXTERN_C
1013           else if (!prototype_p (f1)
1014                    && (DECL_EXTERN_C_P (olddecl)
1015                        && DECL_IN_SYSTEM_HEADER (olddecl)
1016                        && !DECL_CLASS_SCOPE_P (olddecl))
1017                    && (DECL_EXTERN_C_P (newdecl)
1018                        && DECL_IN_SYSTEM_HEADER (newdecl)
1019                        && !DECL_CLASS_SCOPE_P (newdecl)))
1020             {
1021               types_match = self_promoting_args_p (p2);
1022               TREE_TYPE (newdecl) = TREE_TYPE (olddecl);
1023             }
1024 #endif
1025           else
1026             types_match =
1027               compparms (p1, p2)
1028               && (TYPE_ATTRIBUTES (TREE_TYPE (newdecl)) == NULL_TREE
1029                   || comp_type_attributes (TREE_TYPE (newdecl),
1030                                            TREE_TYPE (olddecl)) != 0);
1031         }
1032       else
1033         types_match = 0;
1034     }
1035   else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1036     {
1037       if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl))
1038           != TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)))
1039         return 0;
1040
1041       if (!comp_template_parms (DECL_TEMPLATE_PARMS (newdecl),
1042                                 DECL_TEMPLATE_PARMS (olddecl)))
1043         return 0;
1044
1045       if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == TYPE_DECL)
1046         types_match = same_type_p (TREE_TYPE (DECL_TEMPLATE_RESULT (olddecl)),
1047                                    TREE_TYPE (DECL_TEMPLATE_RESULT (newdecl)));
1048       else
1049         types_match = decls_match (DECL_TEMPLATE_RESULT (olddecl),
1050                                    DECL_TEMPLATE_RESULT (newdecl));
1051     }
1052   else
1053     {
1054       /* Need to check scope for variable declaration (VAR_DECL).
1055          For typedef (TYPE_DECL), scope is ignored.  */
1056       if (TREE_CODE (newdecl) == VAR_DECL
1057           && CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1058           /* [dcl.link]
1059              Two declarations for an object with C language linkage
1060              with the same name (ignoring the namespace that qualify
1061              it) that appear in different namespace scopes refer to
1062              the same object.  */
1063           && !(DECL_EXTERN_C_P (olddecl) && DECL_EXTERN_C_P (newdecl)))
1064         return 0;
1065
1066       if (TREE_TYPE (newdecl) == error_mark_node)
1067         types_match = TREE_TYPE (olddecl) == error_mark_node;
1068       else if (TREE_TYPE (olddecl) == NULL_TREE)
1069         types_match = TREE_TYPE (newdecl) == NULL_TREE;
1070       else if (TREE_TYPE (newdecl) == NULL_TREE)
1071         types_match = 0;
1072       else
1073         types_match = comptypes (TREE_TYPE (newdecl),
1074                                  TREE_TYPE (olddecl),
1075                                  COMPARE_REDECLARATION);
1076     }
1077
1078   return types_match;
1079 }
1080
1081 /* If NEWDECL is `static' and an `extern' was seen previously,
1082    warn about it.  OLDDECL is the previous declaration.
1083
1084    Note that this does not apply to the C++ case of declaring
1085    a variable `extern const' and then later `const'.
1086
1087    Don't complain about built-in functions, since they are beyond
1088    the user's control.  */
1089
1090 void
1091 warn_extern_redeclared_static (tree newdecl, tree olddecl)
1092 {
1093   if (TREE_CODE (newdecl) == TYPE_DECL
1094       || TREE_CODE (newdecl) == TEMPLATE_DECL
1095       || TREE_CODE (newdecl) == CONST_DECL
1096       || TREE_CODE (newdecl) == NAMESPACE_DECL)
1097     return;
1098
1099   /* Don't get confused by static member functions; that's a different
1100      use of `static'.  */
1101   if (TREE_CODE (newdecl) == FUNCTION_DECL
1102       && DECL_STATIC_FUNCTION_P (newdecl))
1103     return;
1104
1105   /* If the old declaration was `static', or the new one isn't, then
1106      everything is OK.  */
1107   if (DECL_THIS_STATIC (olddecl) || !DECL_THIS_STATIC (newdecl))
1108     return;
1109
1110   /* It's OK to declare a builtin function as `static'.  */
1111   if (TREE_CODE (olddecl) == FUNCTION_DECL
1112       && DECL_ARTIFICIAL (olddecl))
1113     return;
1114
1115   permerror (input_location, "%qD was declared %<extern%> and later %<static%>", newdecl);
1116   permerror (input_location, "previous declaration of %q+D", olddecl);
1117 }
1118
1119 /* NEW_DECL is a redeclaration of OLD_DECL; both are functions or
1120    function templates.  If their exception specifications do not
1121    match, issue a diagnostic.  */
1122
1123 static void
1124 check_redeclaration_exception_specification (tree new_decl,
1125                                              tree old_decl)
1126 {
1127   tree new_type;
1128   tree old_type;
1129   tree new_exceptions;
1130   tree old_exceptions;
1131
1132   new_type = TREE_TYPE (new_decl);
1133   new_exceptions = TYPE_RAISES_EXCEPTIONS (new_type);
1134   old_type = TREE_TYPE (old_decl);
1135   old_exceptions = TYPE_RAISES_EXCEPTIONS (old_type);
1136
1137   /* [except.spec]
1138
1139      If any declaration of a function has an exception-specification,
1140      all declarations, including the definition and an explicit
1141      specialization, of that function shall have an
1142      exception-specification with the same set of type-ids.  */
1143   if ((pedantic || ! DECL_IN_SYSTEM_HEADER (old_decl))
1144       && ! DECL_IS_BUILTIN (old_decl)
1145       && flag_exceptions
1146       && !comp_except_specs (new_exceptions, old_exceptions, ce_normal))
1147     {
1148       error ("declaration of %qF has a different exception specifier",
1149              new_decl);
1150       error ("from previous declaration %q+F", old_decl);
1151     }
1152 }
1153
1154 /* Return true if OLD_DECL and NEW_DECL agree on constexprness.
1155    Otherwise issue diagnostics.  */
1156
1157 static bool
1158 validate_constexpr_redeclaration (tree old_decl, tree new_decl)
1159 {
1160   old_decl = STRIP_TEMPLATE (old_decl);
1161   new_decl = STRIP_TEMPLATE (new_decl);
1162   if (!VAR_OR_FUNCTION_DECL_P (old_decl)
1163       || !VAR_OR_FUNCTION_DECL_P (new_decl))
1164     return true;
1165   if (DECL_DECLARED_CONSTEXPR_P (old_decl)
1166       == DECL_DECLARED_CONSTEXPR_P (new_decl))
1167     return true;
1168   if (TREE_CODE (old_decl) == FUNCTION_DECL && DECL_BUILT_IN (old_decl))
1169     {
1170       /* Hide a built-in declaration.  */
1171       DECL_DECLARED_CONSTEXPR_P (old_decl)
1172         = DECL_DECLARED_CONSTEXPR_P (new_decl);
1173       return true;
1174     }
1175   error ("redeclaration %qD differs in %<constexpr%>", new_decl);
1176   error ("from previous declaration %q+D", old_decl);
1177   return false;
1178 }
1179
1180 #define GNU_INLINE_P(fn) (DECL_DECLARED_INLINE_P (fn)                   \
1181                           && lookup_attribute ("gnu_inline",            \
1182                                                DECL_ATTRIBUTES (fn)))
1183
1184 /* If NEWDECL is a redeclaration of OLDDECL, merge the declarations.
1185    If the redeclaration is invalid, a diagnostic is issued, and the
1186    error_mark_node is returned.  Otherwise, OLDDECL is returned.
1187
1188    If NEWDECL is not a redeclaration of OLDDECL, NULL_TREE is
1189    returned.
1190
1191    NEWDECL_IS_FRIEND is true if NEWDECL was declared as a friend.  */
1192
1193 tree
1194 duplicate_decls (tree newdecl, tree olddecl, bool newdecl_is_friend)
1195 {
1196   unsigned olddecl_uid = DECL_UID (olddecl);
1197   int olddecl_friend = 0, types_match = 0, hidden_friend = 0;
1198   int new_defines_function = 0;
1199   tree new_template_info;
1200
1201   if (newdecl == olddecl)
1202     return olddecl;
1203
1204   types_match = decls_match (newdecl, olddecl);
1205
1206   /* If either the type of the new decl or the type of the old decl is an
1207      error_mark_node, then that implies that we have already issued an
1208      error (earlier) for some bogus type specification, and in that case,
1209      it is rather pointless to harass the user with yet more error message
1210      about the same declaration, so just pretend the types match here.  */
1211   if (TREE_TYPE (newdecl) == error_mark_node
1212       || TREE_TYPE (olddecl) == error_mark_node)
1213     return error_mark_node;
1214
1215   if (UDLIT_OPER_P (DECL_NAME (newdecl))
1216       && UDLIT_OPER_P (DECL_NAME (olddecl)))
1217     {
1218       if (TREE_CODE (newdecl) == TEMPLATE_DECL
1219           && TREE_CODE (olddecl) != TEMPLATE_DECL
1220           && check_raw_literal_operator (olddecl))
1221         error ("literal operator template %q+D conflicts with"
1222                " raw literal operator %qD", newdecl, olddecl);
1223       else if (TREE_CODE (newdecl) != TEMPLATE_DECL
1224                && TREE_CODE (olddecl) == TEMPLATE_DECL
1225                && check_raw_literal_operator (newdecl))
1226         error ("raw literal operator %q+D conflicts with"
1227                " literal operator template %qD", newdecl, olddecl);
1228     }
1229
1230   if (DECL_P (olddecl)
1231       && TREE_CODE (newdecl) == FUNCTION_DECL
1232       && TREE_CODE (olddecl) == FUNCTION_DECL
1233       && (DECL_UNINLINABLE (newdecl) || DECL_UNINLINABLE (olddecl)))
1234     {
1235       if (DECL_DECLARED_INLINE_P (newdecl)
1236           && DECL_UNINLINABLE (newdecl)
1237           && lookup_attribute ("noinline", DECL_ATTRIBUTES (newdecl)))
1238         /* Already warned elsewhere.  */;
1239       else if (DECL_DECLARED_INLINE_P (olddecl)
1240                && DECL_UNINLINABLE (olddecl)
1241                && lookup_attribute ("noinline", DECL_ATTRIBUTES (olddecl)))
1242         /* Already warned.  */;
1243       else if (DECL_DECLARED_INLINE_P (newdecl)
1244                && DECL_UNINLINABLE (olddecl)
1245                && lookup_attribute ("noinline", DECL_ATTRIBUTES (olddecl)))
1246         {
1247           warning (OPT_Wattributes, "function %q+D redeclared as inline",
1248                    newdecl);
1249           warning (OPT_Wattributes, "previous declaration of %q+D "
1250                    "with attribute noinline", olddecl);
1251         }
1252       else if (DECL_DECLARED_INLINE_P (olddecl)
1253                && DECL_UNINLINABLE (newdecl)
1254                && lookup_attribute ("noinline", DECL_ATTRIBUTES (newdecl)))
1255         {
1256           warning (OPT_Wattributes, "function %q+D redeclared with "
1257                    "attribute noinline", newdecl);
1258           warning (OPT_Wattributes, "previous declaration of %q+D was inline",
1259                    olddecl);
1260         }
1261     }
1262
1263   /* Check for redeclaration and other discrepancies.  */
1264   if (TREE_CODE (olddecl) == FUNCTION_DECL
1265       && DECL_ARTIFICIAL (olddecl))
1266     {
1267       gcc_assert (!DECL_HIDDEN_FRIEND_P (olddecl));
1268       if (TREE_CODE (newdecl) != FUNCTION_DECL)
1269         {
1270           /* Avoid warnings redeclaring built-ins which have not been
1271              explicitly declared.  */
1272           if (DECL_ANTICIPATED (olddecl))
1273             return NULL_TREE;
1274
1275           /* If you declare a built-in or predefined function name as static,
1276              the old definition is overridden, but optionally warn this was a
1277              bad choice of name.  */
1278           if (! TREE_PUBLIC (newdecl))
1279             {
1280               warning (OPT_Wshadow, 
1281                        DECL_BUILT_IN (olddecl)
1282                        ? G_("shadowing built-in function %q#D")
1283                        : G_("shadowing library function %q#D"), olddecl);
1284               /* Discard the old built-in function.  */
1285               return NULL_TREE;
1286             }
1287           /* If the built-in is not ansi, then programs can override
1288              it even globally without an error.  */
1289           else if (! DECL_BUILT_IN (olddecl))
1290             warning (0, "library function %q#D redeclared as non-function %q#D",
1291                      olddecl, newdecl);
1292           else
1293             {
1294               error ("declaration of %q#D", newdecl);
1295               error ("conflicts with built-in declaration %q#D",
1296                      olddecl);
1297             }
1298           return NULL_TREE;
1299         }
1300       else if (!types_match)
1301         {
1302           /* Avoid warnings redeclaring built-ins which have not been
1303              explicitly declared.  */
1304           if (DECL_ANTICIPATED (olddecl))
1305             {
1306               /* Deal with fileptr_type_node.  FILE type is not known
1307                  at the time we create the builtins.  */
1308               tree t1, t2;
1309
1310               for (t1 = TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1311                    t2 = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1312                    t1 || t2;
1313                    t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1314                 if (!t1 || !t2)
1315                   break;
1316                 else if (TREE_VALUE (t2) == fileptr_type_node)
1317                   {
1318                     tree t = TREE_VALUE (t1);
1319
1320                     if (TREE_CODE (t) == POINTER_TYPE
1321                         && TYPE_NAME (TREE_TYPE (t))
1322                         && DECL_NAME (TYPE_NAME (TREE_TYPE (t)))
1323                            == get_identifier ("FILE")
1324                         && compparms (TREE_CHAIN (t1), TREE_CHAIN (t2)))
1325                       {
1326                         tree oldargs = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1327
1328                         TYPE_ARG_TYPES (TREE_TYPE (olddecl))
1329                           = TYPE_ARG_TYPES (TREE_TYPE (newdecl));
1330                         types_match = decls_match (newdecl, olddecl);
1331                         if (types_match)
1332                           return duplicate_decls (newdecl, olddecl,
1333                                                   newdecl_is_friend);
1334                         TYPE_ARG_TYPES (TREE_TYPE (olddecl)) = oldargs;
1335                       }
1336                   }
1337                 else if (! same_type_p (TREE_VALUE (t1), TREE_VALUE (t2)))
1338                   break;
1339             }
1340           else if ((DECL_EXTERN_C_P (newdecl)
1341                     && DECL_EXTERN_C_P (olddecl))
1342                    || compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1343                                  TYPE_ARG_TYPES (TREE_TYPE (olddecl))))
1344             {
1345               /* A near match; override the builtin.  */
1346
1347               if (TREE_PUBLIC (newdecl))
1348                 {
1349                   warning (0, "new declaration %q#D", newdecl);
1350                   warning (0, "ambiguates built-in declaration %q#D",
1351                            olddecl);
1352                 }
1353               else
1354                 warning (OPT_Wshadow, 
1355                          DECL_BUILT_IN (olddecl)
1356                          ? G_("shadowing built-in function %q#D")
1357                          : G_("shadowing library function %q#D"), olddecl);
1358             }
1359           else
1360             /* Discard the old built-in function.  */
1361             return NULL_TREE;
1362
1363           /* Replace the old RTL to avoid problems with inlining.  */
1364           COPY_DECL_RTL (newdecl, olddecl);
1365         }
1366       /* Even if the types match, prefer the new declarations type for
1367          built-ins which have not been explicitly declared, for
1368          exception lists, etc...  */
1369       else if (DECL_IS_BUILTIN (olddecl))
1370         {
1371           tree type = TREE_TYPE (newdecl);
1372           tree attribs = (*targetm.merge_type_attributes)
1373             (TREE_TYPE (olddecl), type);
1374
1375           type = cp_build_type_attribute_variant (type, attribs);
1376           TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = type;
1377         }
1378
1379       /* If a function is explicitly declared "throw ()", propagate that to
1380          the corresponding builtin.  */
1381       if (DECL_BUILT_IN_CLASS (olddecl) == BUILT_IN_NORMAL
1382           && DECL_ANTICIPATED (olddecl)
1383           && TREE_NOTHROW (newdecl)
1384           && !TREE_NOTHROW (olddecl))
1385         {
1386           enum built_in_function fncode = DECL_FUNCTION_CODE (olddecl);
1387           tree tmpdecl = builtin_decl_explicit (fncode);
1388           if (tmpdecl && tmpdecl != olddecl && types_match)
1389             TREE_NOTHROW (tmpdecl)  = 1;
1390         }
1391
1392       /* Whether or not the builtin can throw exceptions has no
1393          bearing on this declarator.  */
1394       TREE_NOTHROW (olddecl) = 0;
1395
1396       if (DECL_THIS_STATIC (newdecl) && !DECL_THIS_STATIC (olddecl))
1397         {
1398           /* If a builtin function is redeclared as `static', merge
1399              the declarations, but make the original one static.  */
1400           DECL_THIS_STATIC (olddecl) = 1;
1401           TREE_PUBLIC (olddecl) = 0;
1402
1403           /* Make the old declaration consistent with the new one so
1404              that all remnants of the builtin-ness of this function
1405              will be banished.  */
1406           SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
1407           COPY_DECL_RTL (newdecl, olddecl);
1408         }
1409     }
1410   else if (TREE_CODE (olddecl) != TREE_CODE (newdecl))
1411     {
1412       /* C++ Standard, 3.3, clause 4:
1413          "[Note: a namespace name or a class template name must be unique
1414          in its declarative region (7.3.2, clause 14). ]"  */
1415       if (TREE_CODE (olddecl) != NAMESPACE_DECL
1416           && TREE_CODE (newdecl) != NAMESPACE_DECL
1417           && (TREE_CODE (olddecl) != TEMPLATE_DECL
1418               || TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)) != TYPE_DECL)
1419           && (TREE_CODE (newdecl) != TEMPLATE_DECL
1420               || TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) != TYPE_DECL))
1421         {
1422           if ((TREE_CODE (olddecl) == TYPE_DECL && DECL_ARTIFICIAL (olddecl)
1423                && TREE_CODE (newdecl) != TYPE_DECL)
1424               || (TREE_CODE (newdecl) == TYPE_DECL && DECL_ARTIFICIAL (newdecl)
1425                   && TREE_CODE (olddecl) != TYPE_DECL))
1426             {
1427               /* We do nothing special here, because C++ does such nasty
1428                  things with TYPE_DECLs.  Instead, just let the TYPE_DECL
1429                  get shadowed, and know that if we need to find a TYPE_DECL
1430                  for a given name, we can look in the IDENTIFIER_TYPE_VALUE
1431                  slot of the identifier.  */
1432               return NULL_TREE;
1433             }
1434             
1435             if ((TREE_CODE (newdecl) == FUNCTION_DECL
1436                  && DECL_FUNCTION_TEMPLATE_P (olddecl))
1437                 || (TREE_CODE (olddecl) == FUNCTION_DECL
1438                     && DECL_FUNCTION_TEMPLATE_P (newdecl)))
1439               return NULL_TREE;
1440         }
1441
1442       error ("%q#D redeclared as different kind of symbol", newdecl);
1443       if (TREE_CODE (olddecl) == TREE_LIST)
1444         olddecl = TREE_VALUE (olddecl);
1445       error ("previous declaration of %q+#D", olddecl);
1446
1447       return error_mark_node;
1448     }
1449   else if (!types_match)
1450     {
1451       if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl))
1452         /* These are certainly not duplicate declarations; they're
1453            from different scopes.  */
1454         return NULL_TREE;
1455
1456       if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1457         {
1458           /* The name of a class template may not be declared to refer to
1459              any other template, class, function, object, namespace, value,
1460              or type in the same scope.  */
1461           if (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)) == TYPE_DECL
1462               || TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == TYPE_DECL)
1463             {
1464               error ("declaration of template %q#D", newdecl);
1465               error ("conflicts with previous declaration %q+#D", olddecl);
1466               return error_mark_node;
1467             }
1468           else if (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)) == FUNCTION_DECL
1469                    && TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == FUNCTION_DECL
1470                    && compparms (TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (olddecl))),
1471                                  TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (newdecl))))
1472                    && comp_template_parms (DECL_TEMPLATE_PARMS (newdecl),
1473                                            DECL_TEMPLATE_PARMS (olddecl))
1474                    /* Template functions can be disambiguated by
1475                       return type.  */
1476                    && same_type_p (TREE_TYPE (TREE_TYPE (newdecl)),
1477                                    TREE_TYPE (TREE_TYPE (olddecl))))
1478             {
1479               error ("new declaration %q#D", newdecl);
1480               error ("ambiguates old declaration %q+#D", olddecl);
1481             }
1482           return NULL_TREE;
1483         }
1484       if (TREE_CODE (newdecl) == FUNCTION_DECL)
1485         {
1486           if (DECL_EXTERN_C_P (newdecl) && DECL_EXTERN_C_P (olddecl))
1487             {
1488               error ("declaration of C function %q#D conflicts with",
1489                      newdecl);
1490               error ("previous declaration %q+#D here", olddecl);
1491               return NULL_TREE;
1492             }
1493           else if (compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1494                               TYPE_ARG_TYPES (TREE_TYPE (olddecl))))
1495             {
1496               error ("new declaration %q#D", newdecl);
1497               if (FNDECL_USED_AUTO (olddecl))
1498                 error_at (DECL_SOURCE_LOCATION (olddecl), "ambiguates old "
1499                           "declaration with deduced return type");
1500               else
1501                 error ("ambiguates old declaration %q+#D", olddecl);
1502               return error_mark_node;
1503             }
1504           else
1505             return NULL_TREE;
1506         }
1507       else
1508         {
1509           error ("conflicting declaration %q#D", newdecl);
1510           error ("%q+D has a previous declaration as %q#D", olddecl, olddecl);
1511           return error_mark_node;
1512         }
1513     }
1514   else if (TREE_CODE (newdecl) == FUNCTION_DECL
1515             && ((DECL_TEMPLATE_SPECIALIZATION (olddecl)
1516                  && (!DECL_TEMPLATE_INFO (newdecl)
1517                      || (DECL_TI_TEMPLATE (newdecl)
1518                          != DECL_TI_TEMPLATE (olddecl))))
1519                 || (DECL_TEMPLATE_SPECIALIZATION (newdecl)
1520                     && (!DECL_TEMPLATE_INFO (olddecl)
1521                         || (DECL_TI_TEMPLATE (olddecl)
1522                             != DECL_TI_TEMPLATE (newdecl))))))
1523     /* It's OK to have a template specialization and a non-template
1524        with the same type, or to have specializations of two
1525        different templates with the same type.  Note that if one is a
1526        specialization, and the other is an instantiation of the same
1527        template, that we do not exit at this point.  That situation
1528        can occur if we instantiate a template class, and then
1529        specialize one of its methods.  This situation is valid, but
1530        the declarations must be merged in the usual way.  */
1531     return NULL_TREE;
1532   else if (TREE_CODE (newdecl) == FUNCTION_DECL
1533            && ((DECL_TEMPLATE_INSTANTIATION (olddecl)
1534                 && !DECL_USE_TEMPLATE (newdecl))
1535                || (DECL_TEMPLATE_INSTANTIATION (newdecl)
1536                    && !DECL_USE_TEMPLATE (olddecl))))
1537     /* One of the declarations is a template instantiation, and the
1538        other is not a template at all.  That's OK.  */
1539     return NULL_TREE;
1540   else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
1541     {
1542       /* In [namespace.alias] we have:
1543
1544            In a declarative region, a namespace-alias-definition can be
1545            used to redefine a namespace-alias declared in that declarative
1546            region to refer only to the namespace to which it already
1547            refers.
1548
1549          Therefore, if we encounter a second alias directive for the same
1550          alias, we can just ignore the second directive.  */
1551       if (DECL_NAMESPACE_ALIAS (newdecl)
1552           && (DECL_NAMESPACE_ALIAS (newdecl)
1553               == DECL_NAMESPACE_ALIAS (olddecl)))
1554         return olddecl;
1555       /* [namespace.alias]
1556
1557          A namespace-name or namespace-alias shall not be declared as
1558          the name of any other entity in the same declarative region.
1559          A namespace-name defined at global scope shall not be
1560          declared as the name of any other entity in any global scope
1561          of the program.  */
1562       error ("declaration of namespace %qD conflicts with", newdecl);
1563       error ("previous declaration of namespace %q+D here", olddecl);
1564       return error_mark_node;
1565     }
1566   else
1567     {
1568       const char *errmsg = redeclaration_error_message (newdecl, olddecl);
1569       if (errmsg)
1570         {
1571           error_at (DECL_SOURCE_LOCATION (newdecl), errmsg, newdecl);
1572           if (DECL_NAME (olddecl) != NULL_TREE)
1573             error ((DECL_INITIAL (olddecl) && namespace_bindings_p ())
1574                    ? G_("%q+#D previously defined here")
1575                    : G_("%q+#D previously declared here"), olddecl);
1576           return error_mark_node;
1577         }
1578       else if (TREE_CODE (olddecl) == FUNCTION_DECL
1579                && DECL_INITIAL (olddecl) != NULL_TREE
1580                && !prototype_p (TREE_TYPE (olddecl))
1581                && prototype_p (TREE_TYPE (newdecl)))
1582         {
1583           /* Prototype decl follows defn w/o prototype.  */
1584           warning_at (input_location, 0, "prototype for %q+#D", newdecl);
1585           warning_at (DECL_SOURCE_LOCATION (olddecl), 0,
1586                       "follows non-prototype definition here");
1587         }
1588       else if ((TREE_CODE (olddecl) == FUNCTION_DECL
1589                 || TREE_CODE (olddecl) == VAR_DECL)
1590                && DECL_LANGUAGE (newdecl) != DECL_LANGUAGE (olddecl))
1591         {
1592           /* [dcl.link]
1593              If two declarations of the same function or object
1594              specify different linkage-specifications ..., the program
1595              is ill-formed.... Except for functions with C++ linkage,
1596              a function declaration without a linkage specification
1597              shall not precede the first linkage specification for
1598              that function.  A function can be declared without a
1599              linkage specification after an explicit linkage
1600              specification has been seen; the linkage explicitly
1601              specified in the earlier declaration is not affected by
1602              such a function declaration.
1603
1604              DR 563 raises the question why the restrictions on
1605              functions should not also apply to objects.  Older
1606              versions of G++ silently ignore the linkage-specification
1607              for this example:
1608
1609                namespace N { 
1610                  extern int i;
1611                  extern "C" int i;
1612                }
1613
1614              which is clearly wrong.  Therefore, we now treat objects
1615              like functions.  */
1616           if (current_lang_depth () == 0)
1617             {
1618               /* There is no explicit linkage-specification, so we use
1619                  the linkage from the previous declaration.  */
1620               if (!DECL_LANG_SPECIFIC (newdecl))
1621                 retrofit_lang_decl (newdecl);
1622               SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
1623             }
1624           else
1625             {
1626               error ("previous declaration of %q+#D with %qL linkage",
1627                      olddecl, DECL_LANGUAGE (olddecl));
1628               error ("conflicts with new declaration with %qL linkage",
1629                      DECL_LANGUAGE (newdecl));
1630             }
1631         }
1632
1633       if (DECL_LANG_SPECIFIC (olddecl) && DECL_USE_TEMPLATE (olddecl))
1634         ;
1635       else if (TREE_CODE (olddecl) == FUNCTION_DECL)
1636         {
1637           tree t1 = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1638           tree t2 = TYPE_ARG_TYPES (TREE_TYPE (newdecl));
1639           int i = 1;
1640
1641           if (TREE_CODE (TREE_TYPE (newdecl)) == METHOD_TYPE)
1642             t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2);
1643
1644           for (; t1 && t1 != void_list_node;
1645                t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2), i++)
1646             if (TREE_PURPOSE (t1) && TREE_PURPOSE (t2))
1647               {
1648                 if (1 == simple_cst_equal (TREE_PURPOSE (t1),
1649                                            TREE_PURPOSE (t2)))
1650                   {
1651                     permerror (input_location, "default argument given for parameter %d of %q#D",
1652                                i, newdecl);
1653                     permerror (input_location, "after previous specification in %q+#D", olddecl);
1654                   }
1655                 else
1656                   {
1657                     error ("default argument given for parameter %d of %q#D",
1658                            i, newdecl);
1659                     error ("after previous specification in %q+#D",
1660                                  olddecl);
1661                   }
1662               }
1663         }
1664     }
1665
1666   /* Do not merge an implicit typedef with an explicit one.  In:
1667
1668        class A;
1669        ...
1670        typedef class A A __attribute__ ((foo));
1671
1672      the attribute should apply only to the typedef.  */
1673   if (TREE_CODE (olddecl) == TYPE_DECL
1674       && (DECL_IMPLICIT_TYPEDEF_P (olddecl)
1675           || DECL_IMPLICIT_TYPEDEF_P (newdecl)))
1676     return NULL_TREE;
1677
1678   /* If new decl is `static' and an `extern' was seen previously,
1679      warn about it.  */
1680   warn_extern_redeclared_static (newdecl, olddecl);
1681
1682   if (!validate_constexpr_redeclaration (olddecl, newdecl))
1683     return error_mark_node;
1684
1685   /* We have committed to returning 1 at this point.  */
1686   if (TREE_CODE (newdecl) == FUNCTION_DECL)
1687     {
1688       /* Now that functions must hold information normally held
1689          by field decls, there is extra work to do so that
1690          declaration information does not get destroyed during
1691          definition.  */
1692       if (DECL_VINDEX (olddecl))
1693         DECL_VINDEX (newdecl) = DECL_VINDEX (olddecl);
1694       if (DECL_CONTEXT (olddecl))
1695         DECL_CONTEXT (newdecl) = DECL_CONTEXT (olddecl);
1696       DECL_STATIC_CONSTRUCTOR (newdecl) |= DECL_STATIC_CONSTRUCTOR (olddecl);
1697       DECL_STATIC_DESTRUCTOR (newdecl) |= DECL_STATIC_DESTRUCTOR (olddecl);
1698       DECL_PURE_VIRTUAL_P (newdecl) |= DECL_PURE_VIRTUAL_P (olddecl);
1699       DECL_VIRTUAL_P (newdecl) |= DECL_VIRTUAL_P (olddecl);
1700       DECL_INVALID_OVERRIDER_P (newdecl) |= DECL_INVALID_OVERRIDER_P (olddecl);
1701       DECL_THIS_STATIC (newdecl) |= DECL_THIS_STATIC (olddecl);
1702       if (DECL_OVERLOADED_OPERATOR_P (olddecl) != ERROR_MARK)
1703         SET_OVERLOADED_OPERATOR_CODE
1704           (newdecl, DECL_OVERLOADED_OPERATOR_P (olddecl));
1705       new_defines_function = DECL_INITIAL (newdecl) != NULL_TREE;
1706
1707       /* Optionally warn about more than one declaration for the same
1708          name, but don't warn about a function declaration followed by a
1709          definition.  */
1710       if (warn_redundant_decls && ! DECL_ARTIFICIAL (olddecl)
1711           && !(new_defines_function && DECL_INITIAL (olddecl) == NULL_TREE)
1712           /* Don't warn about extern decl followed by definition.  */
1713           && !(DECL_EXTERNAL (olddecl) && ! DECL_EXTERNAL (newdecl))
1714           /* Don't warn about friends, let add_friend take care of it.  */
1715           && ! (newdecl_is_friend || DECL_FRIEND_P (olddecl))
1716           /* Don't warn about declaration followed by specialization.  */
1717           && (! DECL_TEMPLATE_SPECIALIZATION (newdecl)
1718               || DECL_TEMPLATE_SPECIALIZATION (olddecl)))
1719         {
1720           warning (OPT_Wredundant_decls, "redundant redeclaration of %qD in same scope", newdecl);
1721           warning (OPT_Wredundant_decls, "previous declaration of %q+D", olddecl);
1722         }
1723
1724       if (DECL_DELETED_FN (newdecl))
1725         {
1726           error ("deleted definition of %qD", newdecl);
1727           error ("after previous declaration %q+D", olddecl);
1728         }
1729       DECL_DELETED_FN (newdecl) |= DECL_DELETED_FN (olddecl);
1730     }
1731
1732   /* Deal with C++: must preserve virtual function table size.  */
1733   if (TREE_CODE (olddecl) == TYPE_DECL)
1734     {
1735       tree newtype = TREE_TYPE (newdecl);
1736       tree oldtype = TREE_TYPE (olddecl);
1737
1738       if (newtype != error_mark_node && oldtype != error_mark_node
1739           && TYPE_LANG_SPECIFIC (newtype) && TYPE_LANG_SPECIFIC (oldtype))
1740         CLASSTYPE_FRIEND_CLASSES (newtype)
1741           = CLASSTYPE_FRIEND_CLASSES (oldtype);
1742
1743       DECL_ORIGINAL_TYPE (newdecl) = DECL_ORIGINAL_TYPE (olddecl);
1744     }
1745
1746   /* Copy all the DECL_... slots specified in the new decl
1747      except for any that we copy here from the old type.  */
1748   DECL_ATTRIBUTES (newdecl)
1749     = (*targetm.merge_decl_attributes) (olddecl, newdecl);
1750
1751   if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1752     {
1753       tree old_result;
1754       tree new_result;
1755       old_result = DECL_TEMPLATE_RESULT (olddecl);
1756       new_result = DECL_TEMPLATE_RESULT (newdecl);
1757       TREE_TYPE (olddecl) = TREE_TYPE (old_result);
1758       DECL_TEMPLATE_SPECIALIZATIONS (olddecl)
1759         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (olddecl),
1760                    DECL_TEMPLATE_SPECIALIZATIONS (newdecl));
1761
1762       DECL_ATTRIBUTES (old_result)
1763         = (*targetm.merge_decl_attributes) (old_result, new_result);
1764
1765       if (DECL_FUNCTION_TEMPLATE_P (newdecl))
1766         {
1767           if (GNU_INLINE_P (old_result) != GNU_INLINE_P (new_result)
1768               && DECL_INITIAL (new_result))
1769             {
1770               if (DECL_INITIAL (old_result))
1771                 DECL_UNINLINABLE (old_result) = 1;
1772               else
1773                 DECL_UNINLINABLE (old_result) = DECL_UNINLINABLE (new_result);
1774               DECL_EXTERNAL (old_result) = DECL_EXTERNAL (new_result);
1775               DECL_NOT_REALLY_EXTERN (old_result)
1776                 = DECL_NOT_REALLY_EXTERN (new_result);
1777               DECL_INTERFACE_KNOWN (old_result)
1778                 = DECL_INTERFACE_KNOWN (new_result);
1779               DECL_DECLARED_INLINE_P (old_result)
1780                 = DECL_DECLARED_INLINE_P (new_result);
1781               DECL_DISREGARD_INLINE_LIMITS (old_result)
1782                 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
1783
1784             }
1785           else
1786             {
1787               DECL_DECLARED_INLINE_P (old_result)
1788                 |= DECL_DECLARED_INLINE_P (new_result);
1789               DECL_DISREGARD_INLINE_LIMITS (old_result)
1790                 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
1791               check_redeclaration_exception_specification (newdecl, olddecl);
1792             }
1793         }
1794
1795       /* If the new declaration is a definition, update the file and
1796          line information on the declaration, and also make
1797          the old declaration the same definition.  */
1798       if (DECL_INITIAL (new_result) != NULL_TREE)
1799         {
1800           DECL_SOURCE_LOCATION (olddecl)
1801             = DECL_SOURCE_LOCATION (old_result)
1802             = DECL_SOURCE_LOCATION (newdecl);
1803           DECL_INITIAL (old_result) = DECL_INITIAL (new_result);
1804           if (DECL_FUNCTION_TEMPLATE_P (newdecl))
1805             {
1806               tree parm;
1807               DECL_ARGUMENTS (old_result)
1808                 = DECL_ARGUMENTS (new_result);
1809               for (parm = DECL_ARGUMENTS (old_result); parm;
1810                    parm = DECL_CHAIN (parm))
1811                 DECL_CONTEXT (parm) = old_result;
1812             }
1813         }
1814
1815       return olddecl;
1816     }
1817
1818   if (types_match)
1819     {
1820       /* Automatically handles default parameters.  */
1821       tree oldtype = TREE_TYPE (olddecl);
1822       tree newtype;
1823
1824       if (TREE_CODE (newdecl) == FUNCTION_DECL)
1825         maybe_instantiate_noexcept (olddecl);
1826
1827       /* Merge the data types specified in the two decls.  */
1828       newtype = merge_types (TREE_TYPE (newdecl), TREE_TYPE (olddecl));
1829
1830       /* If merge_types produces a non-typedef type, just use the old type.  */
1831       if (TREE_CODE (newdecl) == TYPE_DECL
1832           && newtype == DECL_ORIGINAL_TYPE (newdecl))
1833         newtype = oldtype;
1834
1835       if (TREE_CODE (newdecl) == VAR_DECL)
1836         {
1837           DECL_THIS_EXTERN (newdecl) |= DECL_THIS_EXTERN (olddecl);
1838           DECL_INITIALIZED_P (newdecl) |= DECL_INITIALIZED_P (olddecl);
1839           DECL_NONTRIVIALLY_INITIALIZED_P (newdecl)
1840             |= DECL_NONTRIVIALLY_INITIALIZED_P (olddecl);
1841           DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (newdecl)
1842             |= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (olddecl);
1843
1844           /* Merge the threadprivate attribute from OLDDECL into NEWDECL.  */
1845           if (DECL_LANG_SPECIFIC (olddecl)
1846               && CP_DECL_THREADPRIVATE_P (olddecl))
1847             {
1848               /* Allocate a LANG_SPECIFIC structure for NEWDECL, if needed.  */
1849               if (!DECL_LANG_SPECIFIC (newdecl))
1850                 retrofit_lang_decl (newdecl);
1851
1852               DECL_TLS_MODEL (newdecl) = DECL_TLS_MODEL (olddecl);
1853               CP_DECL_THREADPRIVATE_P (newdecl) = 1;
1854             }
1855         }
1856
1857       /* Do this after calling `merge_types' so that default
1858          parameters don't confuse us.  */
1859       else if (TREE_CODE (newdecl) == FUNCTION_DECL)
1860         check_redeclaration_exception_specification (newdecl, olddecl);
1861       TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = newtype;
1862
1863       if (TREE_CODE (newdecl) == FUNCTION_DECL)
1864         check_default_args (newdecl);
1865
1866       /* Lay the type out, unless already done.  */
1867       if (! same_type_p (newtype, oldtype)
1868           && TREE_TYPE (newdecl) != error_mark_node
1869           && !(processing_template_decl && uses_template_parms (newdecl)))
1870         layout_type (TREE_TYPE (newdecl));
1871
1872       if ((TREE_CODE (newdecl) == VAR_DECL
1873            || TREE_CODE (newdecl) == PARM_DECL
1874            || TREE_CODE (newdecl) == RESULT_DECL
1875            || TREE_CODE (newdecl) == FIELD_DECL
1876            || TREE_CODE (newdecl) == TYPE_DECL)
1877           && !(processing_template_decl && uses_template_parms (newdecl)))
1878         layout_decl (newdecl, 0);
1879
1880       /* Merge the type qualifiers.  */
1881       if (TREE_READONLY (newdecl))
1882         TREE_READONLY (olddecl) = 1;
1883       if (TREE_THIS_VOLATILE (newdecl))
1884         TREE_THIS_VOLATILE (olddecl) = 1;
1885       if (TREE_NOTHROW (newdecl))
1886         TREE_NOTHROW (olddecl) = 1;
1887
1888       /* Merge deprecatedness.  */
1889       if (TREE_DEPRECATED (newdecl))
1890         TREE_DEPRECATED (olddecl) = 1;
1891
1892       /* Preserve function specific target and optimization options */
1893       if (TREE_CODE (newdecl) == FUNCTION_DECL)
1894         {
1895           if (DECL_FUNCTION_SPECIFIC_TARGET (olddecl)
1896               && !DECL_FUNCTION_SPECIFIC_TARGET (newdecl))
1897             DECL_FUNCTION_SPECIFIC_TARGET (newdecl)
1898               = DECL_FUNCTION_SPECIFIC_TARGET (olddecl);
1899
1900           if (DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl)
1901               && !DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl))
1902             DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl)
1903               = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl);
1904         }
1905
1906       /* Merge the initialization information.  */
1907       if (DECL_INITIAL (newdecl) == NULL_TREE
1908           && DECL_INITIAL (olddecl) != NULL_TREE)
1909         {
1910           DECL_INITIAL (newdecl) = DECL_INITIAL (olddecl);
1911           DECL_SOURCE_LOCATION (newdecl) = DECL_SOURCE_LOCATION (olddecl);
1912           if (TREE_CODE (newdecl) == FUNCTION_DECL)
1913             {
1914               DECL_SAVED_TREE (newdecl) = DECL_SAVED_TREE (olddecl);
1915               DECL_STRUCT_FUNCTION (newdecl) = DECL_STRUCT_FUNCTION (olddecl);
1916             }
1917         }
1918
1919       /* Merge the section attribute.
1920          We want to issue an error if the sections conflict but that must be
1921          done later in decl_attributes since we are called before attributes
1922          are assigned.  */
1923       if (DECL_SECTION_NAME (newdecl) == NULL_TREE)
1924         DECL_SECTION_NAME (newdecl) = DECL_SECTION_NAME (olddecl);
1925
1926       if (TREE_CODE (newdecl) == FUNCTION_DECL)
1927         {
1928           DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (newdecl)
1929             |= DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (olddecl);
1930           DECL_NO_LIMIT_STACK (newdecl) |= DECL_NO_LIMIT_STACK (olddecl);
1931           TREE_THIS_VOLATILE (newdecl) |= TREE_THIS_VOLATILE (olddecl);
1932           TREE_NOTHROW (newdecl) |= TREE_NOTHROW (olddecl);
1933           DECL_IS_MALLOC (newdecl) |= DECL_IS_MALLOC (olddecl);
1934           DECL_IS_OPERATOR_NEW (newdecl) |= DECL_IS_OPERATOR_NEW (olddecl);
1935           DECL_PURE_P (newdecl) |= DECL_PURE_P (olddecl);
1936           TREE_READONLY (newdecl) |= TREE_READONLY (olddecl);
1937           DECL_LOOPING_CONST_OR_PURE_P (newdecl) 
1938             |= DECL_LOOPING_CONST_OR_PURE_P (olddecl);
1939           /* Keep the old RTL.  */
1940           COPY_DECL_RTL (olddecl, newdecl);
1941         }
1942       else if (TREE_CODE (newdecl) == VAR_DECL
1943                && (DECL_SIZE (olddecl) || !DECL_SIZE (newdecl)))
1944         {
1945           /* Keep the old RTL.  We cannot keep the old RTL if the old
1946              declaration was for an incomplete object and the new
1947              declaration is not since many attributes of the RTL will
1948              change.  */
1949           COPY_DECL_RTL (olddecl, newdecl);
1950         }
1951     }
1952   /* If cannot merge, then use the new type and qualifiers,
1953      and don't preserve the old rtl.  */
1954   else
1955     {
1956       /* Clean out any memory we had of the old declaration.  */
1957       tree oldstatic = value_member (olddecl, static_aggregates);
1958       if (oldstatic)
1959         TREE_VALUE (oldstatic) = error_mark_node;
1960
1961       TREE_TYPE (olddecl) = TREE_TYPE (newdecl);
1962       TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
1963       TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
1964       TREE_SIDE_EFFECTS (olddecl) = TREE_SIDE_EFFECTS (newdecl);
1965     }
1966
1967   /* Merge the storage class information.  */
1968   merge_weak (newdecl, olddecl);
1969
1970   if (DECL_ONE_ONLY (olddecl))
1971     DECL_COMDAT_GROUP (newdecl) = DECL_COMDAT_GROUP (olddecl);
1972
1973   DECL_DEFER_OUTPUT (newdecl) |= DECL_DEFER_OUTPUT (olddecl);
1974   TREE_PUBLIC (newdecl) = TREE_PUBLIC (olddecl);
1975   TREE_STATIC (olddecl) = TREE_STATIC (newdecl) |= TREE_STATIC (olddecl);
1976   if (! DECL_EXTERNAL (olddecl))
1977     DECL_EXTERNAL (newdecl) = 0;
1978
1979   new_template_info = NULL_TREE;
1980   if (DECL_LANG_SPECIFIC (newdecl) && DECL_LANG_SPECIFIC (olddecl))
1981     {
1982       bool new_redefines_gnu_inline = false;
1983
1984       if (new_defines_function
1985           && ((DECL_INTERFACE_KNOWN (olddecl)
1986                && TREE_CODE (olddecl) == FUNCTION_DECL)
1987               || (TREE_CODE (olddecl) == TEMPLATE_DECL
1988                   && (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl))
1989                       == FUNCTION_DECL))))
1990         {
1991           tree fn = olddecl;
1992
1993           if (TREE_CODE (fn) == TEMPLATE_DECL)
1994             fn = DECL_TEMPLATE_RESULT (olddecl);
1995
1996           new_redefines_gnu_inline = GNU_INLINE_P (fn) && DECL_INITIAL (fn);
1997         }
1998
1999       if (!new_redefines_gnu_inline)
2000         {
2001           DECL_INTERFACE_KNOWN (newdecl) |= DECL_INTERFACE_KNOWN (olddecl);
2002           DECL_NOT_REALLY_EXTERN (newdecl) |= DECL_NOT_REALLY_EXTERN (olddecl);
2003           DECL_COMDAT (newdecl) |= DECL_COMDAT (olddecl);
2004         }
2005       DECL_TEMPLATE_INSTANTIATED (newdecl)
2006         |= DECL_TEMPLATE_INSTANTIATED (olddecl);
2007       DECL_ODR_USED (newdecl) |= DECL_ODR_USED (olddecl);
2008
2009       /* If the OLDDECL is an instantiation and/or specialization,
2010          then the NEWDECL must be too.  But, it may not yet be marked
2011          as such if the caller has created NEWDECL, but has not yet
2012          figured out that it is a redeclaration.  */
2013       if (!DECL_USE_TEMPLATE (newdecl))
2014         DECL_USE_TEMPLATE (newdecl) = DECL_USE_TEMPLATE (olddecl);
2015
2016       /* Don't really know how much of the language-specific
2017          values we should copy from old to new.  */
2018       DECL_IN_AGGR_P (newdecl) = DECL_IN_AGGR_P (olddecl);
2019       DECL_REPO_AVAILABLE_P (newdecl) = DECL_REPO_AVAILABLE_P (olddecl);
2020       DECL_INITIALIZED_IN_CLASS_P (newdecl)
2021         |= DECL_INITIALIZED_IN_CLASS_P (olddecl);
2022
2023       if (LANG_DECL_HAS_MIN (newdecl))
2024         {
2025           DECL_LANG_SPECIFIC (newdecl)->u.min.u2 =
2026             DECL_LANG_SPECIFIC (olddecl)->u.min.u2;
2027           if (DECL_TEMPLATE_INFO (newdecl))
2028             new_template_info = DECL_TEMPLATE_INFO (newdecl);
2029           DECL_TEMPLATE_INFO (newdecl) = DECL_TEMPLATE_INFO (olddecl);
2030         }
2031       /* Only functions have these fields.  */
2032       if (TREE_CODE (newdecl) == FUNCTION_DECL
2033           || DECL_FUNCTION_TEMPLATE_P (newdecl))
2034         {
2035           DECL_NONCONVERTING_P (newdecl) = DECL_NONCONVERTING_P (olddecl);
2036           olddecl_friend = DECL_FRIEND_P (olddecl);
2037           hidden_friend = (DECL_ANTICIPATED (olddecl)
2038                            && DECL_HIDDEN_FRIEND_P (olddecl)
2039                            && newdecl_is_friend);
2040           DECL_BEFRIENDING_CLASSES (newdecl)
2041             = chainon (DECL_BEFRIENDING_CLASSES (newdecl),
2042                        DECL_BEFRIENDING_CLASSES (olddecl));
2043           /* DECL_THUNKS is only valid for virtual functions,
2044              otherwise it is a DECL_FRIEND_CONTEXT.  */
2045           if (DECL_VIRTUAL_P (newdecl))
2046             DECL_THUNKS (newdecl) = DECL_THUNKS (olddecl);
2047         }
2048       /* Only variables have this field.  */
2049       else if (TREE_CODE (newdecl) == VAR_DECL
2050                && VAR_HAD_UNKNOWN_BOUND (olddecl))
2051         SET_VAR_HAD_UNKNOWN_BOUND (newdecl);
2052     }
2053
2054   if (TREE_CODE (newdecl) == FUNCTION_DECL)
2055     {
2056       tree parm;
2057
2058       /* Merge parameter attributes. */
2059       tree oldarg, newarg;
2060       for (oldarg = DECL_ARGUMENTS(olddecl), 
2061                newarg = DECL_ARGUMENTS(newdecl);
2062            oldarg && newarg;
2063            oldarg = DECL_CHAIN(oldarg), newarg = DECL_CHAIN(newarg)) {
2064           DECL_ATTRIBUTES (newarg)
2065               = (*targetm.merge_decl_attributes) (oldarg, newarg);
2066           DECL_ATTRIBUTES (oldarg) = DECL_ATTRIBUTES (newarg);
2067       }
2068       
2069       if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2070           && !DECL_TEMPLATE_INSTANTIATION (newdecl))
2071         {
2072           /* If newdecl is not a specialization, then it is not a
2073              template-related function at all.  And that means that we
2074              should have exited above, returning 0.  */
2075           gcc_assert (DECL_TEMPLATE_SPECIALIZATION (newdecl));
2076
2077           if (DECL_ODR_USED (olddecl))
2078             /* From [temp.expl.spec]:
2079
2080                If a template, a member template or the member of a class
2081                template is explicitly specialized then that
2082                specialization shall be declared before the first use of
2083                that specialization that would cause an implicit
2084                instantiation to take place, in every translation unit in
2085                which such a use occurs.  */
2086             error ("explicit specialization of %qD after first use",
2087                       olddecl);
2088
2089           SET_DECL_TEMPLATE_SPECIALIZATION (olddecl);
2090
2091           /* Don't propagate visibility from the template to the
2092              specialization here.  We'll do that in determine_visibility if
2093              appropriate.  */
2094           DECL_VISIBILITY_SPECIFIED (olddecl) = 0;
2095
2096           /* [temp.expl.spec/14] We don't inline explicit specialization
2097              just because the primary template says so.  */
2098
2099           /* But still keep DECL_DISREGARD_INLINE_LIMITS in sync with
2100              the always_inline attribute.  */
2101           if (DECL_DISREGARD_INLINE_LIMITS (olddecl)
2102               && !DECL_DISREGARD_INLINE_LIMITS (newdecl))
2103             {
2104               if (DECL_DECLARED_INLINE_P (newdecl))
2105                 DECL_DISREGARD_INLINE_LIMITS (newdecl) = true;
2106               else
2107                 DECL_ATTRIBUTES (newdecl)
2108                   = remove_attribute ("always_inline",
2109                                       DECL_ATTRIBUTES (newdecl));
2110             }
2111         }
2112       else if (new_defines_function && DECL_INITIAL (olddecl))
2113         {
2114           /* Never inline re-defined extern inline functions.
2115              FIXME: this could be better handled by keeping both
2116              function as separate declarations.  */
2117           DECL_UNINLINABLE (newdecl) = 1;
2118         }
2119       else
2120         {
2121           if (DECL_PENDING_INLINE_INFO (newdecl) == 0)
2122             DECL_PENDING_INLINE_INFO (newdecl) = DECL_PENDING_INLINE_INFO (olddecl);
2123
2124           DECL_DECLARED_INLINE_P (newdecl) |= DECL_DECLARED_INLINE_P (olddecl);
2125
2126           DECL_UNINLINABLE (newdecl) = DECL_UNINLINABLE (olddecl)
2127             = (DECL_UNINLINABLE (newdecl) || DECL_UNINLINABLE (olddecl));
2128
2129           DECL_DISREGARD_INLINE_LIMITS (newdecl)
2130             = DECL_DISREGARD_INLINE_LIMITS (olddecl)
2131             = (DECL_DISREGARD_INLINE_LIMITS (newdecl)
2132                || DECL_DISREGARD_INLINE_LIMITS (olddecl));
2133         }
2134
2135       /* Preserve abstractness on cloned [cd]tors.  */
2136       DECL_ABSTRACT (newdecl) = DECL_ABSTRACT (olddecl);
2137
2138       /* Update newdecl's parms to point at olddecl.  */
2139       for (parm = DECL_ARGUMENTS (newdecl); parm;
2140            parm = DECL_CHAIN (parm))
2141         DECL_CONTEXT (parm) = olddecl;
2142
2143       if (! types_match)
2144         {
2145           SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
2146           COPY_DECL_ASSEMBLER_NAME (newdecl, olddecl);
2147           COPY_DECL_RTL (newdecl, olddecl);
2148         }
2149       if (! types_match || new_defines_function)
2150         {
2151           /* These need to be copied so that the names are available.
2152              Note that if the types do match, we'll preserve inline
2153              info and other bits, but if not, we won't.  */
2154           DECL_ARGUMENTS (olddecl) = DECL_ARGUMENTS (newdecl);
2155           DECL_RESULT (olddecl) = DECL_RESULT (newdecl);
2156         }
2157       if (new_defines_function)
2158         /* If defining a function declared with other language
2159            linkage, use the previously declared language linkage.  */
2160         SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
2161       else if (types_match)
2162         {
2163           /* If redeclaring a builtin function, and not a definition,
2164              it stays built in.  */
2165           if (DECL_BUILT_IN (olddecl))
2166             {
2167               DECL_BUILT_IN_CLASS (newdecl) = DECL_BUILT_IN_CLASS (olddecl);
2168               DECL_FUNCTION_CODE (newdecl) = DECL_FUNCTION_CODE (olddecl);
2169               /* If we're keeping the built-in definition, keep the rtl,
2170                  regardless of declaration matches.  */
2171               COPY_DECL_RTL (olddecl, newdecl);
2172               if (DECL_BUILT_IN_CLASS (newdecl) == BUILT_IN_NORMAL)
2173                 {
2174                   enum built_in_function fncode = DECL_FUNCTION_CODE (newdecl);
2175                   switch (fncode)
2176                     {
2177                       /* If a compatible prototype of these builtin functions
2178                          is seen, assume the runtime implements it with the
2179                          expected semantics.  */
2180                     case BUILT_IN_STPCPY:
2181                       if (builtin_decl_explicit_p (fncode))
2182                         set_builtin_decl_implicit_p (fncode, true);
2183                       break;
2184                     default:
2185                       break;
2186                     }
2187                 }
2188             }
2189
2190           DECL_RESULT (newdecl) = DECL_RESULT (olddecl);
2191           /* Don't clear out the arguments if we're just redeclaring a
2192              function.  */
2193           if (DECL_ARGUMENTS (olddecl))
2194             DECL_ARGUMENTS (newdecl) = DECL_ARGUMENTS (olddecl);
2195         }
2196     }
2197   else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
2198     NAMESPACE_LEVEL (newdecl) = NAMESPACE_LEVEL (olddecl);
2199
2200   /* Now preserve various other info from the definition.  */
2201   TREE_ADDRESSABLE (newdecl) = TREE_ADDRESSABLE (olddecl);
2202   TREE_ASM_WRITTEN (newdecl) = TREE_ASM_WRITTEN (olddecl);
2203   DECL_COMMON (newdecl) = DECL_COMMON (olddecl);
2204   COPY_DECL_ASSEMBLER_NAME (olddecl, newdecl);
2205
2206   /* Warn about conflicting visibility specifications.  */
2207   if (DECL_VISIBILITY_SPECIFIED (olddecl)
2208       && DECL_VISIBILITY_SPECIFIED (newdecl)
2209       && DECL_VISIBILITY (newdecl) != DECL_VISIBILITY (olddecl))
2210     {
2211       warning_at (input_location, OPT_Wattributes,
2212                   "%q+D: visibility attribute ignored because it", newdecl);
2213       warning_at (DECL_SOURCE_LOCATION (olddecl), OPT_Wattributes,
2214                   "conflicts with previous declaration here");
2215     }
2216   /* Choose the declaration which specified visibility.  */
2217   if (DECL_VISIBILITY_SPECIFIED (olddecl))
2218     {
2219       DECL_VISIBILITY (newdecl) = DECL_VISIBILITY (olddecl);
2220       DECL_VISIBILITY_SPECIFIED (newdecl) = 1;
2221     }
2222   /* Init priority used to be merged from newdecl to olddecl by the memcpy,
2223      so keep this behavior.  */
2224   if (TREE_CODE (newdecl) == VAR_DECL && DECL_HAS_INIT_PRIORITY_P (newdecl))
2225     {
2226       SET_DECL_INIT_PRIORITY (olddecl, DECL_INIT_PRIORITY (newdecl));
2227       DECL_HAS_INIT_PRIORITY_P (olddecl) = 1;
2228     }
2229   /* Likewise for DECL_ALIGN, DECL_USER_ALIGN and DECL_PACKED.  */
2230   if (DECL_ALIGN (olddecl) > DECL_ALIGN (newdecl))
2231     {
2232       DECL_ALIGN (newdecl) = DECL_ALIGN (olddecl);
2233       DECL_USER_ALIGN (newdecl) |= DECL_USER_ALIGN (olddecl);
2234     }
2235   DECL_USER_ALIGN (olddecl) = DECL_USER_ALIGN (newdecl);
2236   if (TREE_CODE (newdecl) == FIELD_DECL)
2237     DECL_PACKED (olddecl) = DECL_PACKED (newdecl);
2238
2239   /* The DECL_LANG_SPECIFIC information in OLDDECL will be replaced
2240      with that from NEWDECL below.  */
2241   if (DECL_LANG_SPECIFIC (olddecl))
2242     {
2243       gcc_assert (DECL_LANG_SPECIFIC (olddecl)
2244                   != DECL_LANG_SPECIFIC (newdecl));
2245       ggc_free (DECL_LANG_SPECIFIC (olddecl));
2246     }
2247
2248   /* Merge the USED information.  */
2249   if (TREE_USED (olddecl))
2250     TREE_USED (newdecl) = 1;
2251   else if (TREE_USED (newdecl))
2252     TREE_USED (olddecl) = 1;
2253   if (TREE_CODE (newdecl) == VAR_DECL)
2254     {
2255       if (DECL_READ_P (olddecl))
2256         DECL_READ_P (newdecl) = 1;
2257       else if (DECL_READ_P (newdecl))
2258         DECL_READ_P (olddecl) = 1;
2259     }
2260   if (DECL_PRESERVE_P (olddecl))
2261     DECL_PRESERVE_P (newdecl) = 1;
2262   else if (DECL_PRESERVE_P (newdecl))
2263     DECL_PRESERVE_P (olddecl) = 1;
2264
2265   if (TREE_CODE (newdecl) == FUNCTION_DECL)
2266     {
2267       int function_size;
2268
2269       function_size = sizeof (struct tree_decl_common);
2270
2271       memcpy ((char *) olddecl + sizeof (struct tree_common),
2272               (char *) newdecl + sizeof (struct tree_common),
2273               function_size - sizeof (struct tree_common));
2274
2275       memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2276               (char *) newdecl + sizeof (struct tree_decl_common),
2277               sizeof (struct tree_function_decl) - sizeof (struct tree_decl_common));
2278       if (new_template_info)
2279         /* If newdecl is a template instantiation, it is possible that
2280            the following sequence of events has occurred:
2281
2282            o A friend function was declared in a class template.  The
2283            class template was instantiated.
2284
2285            o The instantiation of the friend declaration was
2286            recorded on the instantiation list, and is newdecl.
2287
2288            o Later, however, instantiate_class_template called pushdecl
2289            on the newdecl to perform name injection.  But, pushdecl in
2290            turn called duplicate_decls when it discovered that another
2291            declaration of a global function with the same name already
2292            existed.
2293
2294            o Here, in duplicate_decls, we decided to clobber newdecl.
2295
2296            If we're going to do that, we'd better make sure that
2297            olddecl, and not newdecl, is on the list of
2298            instantiations so that if we try to do the instantiation
2299            again we won't get the clobbered declaration.  */
2300         reregister_specialization (newdecl,
2301                                    new_template_info,
2302                                    olddecl);
2303     }
2304   else
2305     {
2306       size_t size = tree_code_size (TREE_CODE (olddecl));
2307       memcpy ((char *) olddecl + sizeof (struct tree_common),
2308               (char *) newdecl + sizeof (struct tree_common),
2309               sizeof (struct tree_decl_common) - sizeof (struct tree_common));
2310       switch (TREE_CODE (olddecl))
2311         {
2312         case LABEL_DECL:
2313         case VAR_DECL:
2314         case RESULT_DECL:
2315         case PARM_DECL:
2316         case FIELD_DECL:
2317         case TYPE_DECL:
2318         case CONST_DECL:
2319           {
2320             memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2321                     (char *) newdecl + sizeof (struct tree_decl_common),
2322                     size - sizeof (struct tree_decl_common)
2323                     + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
2324           }
2325           break;
2326         default:
2327           memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2328                   (char *) newdecl + sizeof (struct tree_decl_common),
2329                   sizeof (struct tree_decl_non_common) - sizeof (struct tree_decl_common)
2330                   + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
2331           break;
2332         }
2333     }
2334   DECL_UID (olddecl) = olddecl_uid;
2335   if (olddecl_friend)
2336     DECL_FRIEND_P (olddecl) = 1;
2337   if (hidden_friend)
2338     {
2339       DECL_ANTICIPATED (olddecl) = 1;
2340       DECL_HIDDEN_FRIEND_P (olddecl) = 1;
2341     }
2342
2343   /* NEWDECL contains the merged attribute lists.
2344      Update OLDDECL to be the same.  */
2345   DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
2346
2347   /* If OLDDECL had its DECL_RTL instantiated, re-invoke make_decl_rtl
2348     so that encode_section_info has a chance to look at the new decl
2349     flags and attributes.  */
2350   if (DECL_RTL_SET_P (olddecl)
2351       && (TREE_CODE (olddecl) == FUNCTION_DECL
2352           || (TREE_CODE (olddecl) == VAR_DECL
2353               && TREE_STATIC (olddecl))))
2354     make_decl_rtl (olddecl);
2355
2356   /* The NEWDECL will no longer be needed.  Because every out-of-class
2357      declaration of a member results in a call to duplicate_decls,
2358      freeing these nodes represents in a significant savings.  */
2359   ggc_free (newdecl);
2360
2361   return olddecl;
2362 }
2363 \f
2364 /* Return zero if the declaration NEWDECL is valid
2365    when the declaration OLDDECL (assumed to be for the same name)
2366    has already been seen.
2367    Otherwise return an error message format string with a %s
2368    where the identifier should go.  */
2369
2370 static const char *
2371 redeclaration_error_message (tree newdecl, tree olddecl)
2372 {
2373   if (TREE_CODE (newdecl) == TYPE_DECL)
2374     {
2375       /* Because C++ can put things into name space for free,
2376          constructs like "typedef struct foo { ... } foo"
2377          would look like an erroneous redeclaration.  */
2378       if (same_type_p (TREE_TYPE (newdecl), TREE_TYPE (olddecl)))
2379         return NULL;
2380       else
2381         return G_("redefinition of %q#D");
2382     }
2383   else if (TREE_CODE (newdecl) == FUNCTION_DECL)
2384     {
2385       /* If this is a pure function, its olddecl will actually be
2386          the original initialization to `0' (which we force to call
2387          abort()).  Don't complain about redefinition in this case.  */
2388       if (DECL_LANG_SPECIFIC (olddecl) && DECL_PURE_VIRTUAL_P (olddecl)
2389           && DECL_INITIAL (olddecl) == NULL_TREE)
2390         return NULL;
2391
2392       /* If both functions come from different namespaces, this is not
2393          a redeclaration - this is a conflict with a used function.  */
2394       if (DECL_NAMESPACE_SCOPE_P (olddecl)
2395           && DECL_CONTEXT (olddecl) != DECL_CONTEXT (newdecl)
2396           && ! decls_match (olddecl, newdecl))
2397         return G_("%qD conflicts with used function");
2398
2399       /* We'll complain about linkage mismatches in
2400          warn_extern_redeclared_static.  */
2401
2402       /* Defining the same name twice is no good.  */
2403       if (DECL_INITIAL (olddecl) != NULL_TREE
2404           && DECL_INITIAL (newdecl) != NULL_TREE)
2405         {
2406           if (DECL_NAME (olddecl) == NULL_TREE)
2407             return G_("%q#D not declared in class");
2408           else if (!GNU_INLINE_P (olddecl)
2409                    || GNU_INLINE_P (newdecl))
2410             return G_("redefinition of %q#D");
2411         }
2412
2413       if (DECL_DECLARED_INLINE_P (olddecl) && DECL_DECLARED_INLINE_P (newdecl))
2414         {
2415           bool olda = GNU_INLINE_P (olddecl);
2416           bool newa = GNU_INLINE_P (newdecl);
2417
2418           if (olda != newa)
2419             {
2420               if (newa)
2421                 return G_("%q+D redeclared inline with "
2422                           "%<gnu_inline%> attribute");
2423               else
2424                 return G_("%q+D redeclared inline without "
2425                           "%<gnu_inline%> attribute");
2426             }
2427         }
2428
2429       return NULL;
2430     }
2431   else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
2432     {
2433       tree nt, ot;
2434
2435       if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == TYPE_DECL)
2436         {
2437           if (COMPLETE_TYPE_P (TREE_TYPE (newdecl))
2438               && COMPLETE_TYPE_P (TREE_TYPE (olddecl)))
2439             return G_("redefinition of %q#D");
2440           return NULL;
2441         }
2442
2443       if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) != FUNCTION_DECL
2444           || (DECL_TEMPLATE_RESULT (newdecl)
2445               == DECL_TEMPLATE_RESULT (olddecl)))
2446         return NULL;
2447
2448       nt = DECL_TEMPLATE_RESULT (newdecl);
2449       if (DECL_TEMPLATE_INFO (nt))
2450         nt = DECL_TEMPLATE_RESULT (template_for_substitution (nt));
2451       ot = DECL_TEMPLATE_RESULT (olddecl);
2452       if (DECL_TEMPLATE_INFO (ot))
2453         ot = DECL_TEMPLATE_RESULT (template_for_substitution (ot));
2454       if (DECL_INITIAL (nt) && DECL_INITIAL (ot)
2455           && (!GNU_INLINE_P (ot) || GNU_INLINE_P (nt)))
2456         return G_("redefinition of %q#D");
2457
2458       if (DECL_DECLARED_INLINE_P (ot) && DECL_DECLARED_INLINE_P (nt))
2459         {
2460           bool olda = GNU_INLINE_P (ot);
2461           bool newa = GNU_INLINE_P (nt);
2462
2463           if (olda != newa)
2464             {
2465               if (newa)
2466                 return G_("%q+D redeclared inline with "
2467                           "%<gnu_inline%> attribute");
2468               else
2469                 return G_("%q+D redeclared inline without "
2470                           "%<gnu_inline%> attribute");
2471             }
2472         }
2473
2474       /* Core issue #226 (C++0x): 
2475            
2476            If a friend function template declaration specifies a
2477            default template-argument, that declaration shall be a
2478            definition and shall be the only declaration of the
2479            function template in the translation unit.  */
2480       if ((cxx_dialect != cxx98) 
2481           && TREE_CODE (ot) == FUNCTION_DECL && DECL_FRIEND_P (ot)
2482           && !check_default_tmpl_args (nt, DECL_TEMPLATE_PARMS (newdecl), 
2483                                        /*is_primary=*/true,
2484                                        /*is_partial=*/false,
2485                                        /*is_friend_decl=*/2))
2486         return G_("redeclaration of friend %q#D "
2487                   "may not have default template arguments");
2488
2489       return NULL;
2490     }
2491   else if (TREE_CODE (newdecl) == VAR_DECL
2492            && DECL_THREAD_LOCAL_P (newdecl) != DECL_THREAD_LOCAL_P (olddecl)
2493            && (! DECL_LANG_SPECIFIC (olddecl)
2494                || ! CP_DECL_THREADPRIVATE_P (olddecl)
2495                || DECL_THREAD_LOCAL_P (newdecl)))
2496     {
2497       /* Only variables can be thread-local, and all declarations must
2498          agree on this property.  */
2499       if (DECL_THREAD_LOCAL_P (newdecl))
2500         return G_("thread-local declaration of %q#D follows "
2501                   "non-thread-local declaration");
2502       else
2503         return G_("non-thread-local declaration of %q#D follows "
2504                   "thread-local declaration");
2505     }
2506   else if (toplevel_bindings_p () || DECL_NAMESPACE_SCOPE_P (newdecl))
2507     {
2508       /* The objects have been declared at namespace scope.  If either
2509          is a member of an anonymous union, then this is an invalid
2510          redeclaration.  For example:
2511
2512            int i;
2513            union { int i; };
2514
2515            is invalid.  */
2516       if ((TREE_CODE (newdecl) == VAR_DECL && DECL_ANON_UNION_VAR_P (newdecl))
2517           || (TREE_CODE (olddecl) == VAR_DECL && DECL_ANON_UNION_VAR_P (olddecl)))
2518         return G_("redeclaration of %q#D");
2519       /* If at least one declaration is a reference, there is no
2520          conflict.  For example:
2521
2522            int i = 3;
2523            extern int i;
2524
2525          is valid.  */
2526       if (DECL_EXTERNAL (newdecl) || DECL_EXTERNAL (olddecl))
2527         return NULL;
2528       /* Reject two definitions.  */
2529       return G_("redefinition of %q#D");
2530     }
2531   else
2532     {
2533       /* Objects declared with block scope:  */
2534       /* Reject two definitions, and reject a definition
2535          together with an external reference.  */
2536       if (!(DECL_EXTERNAL (newdecl) && DECL_EXTERNAL (olddecl)))
2537         return G_("redeclaration of %q#D");
2538       return NULL;
2539     }
2540 }
2541 \f
2542 /* Hash and equality functions for the named_label table.  */
2543
2544 static hashval_t
2545 named_label_entry_hash (const void *data)
2546 {
2547   const struct named_label_entry *ent = (const struct named_label_entry *) data;
2548   return DECL_UID (ent->label_decl);
2549 }
2550
2551 static int
2552 named_label_entry_eq (const void *a, const void *b)
2553 {
2554   const struct named_label_entry *ent_a = (const struct named_label_entry *) a;
2555   const struct named_label_entry *ent_b = (const struct named_label_entry *) b;
2556   return ent_a->label_decl == ent_b->label_decl;
2557 }
2558
2559 /* Create a new label, named ID.  */
2560
2561 static tree
2562 make_label_decl (tree id, int local_p)
2563 {
2564   struct named_label_entry *ent;
2565   void **slot;
2566   tree decl;
2567
2568   decl = build_decl (input_location, LABEL_DECL, id, void_type_node);
2569
2570   DECL_CONTEXT (decl) = current_function_decl;
2571   DECL_MODE (decl) = VOIDmode;
2572   C_DECLARED_LABEL_FLAG (decl) = local_p;
2573
2574   /* Say where one reference is to the label, for the sake of the
2575      error if it is not defined.  */
2576   DECL_SOURCE_LOCATION (decl) = input_location;
2577
2578   /* Record the fact that this identifier is bound to this label.  */
2579   SET_IDENTIFIER_LABEL_VALUE (id, decl);
2580
2581   /* Create the label htab for the function on demand.  */
2582   if (!named_labels)
2583     named_labels = htab_create_ggc (13, named_label_entry_hash,
2584                                     named_label_entry_eq, NULL);
2585
2586   /* Record this label on the list of labels used in this function.
2587      We do this before calling make_label_decl so that we get the
2588      IDENTIFIER_LABEL_VALUE before the new label is declared.  */
2589   ent = ggc_alloc_cleared_named_label_entry ();
2590   ent->label_decl = decl;
2591
2592   slot = htab_find_slot (named_labels, ent, INSERT);
2593   gcc_assert (*slot == NULL);
2594   *slot = ent;
2595
2596   return decl;
2597 }
2598
2599 /* Look for a label named ID in the current function.  If one cannot
2600    be found, create one.  (We keep track of used, but undefined,
2601    labels, and complain about them at the end of a function.)  */
2602
2603 static tree
2604 lookup_label_1 (tree id)
2605 {
2606   tree decl;
2607
2608   /* You can't use labels at global scope.  */
2609   if (current_function_decl == NULL_TREE)
2610     {
2611       error ("label %qE referenced outside of any function", id);
2612       return NULL_TREE;
2613     }
2614
2615   /* See if we've already got this label.  */
2616   decl = IDENTIFIER_LABEL_VALUE (id);
2617   if (decl != NULL_TREE && DECL_CONTEXT (decl) == current_function_decl)
2618     return decl;
2619
2620   decl = make_label_decl (id, /*local_p=*/0);
2621   return decl;
2622 }
2623
2624 /* Wrapper for lookup_label_1.  */
2625
2626 tree
2627 lookup_label (tree id)
2628 {
2629   tree ret;
2630   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
2631   ret = lookup_label_1 (id);
2632   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
2633   return ret;
2634 }
2635
2636 /* Declare a local label named ID.  */
2637
2638 tree
2639 declare_local_label (tree id)
2640 {
2641   tree decl;
2642   cp_label_binding *bind;
2643
2644   /* Add a new entry to the SHADOWED_LABELS list so that when we leave
2645      this scope we can restore the old value of IDENTIFIER_TYPE_VALUE.  */
2646   bind = VEC_safe_push (cp_label_binding, gc,
2647                         current_binding_level->shadowed_labels, NULL);
2648   bind->prev_value = IDENTIFIER_LABEL_VALUE (id);
2649
2650   decl = make_label_decl (id, /*local_p=*/1);
2651   bind->label = decl;
2652
2653   return decl;
2654 }
2655
2656 /* Returns nonzero if it is ill-formed to jump past the declaration of
2657    DECL.  Returns 2 if it's also a real problem.  */
2658
2659 static int
2660 decl_jump_unsafe (tree decl)
2661 {
2662   /* [stmt.dcl]/3: A program that jumps from a point where a local variable
2663      with automatic storage duration is not in scope to a point where it is
2664      in scope is ill-formed unless the variable has scalar type, class type
2665      with a trivial default constructor and a trivial destructor, a
2666      cv-qualified version of one of these types, or an array of one of the
2667      preceding types and is declared without an initializer (8.5).  */
2668   tree type = TREE_TYPE (decl);
2669
2670   if (TREE_CODE (decl) != VAR_DECL || TREE_STATIC (decl)
2671       || type == error_mark_node)
2672     return 0;
2673
2674   type = strip_array_types (type);
2675
2676   if (type_has_nontrivial_default_init (TREE_TYPE (decl))
2677       || DECL_NONTRIVIALLY_INITIALIZED_P (decl))
2678     return 2;
2679
2680   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
2681     return 1;
2682
2683   return 0;
2684 }
2685
2686 /* A subroutine of check_previous_goto_1 to identify a branch to the user.  */
2687
2688 static void
2689 identify_goto (tree decl, const location_t *locus)
2690 {
2691   if (decl)
2692     permerror (input_location, "jump to label %qD", decl);
2693   else
2694     permerror (input_location, "jump to case label");
2695   if (locus)
2696     permerror (*locus, "  from here");
2697 }
2698
2699 /* Check that a single previously seen jump to a newly defined label
2700    is OK.  DECL is the LABEL_DECL or 0; LEVEL is the binding_level for
2701    the jump context; NAMES are the names in scope in LEVEL at the jump
2702    context; LOCUS is the source position of the jump or 0.  Returns
2703    true if all is well.  */
2704
2705 static bool
2706 check_previous_goto_1 (tree decl, cp_binding_level* level, tree names,
2707                        bool exited_omp, const location_t *locus)
2708 {
2709   cp_binding_level *b;
2710   bool identified = false, saw_eh = false, saw_omp = false;
2711
2712   if (exited_omp)
2713     {
2714       identify_goto (decl, locus);
2715       error ("  exits OpenMP structured block");
2716       identified = saw_omp = true;
2717     }
2718
2719   for (b = current_binding_level; b ; b = b->level_chain)
2720     {
2721       tree new_decls, old_decls = (b == level ? names : NULL_TREE);
2722
2723       for (new_decls = b->names; new_decls != old_decls;
2724            new_decls = (DECL_P (new_decls) ? DECL_CHAIN (new_decls)
2725                         : TREE_CHAIN (new_decls)))
2726         {
2727           int problem = decl_jump_unsafe (new_decls);
2728           if (! problem)
2729             continue;
2730
2731           if (!identified)
2732             {
2733               identify_goto (decl, locus);
2734               identified = true;
2735             }
2736           if (problem > 1)
2737             error ("  crosses initialization of %q+#D", new_decls);
2738           else
2739             permerror (input_location, "  enters scope of %q+#D which has "
2740                        "non-trivial destructor", new_decls);
2741         }
2742
2743       if (b == level)
2744         break;
2745       if ((b->kind == sk_try || b->kind == sk_catch) && !saw_eh)
2746         {
2747           if (!identified)
2748             {
2749               identify_goto (decl, locus);
2750               identified = true;
2751             }
2752           if (b->kind == sk_try)
2753             error ("  enters try block");
2754           else
2755             error ("  enters catch block");
2756           saw_eh = true;
2757         }
2758       if (b->kind == sk_omp && !saw_omp)
2759         {
2760           if (!identified)
2761             {
2762               identify_goto (decl, locus);
2763               identified = true;
2764             }
2765           error ("  enters OpenMP structured block");
2766           saw_omp = true;
2767         }
2768     }
2769
2770   return !identified;
2771 }
2772
2773 static void
2774 check_previous_goto (tree decl, struct named_label_use_entry *use)
2775 {
2776   check_previous_goto_1 (decl, use->binding_level,
2777                          use->names_in_scope, use->in_omp_scope,
2778                          &use->o_goto_locus);
2779 }
2780
2781 static bool
2782 check_switch_goto (cp_binding_level* level)
2783 {
2784   return check_previous_goto_1 (NULL_TREE, level, level->names, false, NULL);
2785 }
2786
2787 /* Check that a new jump to a label DECL is OK.  Called by
2788    finish_goto_stmt.  */
2789
2790 void
2791 check_goto (tree decl)
2792 {
2793   struct named_label_entry *ent, dummy;
2794   bool saw_catch = false, identified = false;
2795   tree bad;
2796   unsigned ix;
2797
2798   /* We can't know where a computed goto is jumping.
2799      So we assume that it's OK.  */
2800   if (TREE_CODE (decl) != LABEL_DECL)
2801     return;
2802
2803   /* We didn't record any information about this label when we created it,
2804      and there's not much point since it's trivial to analyze as a return.  */
2805   if (decl == cdtor_label)
2806     return;
2807
2808   dummy.label_decl = decl;
2809   ent = (struct named_label_entry *) htab_find (named_labels, &dummy);
2810   gcc_assert (ent != NULL);
2811
2812   /* If the label hasn't been defined yet, defer checking.  */
2813   if (! DECL_INITIAL (decl))
2814     {
2815       struct named_label_use_entry *new_use;
2816
2817       /* Don't bother creating another use if the last goto had the
2818          same data, and will therefore create the same set of errors.  */
2819       if (ent->uses
2820           && ent->uses->names_in_scope == current_binding_level->names)
2821         return;
2822
2823       new_use = ggc_alloc_named_label_use_entry ();
2824       new_use->binding_level = current_binding_level;
2825       new_use->names_in_scope = current_binding_level->names;
2826       new_use->o_goto_locus = input_location;
2827       new_use->in_omp_scope = false;
2828
2829       new_use->next = ent->uses;
2830       ent->uses = new_use;
2831       return;
2832     }
2833
2834   if (ent->in_try_scope || ent->in_catch_scope
2835       || ent->in_omp_scope || !VEC_empty (tree, ent->bad_decls))
2836     {
2837       permerror (input_location, "jump to label %q+D", decl);
2838       permerror (input_location, "  from here");
2839       identified = true;
2840     }
2841
2842   FOR_EACH_VEC_ELT (tree, ent->bad_decls, ix, bad)
2843     {
2844       int u = decl_jump_unsafe (bad);
2845
2846       if (u > 1 && DECL_ARTIFICIAL (bad))
2847         {
2848           /* Can't skip init of __exception_info.  */
2849           error_at (DECL_SOURCE_LOCATION (bad), "  enters catch block");
2850           saw_catch = true;
2851         }
2852       else if (u > 1)
2853         error ("  skips initialization of %q+#D", bad);
2854       else
2855         permerror (input_location, "  enters scope of %q+#D which has "
2856                    "non-trivial destructor", bad);
2857     }
2858
2859   if (ent->in_try_scope)
2860     error ("  enters try block");
2861   else if (ent->in_catch_scope && !saw_catch)
2862     error ("  enters catch block");
2863
2864   if (ent->in_omp_scope)
2865     error ("  enters OpenMP structured block");
2866   else if (flag_openmp)
2867     {
2868       cp_binding_level *b;
2869       for (b = current_binding_level; b ; b = b->level_chain)
2870         {
2871           if (b == ent->binding_level)
2872             break;
2873           if (b->kind == sk_omp)
2874             {
2875               if (!identified)
2876                 {
2877                   permerror (input_location, "jump to label %q+D", decl);
2878                   permerror (input_location, "  from here");
2879                   identified = true;
2880                 }
2881               error ("  exits OpenMP structured block");
2882               break;
2883             }
2884         }
2885     }
2886 }
2887
2888 /* Check that a return is ok wrt OpenMP structured blocks.
2889    Called by finish_return_stmt.  Returns true if all is well.  */
2890
2891 bool
2892 check_omp_return (void)
2893 {
2894   cp_binding_level *b;
2895   for (b = current_binding_level; b ; b = b->level_chain)
2896     if (b->kind == sk_omp)
2897       {
2898         error ("invalid exit from OpenMP structured block");
2899         return false;
2900       }
2901     else if (b->kind == sk_function_parms)
2902       break;
2903   return true;
2904 }
2905
2906 /* Define a label, specifying the location in the source file.
2907    Return the LABEL_DECL node for the label.  */
2908
2909 static tree
2910 define_label_1 (location_t location, tree name)
2911 {
2912   struct named_label_entry *ent, dummy;
2913   cp_binding_level *p;
2914   tree decl;
2915
2916   decl = lookup_label (name);
2917
2918   dummy.label_decl = decl;
2919   ent = (struct named_label_entry *) htab_find (named_labels, &dummy);
2920   gcc_assert (ent != NULL);
2921
2922   /* After labels, make any new cleanups in the function go into their
2923      own new (temporary) binding contour.  */
2924   for (p = current_binding_level;
2925        p->kind != sk_function_parms;
2926        p = p->level_chain)
2927     p->more_cleanups_ok = 0;
2928
2929   if (name == get_identifier ("wchar_t"))
2930     permerror (input_location, "label named wchar_t");
2931
2932   if (DECL_INITIAL (decl) != NULL_TREE)
2933     {
2934       error ("duplicate label %qD", decl);
2935       return error_mark_node;
2936     }
2937   else
2938     {
2939       struct named_label_use_entry *use;
2940
2941       /* Mark label as having been defined.  */
2942       DECL_INITIAL (decl) = error_mark_node;
2943       /* Say where in the source.  */
2944       DECL_SOURCE_LOCATION (decl) = location;
2945
2946       ent->binding_level = current_binding_level;
2947       ent->names_in_scope = current_binding_level->names;
2948
2949       for (use = ent->uses; use ; use = use->next)
2950         check_previous_goto (decl, use);
2951       ent->uses = NULL;
2952     }
2953
2954   return decl;
2955 }
2956
2957 /* Wrapper for define_label_1.  */
2958
2959 tree
2960 define_label (location_t location, tree name)
2961 {
2962   tree ret;
2963   bool running = timevar_cond_start (TV_NAME_LOOKUP);
2964   ret = define_label_1 (location, name);
2965   timevar_cond_stop (TV_NAME_LOOKUP, running);
2966   return ret;
2967 }
2968
2969
2970 struct cp_switch
2971 {
2972   cp_binding_level *level;
2973   struct cp_switch *next;
2974   /* The SWITCH_STMT being built.  */
2975   tree switch_stmt;
2976   /* A splay-tree mapping the low element of a case range to the high
2977      element, or NULL_TREE if there is no high element.  Used to
2978      determine whether or not a new case label duplicates an old case
2979      label.  We need a tree, rather than simply a hash table, because
2980      of the GNU case range extension.  */
2981   splay_tree cases;
2982 };
2983
2984 /* A stack of the currently active switch statements.  The innermost
2985    switch statement is on the top of the stack.  There is no need to
2986    mark the stack for garbage collection because it is only active
2987    during the processing of the body of a function, and we never
2988    collect at that point.  */
2989
2990 static struct cp_switch *switch_stack;
2991
2992 /* Called right after a switch-statement condition is parsed.
2993    SWITCH_STMT is the switch statement being parsed.  */
2994
2995 void
2996 push_switch (tree switch_stmt)
2997 {
2998   struct cp_switch *p = XNEW (struct cp_switch);
2999   p->level = current_binding_level;
3000   p->next = switch_stack;
3001   p->switch_stmt = switch_stmt;
3002   p->cases = splay_tree_new (case_compare, NULL, NULL);
3003   switch_stack = p;
3004 }
3005
3006 void
3007 pop_switch (void)
3008 {
3009   struct cp_switch *cs = switch_stack;
3010   location_t switch_location;
3011
3012   /* Emit warnings as needed.  */
3013   switch_location = EXPR_LOC_OR_HERE (cs->switch_stmt);
3014   if (!processing_template_decl)
3015     c_do_switch_warnings (cs->cases, switch_location,
3016                           SWITCH_STMT_TYPE (cs->switch_stmt),
3017                           SWITCH_STMT_COND (cs->switch_stmt));
3018
3019   splay_tree_delete (cs->cases);
3020   switch_stack = switch_stack->next;
3021   free (cs);
3022 }
3023
3024 /* Convert a case constant VALUE in a switch to the type TYPE of the switch
3025    condition.  Note that if TYPE and VALUE are already integral we don't
3026    really do the conversion because the language-independent
3027    warning/optimization code will work better that way.  */
3028
3029 static tree
3030 case_conversion (tree type, tree value)
3031 {
3032   if (value == NULL_TREE)
3033     return value;
3034
3035   if (cxx_dialect >= cxx0x
3036       && (SCOPED_ENUM_P (type)
3037           || !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (value))))
3038     {
3039       if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3040         type = type_promotes_to (type);
3041       value = perform_implicit_conversion (type, value, tf_warning_or_error);
3042     }
3043   return cxx_constant_value (value);
3044 }
3045
3046 /* Note that we've seen a definition of a case label, and complain if this
3047    is a bad place for one.  */
3048
3049 tree
3050 finish_case_label (location_t loc, tree low_value, tree high_value)
3051 {
3052   tree cond, r;
3053   cp_binding_level *p;
3054   tree type;
3055
3056   if (processing_template_decl)
3057     {
3058       tree label;
3059
3060       /* For templates, just add the case label; we'll do semantic
3061          analysis at instantiation-time.  */
3062       label = build_decl (loc, LABEL_DECL, NULL_TREE, NULL_TREE);
3063       return add_stmt (build_case_label (low_value, high_value, label));
3064     }
3065
3066   /* Find the condition on which this switch statement depends.  */
3067   cond = SWITCH_STMT_COND (switch_stack->switch_stmt);
3068   if (cond && TREE_CODE (cond) == TREE_LIST)
3069     cond = TREE_VALUE (cond);
3070
3071   if (!check_switch_goto (switch_stack->level))
3072     return error_mark_node;
3073
3074   type = SWITCH_STMT_TYPE (switch_stack->switch_stmt);
3075
3076   low_value = case_conversion (type, low_value);
3077   high_value = case_conversion (type, high_value);
3078
3079   r = c_add_case_label (loc, switch_stack->cases, cond, type,
3080                         low_value, high_value);
3081
3082   /* After labels, make any new cleanups in the function go into their
3083      own new (temporary) binding contour.  */
3084   for (p = current_binding_level;
3085        p->kind != sk_function_parms;
3086        p = p->level_chain)
3087     p->more_cleanups_ok = 0;
3088
3089   return r;
3090 }
3091 \f
3092 /* Hash a TYPENAME_TYPE.  K is really of type `tree'.  */
3093
3094 static hashval_t
3095 typename_hash (const void* k)
3096 {
3097   hashval_t hash;
3098   const_tree const t = (const_tree) k;
3099
3100   hash = (htab_hash_pointer (TYPE_CONTEXT (t))
3101           ^ htab_hash_pointer (DECL_NAME (TYPE_NAME (t))));
3102
3103   return hash;
3104 }
3105
3106 typedef struct typename_info {
3107   tree scope;
3108   tree name;
3109   tree template_id;
3110   bool enum_p;
3111   bool class_p;
3112 } typename_info;
3113
3114 /* Compare two TYPENAME_TYPEs.  K1 is really of type `tree', K2 is
3115    really of type `typename_info*'  */
3116
3117 static int
3118 typename_compare (const void * k1, const void * k2)
3119 {
3120   const_tree const t1 = (const_tree) k1;
3121   const typename_info *const t2 = (const typename_info *) k2;
3122
3123   return (DECL_NAME (TYPE_NAME (t1)) == t2->name
3124           && TYPE_CONTEXT (t1) == t2->scope
3125           && TYPENAME_TYPE_FULLNAME (t1) == t2->template_id
3126           && TYPENAME_IS_ENUM_P (t1) == t2->enum_p
3127           && TYPENAME_IS_CLASS_P (t1) == t2->class_p);
3128 }
3129
3130 /* Build a TYPENAME_TYPE.  If the type is `typename T::t', CONTEXT is
3131    the type of `T', NAME is the IDENTIFIER_NODE for `t'.
3132
3133    Returns the new TYPENAME_TYPE.  */
3134
3135 static GTY ((param_is (union tree_node))) htab_t typename_htab;
3136
3137 static tree
3138 build_typename_type (tree context, tree name, tree fullname,
3139                      enum tag_types tag_type)
3140 {
3141   tree t;
3142   tree d;
3143   typename_info ti;
3144   void **e;
3145   hashval_t hash;
3146
3147   if (typename_htab == NULL)
3148     typename_htab = htab_create_ggc (61, &typename_hash,
3149                                      &typename_compare, NULL);
3150
3151   ti.scope = FROB_CONTEXT (context);
3152   ti.name = name;
3153   ti.template_id = fullname;
3154   ti.enum_p = tag_type == enum_type;
3155   ti.class_p = (tag_type == class_type
3156                 || tag_type == record_type
3157                 || tag_type == union_type);
3158   hash =  (htab_hash_pointer (ti.scope)
3159            ^ htab_hash_pointer (ti.name));
3160
3161   /* See if we already have this type.  */
3162   e = htab_find_slot_with_hash (typename_htab, &ti, hash, INSERT);
3163   if (*e)
3164     t = (tree) *e;
3165   else
3166     {
3167       /* Build the TYPENAME_TYPE.  */
3168       t = cxx_make_type (TYPENAME_TYPE);
3169       TYPE_CONTEXT (t) = ti.scope;
3170       TYPENAME_TYPE_FULLNAME (t) = ti.template_id;
3171       TYPENAME_IS_ENUM_P (t) = ti.enum_p;
3172       TYPENAME_IS_CLASS_P (t) = ti.class_p;
3173
3174       /* Build the corresponding TYPE_DECL.  */
3175       d = build_decl (input_location, TYPE_DECL, name, t);
3176       TYPE_NAME (TREE_TYPE (d)) = d;
3177       TYPE_STUB_DECL (TREE_TYPE (d)) = d;
3178       DECL_CONTEXT (d) = FROB_CONTEXT (context);
3179       DECL_ARTIFICIAL (d) = 1;
3180
3181       /* Store it in the hash table.  */
3182       *e = t;
3183
3184       /* TYPENAME_TYPEs must always be compared structurally, because
3185          they may or may not resolve down to another type depending on
3186          the currently open classes. */
3187       SET_TYPE_STRUCTURAL_EQUALITY (t);
3188     }
3189
3190   return t;
3191 }
3192
3193 /* Resolve `typename CONTEXT::NAME'.  TAG_TYPE indicates the tag
3194    provided to name the type.  Returns an appropriate type, unless an
3195    error occurs, in which case error_mark_node is returned.  If we
3196    locate a non-artificial TYPE_DECL and TF_KEEP_TYPE_DECL is set, we
3197    return that, rather than the _TYPE it corresponds to, in other
3198    cases we look through the type decl.  If TF_ERROR is set, complain
3199    about errors, otherwise be quiet.  */
3200
3201 tree
3202 make_typename_type (tree context, tree name, enum tag_types tag_type,
3203                     tsubst_flags_t complain)
3204 {
3205   tree fullname;
3206   tree t;
3207   bool want_template;
3208
3209   if (name == error_mark_node
3210       || context == NULL_TREE
3211       || context == error_mark_node)
3212     return error_mark_node;
3213
3214   if (TYPE_P (name))
3215     {
3216       if (!(TYPE_LANG_SPECIFIC (name)
3217             && (CLASSTYPE_IS_TEMPLATE (name)
3218                 || CLASSTYPE_USE_TEMPLATE (name))))
3219         name = TYPE_IDENTIFIER (name);
3220       else
3221         /* Create a TEMPLATE_ID_EXPR for the type.  */
3222         name = build_nt (TEMPLATE_ID_EXPR,
3223                          CLASSTYPE_TI_TEMPLATE (name),
3224                          CLASSTYPE_TI_ARGS (name));
3225     }
3226   else if (TREE_CODE (name) == TYPE_DECL)
3227     name = DECL_NAME (name);
3228
3229   fullname = name;
3230
3231   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
3232     {
3233       name = TREE_OPERAND (name, 0);
3234       if (TREE_CODE (name) == TEMPLATE_DECL)
3235         name = TREE_OPERAND (fullname, 0) = DECL_NAME (name);
3236       else if (TREE_CODE (name) == OVERLOAD)
3237         {
3238           error ("%qD is not a type", name);
3239           return error_mark_node;
3240         }
3241     }
3242   if (TREE_CODE (name) == TEMPLATE_DECL)
3243     {
3244       error ("%qD used without template parameters", name);
3245       return error_mark_node;
3246     }
3247   gcc_assert (TREE_CODE (name) == IDENTIFIER_NODE);
3248   gcc_assert (TYPE_P (context));
3249
3250   if (!MAYBE_CLASS_TYPE_P (context))
3251     {
3252       if (complain & tf_error)
3253         error ("%q#T is not a class", context);
3254       return error_mark_node;
3255     }
3256   
3257   /* When the CONTEXT is a dependent type,  NAME could refer to a
3258      dependent base class of CONTEXT.  But look inside it anyway
3259      if CONTEXT is a currently open scope, in case it refers to a
3260      member of the current instantiation or a non-dependent base;
3261      lookup will stop when we hit a dependent base.  */
3262   if (!dependent_scope_p (context))
3263     /* We should only set WANT_TYPE when we're a nested typename type.
3264        Then we can give better diagnostics if we find a non-type.  */
3265     t = lookup_field (context, name, 2, /*want_type=*/true);
3266   else
3267     t = NULL_TREE;
3268
3269   if ((!t || TREE_CODE (t) == TREE_LIST) && dependent_type_p (context))
3270     return build_typename_type (context, name, fullname, tag_type);
3271
3272   want_template = TREE_CODE (fullname) == TEMPLATE_ID_EXPR;
3273   
3274   if (!t)
3275     {
3276       if (complain & tf_error)
3277         error (want_template ? G_("no class template named %q#T in %q#T")
3278                : G_("no type named %q#T in %q#T"), name, context);
3279       return error_mark_node;
3280     }
3281   
3282   /* Pull out the template from an injected-class-name (or multiple).  */
3283   if (want_template)
3284     t = maybe_get_template_decl_from_type_decl (t);
3285
3286   if (TREE_CODE (t) == TREE_LIST)
3287     {
3288       if (complain & tf_error)
3289         {
3290           error ("lookup of %qT in %qT is ambiguous", name, context);
3291           print_candidates (t);
3292         }
3293       return error_mark_node;
3294     }
3295
3296   if (want_template && !DECL_TYPE_TEMPLATE_P (t))
3297     {
3298       if (complain & tf_error)
3299         error ("%<typename %T::%D%> names %q#T, which is not a class template",
3300                context, name, t);
3301       return error_mark_node;
3302     }
3303   if (!want_template && TREE_CODE (t) != TYPE_DECL)
3304     {
3305       if (complain & tf_error)
3306         error ("%<typename %T::%D%> names %q#T, which is not a type",
3307                context, name, t);
3308       return error_mark_node;
3309     }
3310
3311   if (!perform_or_defer_access_check (TYPE_BINFO (context), t, t, complain))
3312     return error_mark_node;
3313
3314   /* If we are currently parsing a template and if T is a typedef accessed
3315      through CONTEXT then we need to remember and check access of T at
3316      template instantiation time.  */
3317   add_typedef_to_current_template_for_access_check (t, context, input_location);
3318
3319   if (want_template)
3320     return lookup_template_class (t, TREE_OPERAND (fullname, 1),
3321                                   NULL_TREE, context,
3322                                   /*entering_scope=*/0,
3323                                   tf_warning_or_error | tf_user);
3324   
3325   if (DECL_ARTIFICIAL (t) || !(complain & tf_keep_type_decl))
3326     t = TREE_TYPE (t);
3327   
3328   return t;
3329 }
3330
3331 /* Resolve `CONTEXT::template NAME'.  Returns a TEMPLATE_DECL if the name
3332    can be resolved or an UNBOUND_CLASS_TEMPLATE, unless an error occurs,
3333    in which case error_mark_node is returned.
3334
3335    If PARM_LIST is non-NULL, also make sure that the template parameter
3336    list of TEMPLATE_DECL matches.
3337
3338    If COMPLAIN zero, don't complain about any errors that occur.  */
3339
3340 tree
3341 make_unbound_class_template (tree context, tree name, tree parm_list,
3342                              tsubst_flags_t complain)
3343 {
3344   tree t;
3345   tree d;
3346
3347   if (TYPE_P (name))
3348     name = TYPE_IDENTIFIER (name);
3349   else if (DECL_P (name))
3350     name = DECL_NAME (name);
3351   gcc_assert (TREE_CODE (name) == IDENTIFIER_NODE);
3352
3353   if (!dependent_type_p (context)
3354       || currently_open_class (context))
3355     {
3356       tree tmpl = NULL_TREE;
3357
3358       if (MAYBE_CLASS_TYPE_P (context))
3359         tmpl = lookup_field (context, name, 0, false);
3360
3361       if (tmpl && TREE_CODE (tmpl) == TYPE_DECL)
3362         tmpl = maybe_get_template_decl_from_type_decl (tmpl);
3363
3364       if (!tmpl || !DECL_TYPE_TEMPLATE_P (tmpl))
3365         {
3366           if (complain & tf_error)
3367             error ("no class template named %q#T in %q#T", name, context);
3368           return error_mark_node;
3369         }
3370
3371       if (parm_list
3372           && !comp_template_parms (DECL_TEMPLATE_PARMS (tmpl), parm_list))
3373         {
3374           if (complain & tf_error)
3375             {
3376               error ("template parameters do not match template");
3377               error ("%q+D declared here", tmpl);
3378             }
3379           return error_mark_node;
3380         }
3381
3382       if (!perform_or_defer_access_check (TYPE_BINFO (context), tmpl, tmpl,
3383                                           complain))
3384         return error_mark_node;
3385
3386       return tmpl;
3387     }
3388
3389   /* Build the UNBOUND_CLASS_TEMPLATE.  */
3390   t = cxx_make_type (UNBOUND_CLASS_TEMPLATE);
3391   TYPE_CONTEXT (t) = FROB_CONTEXT (context);
3392   TREE_TYPE (t) = NULL_TREE;
3393   SET_TYPE_STRUCTURAL_EQUALITY (t);
3394
3395   /* Build the corresponding TEMPLATE_DECL.  */
3396   d = build_decl (input_location, TEMPLATE_DECL, name, t);
3397   TYPE_NAME (TREE_TYPE (d)) = d;
3398   TYPE_STUB_DECL (TREE_TYPE (d)) = d;
3399   DECL_CONTEXT (d) = FROB_CONTEXT (context);
3400   DECL_ARTIFICIAL (d) = 1;
3401   DECL_TEMPLATE_PARMS (d) = parm_list;
3402
3403   return t;
3404 }
3405
3406 \f
3407
3408 /* Push the declarations of builtin types into the namespace.
3409    RID_INDEX is the index of the builtin type in the array
3410    RID_POINTERS.  NAME is the name used when looking up the builtin
3411    type.  TYPE is the _TYPE node for the builtin type.  */
3412
3413 void
3414 record_builtin_type (enum rid rid_index,
3415                      const char* name,
3416                      tree type)
3417 {
3418   tree rname = NULL_TREE, tname = NULL_TREE;
3419   tree tdecl = NULL_TREE;
3420
3421   if ((int) rid_index < (int) RID_MAX)
3422     rname = ridpointers[(int) rid_index];
3423   if (name)
3424     tname = get_identifier (name);
3425
3426   /* The calls to SET_IDENTIFIER_GLOBAL_VALUE below should be
3427      eliminated.  Built-in types should not be looked up name; their
3428      names are keywords that the parser can recognize.  However, there
3429      is code in c-common.c that uses identifier_global_value to look
3430      up built-in types by name.  */
3431   if (tname)
3432     {
3433       tdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, tname, type);
3434       DECL_ARTIFICIAL (tdecl) = 1;
3435       SET_IDENTIFIER_GLOBAL_VALUE (tname, tdecl);
3436     }
3437   if (rname)
3438     {
3439       if (!tdecl)
3440         {
3441           tdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, rname, type);
3442           DECL_ARTIFICIAL (tdecl) = 1;
3443         }
3444       SET_IDENTIFIER_GLOBAL_VALUE (rname, tdecl);
3445     }
3446
3447   if (!TYPE_NAME (type))
3448     TYPE_NAME (type) = tdecl;
3449
3450   if (tdecl)
3451     debug_hooks->type_decl (tdecl, 0);
3452 }
3453
3454 /* Record one of the standard Java types.
3455  * Declare it as having the given NAME.
3456  * If SIZE > 0, it is the size of one of the integral types;
3457  * otherwise it is the negative of the size of one of the other types.  */
3458
3459 static tree
3460 record_builtin_java_type (const char* name, int size)
3461 {
3462   tree type, decl;
3463   if (size > 0)
3464     {
3465       type = build_nonstandard_integer_type (size, 0);
3466       type = build_distinct_type_copy (type);
3467     }
3468   else if (size > -32)
3469     {
3470       tree stype;
3471       /* "__java_char" or ""__java_boolean".  */
3472       type = build_nonstandard_integer_type (-size, 1);
3473       type = build_distinct_type_copy (type);
3474       /* Get the signed type cached and attached to the unsigned type,
3475          so it doesn't get garbage-collected at "random" times,
3476          causing potential codegen differences out of different UIDs
3477          and different alias set numbers.  */
3478       stype = build_nonstandard_integer_type (-size, 0);
3479       stype = build_distinct_type_copy (stype);
3480       TREE_CHAIN (type) = stype;
3481       /*if (size == -1) TREE_SET_CODE (type, BOOLEAN_TYPE);*/
3482     }
3483   else
3484     { /* "__java_float" or ""__java_double".  */
3485       type = make_node (REAL_TYPE);
3486       TYPE_PRECISION (type) = - size;
3487       layout_type (type);
3488     }
3489   record_builtin_type (RID_MAX, name, type);
3490   decl = TYPE_NAME (type);
3491
3492   /* Suppress generate debug symbol entries for these types,
3493      since for normal C++ they are just clutter.
3494      However, push_lang_context undoes this if extern "Java" is seen.  */
3495   DECL_IGNORED_P (decl) = 1;
3496
3497   TYPE_FOR_JAVA (type) = 1;
3498   return type;
3499 }
3500
3501 /* Push a type into the namespace so that the back ends ignore it.  */
3502
3503 static void
3504 record_unknown_type (tree type, const char* name)
3505 {
3506   tree decl = pushdecl (build_decl (UNKNOWN_LOCATION,
3507                                     TYPE_DECL, get_identifier (name), type));
3508   /* Make sure the "unknown type" typedecl gets ignored for debug info.  */
3509   DECL_IGNORED_P (decl) = 1;
3510   TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
3511   TYPE_SIZE (type) = TYPE_SIZE (void_type_node);
3512   TYPE_ALIGN (type) = 1;
3513   TYPE_USER_ALIGN (type) = 0;
3514   SET_TYPE_MODE (type, TYPE_MODE (void_type_node));
3515 }
3516
3517 /* A string for which we should create an IDENTIFIER_NODE at
3518    startup.  */
3519
3520 typedef struct predefined_identifier
3521 {
3522   /* The name of the identifier.  */
3523   const char *const name;
3524   /* The place where the IDENTIFIER_NODE should be stored.  */
3525   tree *const node;
3526   /* Nonzero if this is the name of a constructor or destructor.  */
3527   const int ctor_or_dtor_p;
3528 } predefined_identifier;
3529
3530 /* Create all the predefined identifiers.  */
3531
3532 static void
3533 initialize_predefined_identifiers (void)
3534 {
3535   const predefined_identifier *pid;
3536
3537   /* A table of identifiers to create at startup.  */
3538   static const predefined_identifier predefined_identifiers[] = {
3539     { "C++", &lang_name_cplusplus, 0 },
3540     { "C", &lang_name_c, 0 },
3541     { "Java", &lang_name_java, 0 },
3542     /* Some of these names have a trailing space so that it is
3543        impossible for them to conflict with names written by users.  */
3544     { "__ct ", &ctor_identifier, 1 },
3545     { "__base_ctor ", &base_ctor_identifier, 1 },
3546     { "__comp_ctor ", &complete_ctor_identifier, 1 },
3547     { "__dt ", &dtor_identifier, 1 },
3548     { "__comp_dtor ", &complete_dtor_identifier, 1 },
3549     { "__base_dtor ", &base_dtor_identifier, 1 },
3550     { "__deleting_dtor ", &deleting_dtor_identifier, 1 },
3551     { IN_CHARGE_NAME, &in_charge_identifier, 0 },
3552     { "nelts", &nelts_identifier, 0 },
3553     { THIS_NAME, &this_identifier, 0 },
3554     { VTABLE_DELTA_NAME, &delta_identifier, 0 },
3555     { VTABLE_PFN_NAME, &pfn_identifier, 0 },
3556     { "_vptr", &vptr_identifier, 0 },
3557     { "__vtt_parm", &vtt_parm_identifier, 0 },
3558     { "::", &global_scope_name, 0 },
3559     { "std", &std_identifier, 0 },
3560     { NULL, NULL, 0 }
3561   };
3562
3563   for (pid = predefined_identifiers; pid->name; ++pid)
3564     {
3565       *pid->node = get_identifier (pid->name);
3566       if (pid->ctor_or_dtor_p)
3567         IDENTIFIER_CTOR_OR_DTOR_P (*pid->node) = 1;
3568     }
3569 }
3570
3571 /* Create the predefined scalar types of C,
3572    and some nodes representing standard constants (0, 1, (void *)0).
3573    Initialize the global binding level.
3574    Make definitions for built-in primitive functions.  */
3575
3576 void
3577 cxx_init_decl_processing (void)
3578 {
3579   tree void_ftype;
3580   tree void_ftype_ptr;
3581
3582   /* Create all the identifiers we need.  */
3583   initialize_predefined_identifiers ();
3584
3585   /* Create the global variables.  */
3586   push_to_top_level ();
3587
3588   current_function_decl = NULL_TREE;
3589   current_binding_level = NULL;
3590   /* Enter the global namespace.  */
3591   gcc_assert (global_namespace == NULL_TREE);
3592   global_namespace = build_lang_decl (NAMESPACE_DECL, global_scope_name,
3593                                       void_type_node);
3594   DECL_CONTEXT (global_namespace) = build_translation_unit_decl (NULL_TREE);
3595   TREE_PUBLIC (global_namespace) = 1;
3596   begin_scope (sk_namespace, global_namespace);
3597
3598   if (flag_visibility_ms_compat)
3599     default_visibility = VISIBILITY_HIDDEN;
3600
3601   /* Initially, C.  */
3602   current_lang_name = lang_name_c;
3603
3604   /* Create the `std' namespace.  */
3605   push_namespace (std_identifier);
3606   std_node = current_namespace;
3607   pop_namespace ();
3608
3609   c_common_nodes_and_builtins ();
3610
3611   java_byte_type_node = record_builtin_java_type ("__java_byte", 8);
3612   java_short_type_node = record_builtin_java_type ("__java_short", 16);
3613   java_int_type_node = record_builtin_java_type ("__java_int", 32);
3614   java_long_type_node = record_builtin_java_type ("__java_long", 64);
3615   java_float_type_node = record_builtin_java_type ("__java_float", -32);
3616   java_double_type_node = record_builtin_java_type ("__java_double", -64);
3617   java_char_type_node = record_builtin_java_type ("__java_char", -16);
3618   java_boolean_type_node = record_builtin_java_type ("__java_boolean", -1);
3619
3620   integer_two_node = build_int_cst (NULL_TREE, 2);
3621
3622   record_builtin_type (RID_BOOL, "bool", boolean_type_node);
3623   truthvalue_type_node = boolean_type_node;
3624   truthvalue_false_node = boolean_false_node;
3625   truthvalue_true_node = boolean_true_node;
3626
3627   empty_except_spec = build_tree_list (NULL_TREE, NULL_TREE);
3628   noexcept_true_spec = build_tree_list (boolean_true_node, NULL_TREE);
3629   noexcept_false_spec = build_tree_list (boolean_false_node, NULL_TREE);
3630
3631 #if 0
3632   record_builtin_type (RID_MAX, NULL, string_type_node);
3633 #endif
3634
3635   delta_type_node = ptrdiff_type_node;
3636   vtable_index_type = ptrdiff_type_node;
3637
3638   vtt_parm_type = build_pointer_type (const_ptr_type_node);
3639   void_ftype = build_function_type_list (void_type_node, NULL_TREE);
3640   void_ftype_ptr = build_function_type_list (void_type_node,
3641                                              ptr_type_node, NULL_TREE);
3642   void_ftype_ptr
3643     = build_exception_variant (void_ftype_ptr, empty_except_spec);
3644
3645   /* C++ extensions */
3646
3647   unknown_type_node = make_node (LANG_TYPE);
3648   record_unknown_type (unknown_type_node, "unknown type");
3649
3650   /* Indirecting an UNKNOWN_TYPE node yields an UNKNOWN_TYPE node.  */
3651   TREE_TYPE (unknown_type_node) = unknown_type_node;
3652
3653   /* Looking up TYPE_POINTER_TO and TYPE_REFERENCE_TO yield the same
3654      result.  */
3655   TYPE_POINTER_TO (unknown_type_node) = unknown_type_node;
3656   TYPE_REFERENCE_TO (unknown_type_node) = unknown_type_node;
3657
3658   init_list_type_node = make_node (LANG_TYPE);
3659   record_unknown_type (init_list_type_node, "init list");
3660
3661   {
3662     /* Make sure we get a unique function type, so we can give
3663        its pointer type a name.  (This wins for gdb.) */
3664     tree vfunc_type = make_node (FUNCTION_TYPE);
3665     TREE_TYPE (vfunc_type) = integer_type_node;
3666     TYPE_ARG_TYPES (vfunc_type) = NULL_TREE;
3667     layout_type (vfunc_type);
3668
3669     vtable_entry_type = build_pointer_type (vfunc_type);
3670   }
3671   record_builtin_type (RID_MAX, VTBL_PTR_TYPE, vtable_entry_type);
3672
3673   vtbl_type_node
3674     = build_cplus_array_type (vtable_entry_type, NULL_TREE);
3675   layout_type (vtbl_type_node);
3676   vtbl_type_node = cp_build_qualified_type (vtbl_type_node, TYPE_QUAL_CONST);
3677   record_builtin_type (RID_MAX, NULL, vtbl_type_node);
3678   vtbl_ptr_type_node = build_pointer_type (vtable_entry_type);
3679   layout_type (vtbl_ptr_type_node);
3680   record_builtin_type (RID_MAX, NULL, vtbl_ptr_type_node);
3681
3682   push_namespace (get_identifier ("__cxxabiv1"));
3683   abi_node = current_namespace;
3684   pop_namespace ();
3685
3686   global_type_node = make_node (LANG_TYPE);
3687   record_unknown_type (global_type_node, "global type");
3688
3689   /* Now, C++.  */
3690   current_lang_name = lang_name_cplusplus;
3691
3692   {
3693     tree newattrs, extvisattr;
3694     tree newtype, deltype;
3695     tree ptr_ftype_sizetype;
3696     tree new_eh_spec;
3697
3698     ptr_ftype_sizetype
3699       = build_function_type_list (ptr_type_node, size_type_node, NULL_TREE);
3700     if (cxx_dialect == cxx98)
3701       {
3702         tree bad_alloc_id;
3703         tree bad_alloc_type_node;
3704         tree bad_alloc_decl;
3705
3706         push_namespace (std_identifier);
3707         bad_alloc_id = get_identifier ("bad_alloc");
3708         bad_alloc_type_node = make_class_type (RECORD_TYPE);
3709         TYPE_CONTEXT (bad_alloc_type_node) = current_namespace;
3710         bad_alloc_decl
3711           = create_implicit_typedef (bad_alloc_id, bad_alloc_type_node);
3712         DECL_CONTEXT (bad_alloc_decl) = current_namespace;
3713         pop_namespace ();
3714
3715         new_eh_spec
3716           = add_exception_specifier (NULL_TREE, bad_alloc_type_node, -1);
3717       }
3718     else
3719       new_eh_spec = noexcept_false_spec;
3720
3721     /* Ensure attribs.c is initialized.  */
3722     init_attributes ();
3723     extvisattr = build_tree_list (get_identifier ("externally_visible"),
3724                                   NULL_TREE);
3725     newattrs = tree_cons (get_identifier ("alloc_size"),
3726                           build_tree_list (NULL_TREE, integer_one_node),
3727                           extvisattr);
3728     newtype = cp_build_type_attribute_variant (ptr_ftype_sizetype, newattrs);
3729     newtype = build_exception_variant (newtype, new_eh_spec);
3730     deltype = cp_build_type_attribute_variant (void_ftype_ptr, extvisattr);
3731     deltype = build_exception_variant (deltype, empty_except_spec);
3732     push_cp_library_fn (NEW_EXPR, newtype);
3733     push_cp_library_fn (VEC_NEW_EXPR, newtype);
3734     global_delete_fndecl = push_cp_library_fn (DELETE_EXPR, deltype);
3735     push_cp_library_fn (VEC_DELETE_EXPR, deltype);
3736
3737     nullptr_type_node = make_node (NULLPTR_TYPE);
3738     TYPE_SIZE (nullptr_type_node) = bitsize_int (GET_MODE_BITSIZE (ptr_mode));
3739     TYPE_SIZE_UNIT (nullptr_type_node) = size_int (GET_MODE_SIZE (ptr_mode));
3740     TYPE_UNSIGNED (nullptr_type_node) = 1;
3741     TYPE_PRECISION (nullptr_type_node) = GET_MODE_BITSIZE (ptr_mode);
3742     SET_TYPE_MODE (nullptr_type_node, ptr_mode);
3743     record_builtin_type (RID_MAX, "decltype(nullptr)", nullptr_type_node);
3744     nullptr_node = build_int_cst (nullptr_type_node, 0);
3745   }
3746
3747   abort_fndecl
3748     = build_library_fn_ptr ("__cxa_pure_virtual", void_ftype);
3749
3750   /* Perform other language dependent initializations.  */
3751   init_class_processing ();
3752   init_rtti_processing ();
3753   init_template_processing ();
3754
3755   if (flag_exceptions)
3756     init_exception_processing ();
3757
3758   if (! supports_one_only ())
3759     flag_weak = 0;
3760
3761   make_fname_decl = cp_make_fname_decl;
3762   start_fname_decls ();
3763
3764   /* Show we use EH for cleanups.  */
3765   if (flag_exceptions)
3766     using_eh_for_cleanups ();
3767 }
3768
3769 /* Generate an initializer for a function naming variable from
3770    NAME. NAME may be NULL, to indicate a dependent name.  TYPE_P is
3771    filled in with the type of the init.  */
3772
3773 tree
3774 cp_fname_init (const char* name, tree *type_p)
3775 {
3776   tree domain = NULL_TREE;
3777   tree type;
3778   tree init = NULL_TREE;
3779   size_t length = 0;
3780
3781   if (name)
3782     {
3783       length = strlen (name);
3784       domain = build_index_type (size_int (length));
3785       init = build_string (length + 1, name);
3786     }
3787
3788   type = cp_build_qualified_type (char_type_node, TYPE_QUAL_CONST);
3789   type = build_cplus_array_type (type, domain);
3790
3791   *type_p = type;
3792
3793   if (init)
3794     TREE_TYPE (init) = type;
3795   else
3796     init = error_mark_node;
3797
3798   return init;
3799 }
3800
3801 /* Create the VAR_DECL for __FUNCTION__ etc. ID is the name to give
3802    the decl, LOC is the location to give the decl, NAME is the
3803    initialization string and TYPE_DEP indicates whether NAME depended
3804    on the type of the function. We make use of that to detect
3805    __PRETTY_FUNCTION__ inside a template fn. This is being done lazily
3806    at the point of first use, so we mustn't push the decl now.  */
3807
3808 static tree
3809 cp_make_fname_decl (location_t loc, tree id, int type_dep)
3810 {
3811   const char *const name = (type_dep && processing_template_decl
3812                             ? NULL : fname_as_string (type_dep));
3813   tree type;
3814   tree init = cp_fname_init (name, &type);
3815   tree decl = build_decl (loc, VAR_DECL, id, type);
3816
3817   if (name)
3818     free (CONST_CAST (char *, name));
3819
3820   /* As we're using pushdecl_with_scope, we must set the context.  */
3821   DECL_CONTEXT (decl) = current_function_decl;
3822   DECL_PRETTY_FUNCTION_P (decl) = type_dep;
3823
3824   TREE_STATIC (decl) = 1;
3825   TREE_READONLY (decl) = 1;
3826   DECL_ARTIFICIAL (decl) = 1;
3827
3828   TREE_USED (decl) = 1;
3829
3830   if (current_function_decl)
3831     {
3832       cp_binding_level *b = current_binding_level;
3833       if (b->kind == sk_function_parms)
3834         return error_mark_node;
3835       while (b->level_chain->kind != sk_function_parms)
3836         b = b->level_chain;
3837       pushdecl_with_scope (decl, b, /*is_friend=*/false);
3838       cp_finish_decl (decl, init, /*init_const_expr_p=*/false, NULL_TREE,
3839                       LOOKUP_ONLYCONVERTING);
3840     }
3841   else
3842     {
3843       DECL_THIS_STATIC (decl) = true;
3844       pushdecl_top_level_and_finish (decl, init);
3845     }
3846
3847   return decl;
3848 }
3849
3850 static tree
3851 builtin_function_1 (tree decl, tree context, bool is_global)
3852 {
3853   tree          id = DECL_NAME (decl);
3854   const char *name = IDENTIFIER_POINTER (id);
3855
3856   retrofit_lang_decl (decl);
3857
3858   DECL_ARTIFICIAL (decl) = 1;
3859   SET_OVERLOADED_OPERATOR_CODE (decl, ERROR_MARK);
3860   SET_DECL_LANGUAGE (decl, lang_c);
3861   /* Runtime library routines are, by definition, available in an
3862      external shared object.  */
3863   DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
3864   DECL_VISIBILITY_SPECIFIED (decl) = 1;
3865
3866   DECL_CONTEXT (decl) = context;
3867
3868   if (is_global)
3869     pushdecl_top_level (decl);
3870   else
3871     pushdecl (decl);
3872
3873   /* A function in the user's namespace should have an explicit
3874      declaration before it is used.  Mark the built-in function as
3875      anticipated but not actually declared.  */
3876   if (name[0] != '_' || name[1] != '_')
3877     DECL_ANTICIPATED (decl) = 1;
3878   else if (strncmp (name + 2, "builtin_", strlen ("builtin_")) != 0)
3879     {
3880       size_t len = strlen (name);
3881
3882       /* Treat __*_chk fortification functions as anticipated as well,
3883          unless they are __builtin_*.  */
3884       if (len > strlen ("___chk")
3885           && memcmp (name + len - strlen ("_chk"),
3886                      "_chk", strlen ("_chk") + 1) == 0)
3887         DECL_ANTICIPATED (decl) = 1;
3888     }
3889
3890   return decl;
3891 }
3892
3893 tree
3894 cxx_builtin_function (tree decl)
3895 {
3896   tree          id = DECL_NAME (decl);
3897   const char *name = IDENTIFIER_POINTER (id);
3898   /* All builtins that don't begin with an '_' should additionally
3899      go in the 'std' namespace.  */
3900   if (name[0] != '_')
3901     {
3902       tree decl2 = copy_node(decl);
3903       push_namespace (std_identifier);
3904       builtin_function_1 (decl2, std_node, false);
3905       pop_namespace ();
3906     }
3907
3908   return builtin_function_1 (decl, NULL_TREE, false);
3909 }
3910
3911 /* Like cxx_builtin_function, but guarantee the function is added to the global
3912    scope.  This is to allow function specific options to add new machine
3913    dependent builtins when the target ISA changes via attribute((target(...)))
3914    which saves space on program startup if the program does not use non-generic
3915    ISAs.  */
3916
3917 tree
3918 cxx_builtin_function_ext_scope (tree decl)
3919 {
3920
3921   tree          id = DECL_NAME (decl);
3922   const char *name = IDENTIFIER_POINTER (id);
3923   /* All builtins that don't begin with an '_' should additionally
3924      go in the 'std' namespace.  */
3925   if (name[0] != '_')
3926     {
3927       tree decl2 = copy_node(decl);
3928       push_namespace (std_identifier);
3929       builtin_function_1 (decl2, std_node, true);
3930       pop_namespace ();
3931     }
3932
3933   return builtin_function_1 (decl, NULL_TREE, true);
3934 }
3935
3936 /* Generate a FUNCTION_DECL with the typical flags for a runtime library
3937    function.  Not called directly.  */
3938
3939 static tree
3940 build_library_fn_1 (tree name, enum tree_code operator_code, tree type)
3941 {
3942   tree fn = build_lang_decl (FUNCTION_DECL, name, type);
3943   DECL_EXTERNAL (fn) = 1;
3944   TREE_PUBLIC (fn) = 1;
3945   DECL_ARTIFICIAL (fn) = 1;
3946   SET_OVERLOADED_OPERATOR_CODE (fn, operator_code);
3947   SET_DECL_LANGUAGE (fn, lang_c);
3948   /* Runtime library routines are, by definition, available in an
3949      external shared object.  */
3950   DECL_VISIBILITY (fn) = VISIBILITY_DEFAULT;
3951   DECL_VISIBILITY_SPECIFIED (fn) = 1;
3952   return fn;
3953 }
3954
3955 /* Returns the _DECL for a library function with C linkage.
3956    We assume that such functions never throw; if this is incorrect,
3957    callers should unset TREE_NOTHROW.  */
3958
3959 static tree
3960 build_library_fn (tree name, tree type)
3961 {
3962   tree fn = build_library_fn_1 (name, ERROR_MARK, type);
3963   TREE_NOTHROW (fn) = 1;
3964   return fn;
3965 }
3966
3967 /* Returns the _DECL for a library function with C++ linkage.  */
3968
3969 static tree
3970 build_cp_library_fn (tree name, enum tree_code operator_code, tree type)
3971 {
3972   tree fn = build_library_fn_1 (name, operator_code, type);
3973   TREE_NOTHROW (fn) = TYPE_NOTHROW_P (type);
3974   DECL_CONTEXT (fn) = FROB_CONTEXT (current_namespace);
3975   SET_DECL_LANGUAGE (fn, lang_cplusplus);
3976   return fn;
3977 }
3978
3979 /* Like build_library_fn, but takes a C string instead of an
3980    IDENTIFIER_NODE.  */
3981
3982 tree
3983 build_library_fn_ptr (const char* name, tree type)
3984 {
3985   return build_library_fn (get_identifier (name), type);
3986 }
3987
3988 /* Like build_cp_library_fn, but takes a C string instead of an
3989    IDENTIFIER_NODE.  */
3990
3991 tree
3992 build_cp_library_fn_ptr (const char* name, tree type)
3993 {
3994   return build_cp_library_fn (get_identifier (name), ERROR_MARK, type);
3995 }
3996
3997 /* Like build_library_fn, but also pushes the function so that we will
3998    be able to find it via IDENTIFIER_GLOBAL_VALUE.  Also, the function
3999    may throw exceptions listed in RAISES.  */
4000
4001 tree
4002 push_library_fn (tree name, tree type, tree raises)
4003 {
4004   tree fn;
4005
4006   if (raises)
4007     type = build_exception_variant (type, raises);
4008
4009   fn = build_library_fn (name, type);
4010   pushdecl_top_level (fn);
4011   return fn;
4012 }
4013
4014 /* Like build_cp_library_fn, but also pushes the function so that it
4015    will be found by normal lookup.  */
4016
4017 static tree
4018 push_cp_library_fn (enum tree_code operator_code, tree type)
4019 {
4020   tree fn = build_cp_library_fn (ansi_opname (operator_code),
4021                                  operator_code,
4022                                  type);
4023   pushdecl (fn);
4024   if (flag_tm)
4025     apply_tm_attr (fn, get_identifier ("transaction_safe"));
4026   return fn;
4027 }
4028
4029 /* Like push_library_fn, but takes a TREE_LIST of parm types rather than
4030    a FUNCTION_TYPE.  */
4031
4032 tree
4033 push_void_library_fn (tree name, tree parmtypes)
4034 {
4035   tree type = build_function_type (void_type_node, parmtypes);
4036   return push_library_fn (name, type, NULL_TREE);
4037 }
4038
4039 /* Like push_library_fn, but also note that this function throws
4040    and does not return.  Used for __throw_foo and the like.  */
4041
4042 tree
4043 push_throw_library_fn (tree name, tree type)
4044 {
4045   tree fn = push_library_fn (name, type, NULL_TREE);
4046   TREE_THIS_VOLATILE (fn) = 1;
4047   TREE_NOTHROW (fn) = 0;
4048   return fn;
4049 }
4050 \f
4051 /* When we call finish_struct for an anonymous union, we create
4052    default copy constructors and such.  But, an anonymous union
4053    shouldn't have such things; this function undoes the damage to the
4054    anonymous union type T.
4055
4056    (The reason that we create the synthesized methods is that we don't
4057    distinguish `union { int i; }' from `typedef union { int i; } U'.
4058    The first is an anonymous union; the second is just an ordinary
4059    union type.)  */
4060
4061 void
4062 fixup_anonymous_aggr (tree t)
4063 {
4064   tree *q;
4065
4066   /* Wipe out memory of synthesized methods.  */
4067   TYPE_HAS_USER_CONSTRUCTOR (t) = 0;
4068   TYPE_HAS_DEFAULT_CONSTRUCTOR (t) = 0;
4069   TYPE_HAS_COPY_CTOR (t) = 0;
4070   TYPE_HAS_CONST_COPY_CTOR (t) = 0;
4071   TYPE_HAS_COPY_ASSIGN (t) = 0;
4072   TYPE_HAS_CONST_COPY_ASSIGN (t) = 0;
4073
4074   /* Splice the implicitly generated functions out of the TYPE_METHODS
4075      list.  */
4076   q = &TYPE_METHODS (t);
4077   while (*q)
4078     {
4079       if (DECL_ARTIFICIAL (*q))
4080         *q = TREE_CHAIN (*q);
4081       else
4082         q = &DECL_CHAIN (*q);
4083     }
4084
4085   /* ISO C++ 9.5.3.  Anonymous unions may not have function members.  */
4086   if (TYPE_METHODS (t))
4087     {
4088       tree decl = TYPE_MAIN_DECL (t);
4089
4090       if (TREE_CODE (t) != UNION_TYPE)
4091         error_at (DECL_SOURCE_LOCATION (decl), 
4092                   "an anonymous struct cannot have function members");
4093       else
4094         error_at (DECL_SOURCE_LOCATION (decl),
4095                   "an anonymous union cannot have function members");
4096     }
4097
4098   /* Anonymous aggregates cannot have fields with ctors, dtors or complex
4099      assignment operators (because they cannot have these methods themselves).
4100      For anonymous unions this is already checked because they are not allowed
4101      in any union, otherwise we have to check it.  */
4102   if (TREE_CODE (t) != UNION_TYPE)
4103     {
4104       tree field, type;
4105
4106       for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
4107         if (TREE_CODE (field) == FIELD_DECL)
4108           {
4109             type = TREE_TYPE (field);
4110             if (CLASS_TYPE_P (type))
4111               {
4112                 if (TYPE_NEEDS_CONSTRUCTING (type))
4113                   error ("member %q+#D with constructor not allowed "
4114                          "in anonymous aggregate", field);
4115                 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
4116                   error ("member %q+#D with destructor not allowed "
4117                          "in anonymous aggregate", field);
4118                 if (TYPE_HAS_COMPLEX_COPY_ASSIGN (type))
4119                   error ("member %q+#D with copy assignment operator "
4120                          "not allowed in anonymous aggregate", field);
4121               }
4122           }
4123     }
4124 }
4125
4126 /* Make sure that a declaration with no declarator is well-formed, i.e.
4127    just declares a tagged type or anonymous union.
4128
4129    Returns the type declared; or NULL_TREE if none.  */
4130
4131 tree
4132 check_tag_decl (cp_decl_specifier_seq *declspecs)
4133 {
4134   int saw_friend = decl_spec_seq_has_spec_p (declspecs, ds_friend);
4135   int saw_typedef = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
4136   /* If a class, struct, or enum type is declared by the DECLSPECS
4137      (i.e, if a class-specifier, enum-specifier, or non-typename
4138      elaborated-type-specifier appears in the DECLSPECS),
4139      DECLARED_TYPE is set to the corresponding type.  */
4140   tree declared_type = NULL_TREE;
4141   bool error_p = false;
4142
4143   if (declspecs->multiple_types_p)
4144     error ("multiple types in one declaration");
4145   else if (declspecs->redefined_builtin_type)
4146     {
4147       if (!in_system_header)
4148         permerror (declspecs->locations[ds_redefined_builtin_type_spec],
4149                    "redeclaration of C++ built-in type %qT",
4150                    declspecs->redefined_builtin_type);
4151       return NULL_TREE;
4152     }
4153
4154   if (declspecs->type
4155       && TYPE_P (declspecs->type)
4156       && ((TREE_CODE (declspecs->type) != TYPENAME_TYPE
4157            && MAYBE_CLASS_TYPE_P (declspecs->type))
4158           || TREE_CODE (declspecs->type) == ENUMERAL_TYPE))
4159     declared_type = declspecs->type;
4160   else if (declspecs->type == error_mark_node)
4161     error_p = true;
4162   if (declared_type == NULL_TREE && ! saw_friend && !error_p)
4163     permerror (input_location, "declaration does not declare anything");
4164   else if (declared_type != NULL_TREE && type_uses_auto (declared_type))
4165     {
4166       error ("%<auto%> can only be specified for variables "
4167              "or function declarations");
4168       return error_mark_node;
4169     }
4170   /* Check for an anonymous union.  */
4171   else if (declared_type && RECORD_OR_UNION_CODE_P (TREE_CODE (declared_type))
4172            && TYPE_ANONYMOUS_P (declared_type))
4173     {
4174       /* 7/3 In a simple-declaration, the optional init-declarator-list
4175          can be omitted only when declaring a class (clause 9) or
4176          enumeration (7.2), that is, when the decl-specifier-seq contains
4177          either a class-specifier, an elaborated-type-specifier with
4178          a class-key (9.1), or an enum-specifier.  In these cases and
4179          whenever a class-specifier or enum-specifier is present in the
4180          decl-specifier-seq, the identifiers in these specifiers are among
4181          the names being declared by the declaration (as class-name,
4182          enum-names, or enumerators, depending on the syntax).  In such
4183          cases, and except for the declaration of an unnamed bit-field (9.6),
4184          the decl-specifier-seq shall introduce one or more names into the
4185          program, or shall redeclare a name introduced by a previous
4186          declaration.  [Example:
4187              enum { };                  // ill-formed
4188              typedef class { };         // ill-formed
4189          --end example]  */
4190       if (saw_typedef)
4191         {
4192           error ("missing type-name in typedef-declaration");
4193           return NULL_TREE;
4194         }
4195       /* Anonymous unions are objects, so they can have specifiers.  */;
4196       SET_ANON_AGGR_TYPE_P (declared_type);
4197
4198       if (TREE_CODE (declared_type) != UNION_TYPE && !in_system_header)
4199         pedwarn (input_location, OPT_Wpedantic, "ISO C++ prohibits anonymous structs");
4200     }
4201
4202   else
4203     {
4204       if (decl_spec_seq_has_spec_p (declspecs, ds_inline)
4205           || decl_spec_seq_has_spec_p (declspecs, ds_virtual))
4206         error ("%qs can only be specified for functions",
4207                decl_spec_seq_has_spec_p (declspecs, ds_inline)
4208                ? "inline" : "virtual");
4209       else if (saw_friend
4210                && (!current_class_type
4211                    || current_scope () != current_class_type))
4212         error ("%<friend%> can only be specified inside a class");
4213       else if (decl_spec_seq_has_spec_p (declspecs, ds_explicit))
4214         error ("%<explicit%> can only be specified for constructors");
4215       else if (declspecs->storage_class)
4216         error ("a storage class can only be specified for objects "
4217                "and functions");
4218       else if (decl_spec_seq_has_spec_p (declspecs, ds_const)
4219                || decl_spec_seq_has_spec_p (declspecs, ds_volatile)
4220                || decl_spec_seq_has_spec_p (declspecs, ds_restrict)
4221                || decl_spec_seq_has_spec_p (declspecs, ds_thread))
4222         error ("qualifiers can only be specified for objects "
4223                "and functions");
4224       else if (saw_typedef)
4225         warning (0, "%<typedef%> was ignored in this declaration");
4226       else if (decl_spec_seq_has_spec_p (declspecs,  ds_constexpr))
4227         error ("%<constexpr%> cannot be used for type declarations");
4228     }
4229
4230   if (declspecs->attributes && warn_attributes && declared_type)
4231     {
4232       location_t loc;
4233       if (!CLASS_TYPE_P (declared_type)
4234           || !CLASSTYPE_TEMPLATE_INSTANTIATION (declared_type))
4235         /* For a non-template class, use the name location.  */
4236         loc = location_of (declared_type);
4237       else
4238         /* For a template class (an explicit instantiation), use the
4239            current location.  */
4240         loc = input_location;
4241       warning_at (loc, OPT_Wattributes, "attribute ignored in declaration "
4242                   "of %q#T", declared_type);
4243       inform (loc, "attribute for %q#T must follow the %qs keyword",
4244               declared_type, class_key_or_enum_as_string (declared_type));
4245     }
4246
4247   return declared_type;
4248 }
4249
4250 /* Called when a declaration is seen that contains no names to declare.
4251    If its type is a reference to a structure, union or enum inherited
4252    from a containing scope, shadow that tag name for the current scope
4253    with a forward reference.
4254    If its type defines a new named structure or union
4255    or defines an enum, it is valid but we need not do anything here.
4256    Otherwise, it is an error.
4257
4258    C++: may have to grok the declspecs to learn about static,
4259    complain for anonymous unions.
4260
4261    Returns the TYPE declared -- or NULL_TREE if none.  */
4262
4263 tree
4264 shadow_tag (cp_decl_specifier_seq *declspecs)
4265 {
4266   tree t = check_tag_decl (declspecs);
4267
4268   if (!t)
4269     return NULL_TREE;
4270
4271   if (maybe_process_partial_specialization (t) == error_mark_node)
4272     return NULL_TREE;
4273
4274   /* This is where the variables in an anonymous union are
4275      declared.  An anonymous union declaration looks like:
4276      union { ... } ;
4277      because there is no declarator after the union, the parser
4278      sends that declaration here.  */
4279   if (ANON_AGGR_TYPE_P (t))
4280     {
4281       fixup_anonymous_aggr (t);
4282
4283       if (TYPE_FIELDS (t))
4284         {
4285           tree decl = grokdeclarator (/*declarator=*/NULL,
4286                                       declspecs, NORMAL, 0, NULL);
4287           finish_anon_union (decl);
4288         }
4289     }
4290
4291   return t;
4292 }
4293 \f
4294 /* Decode a "typename", such as "int **", returning a ..._TYPE node.  */
4295
4296 tree
4297 groktypename (cp_decl_specifier_seq *type_specifiers,
4298               const cp_declarator *declarator,
4299               bool is_template_arg)
4300 {
4301   tree attrs;
4302   tree type;
4303   enum decl_context context
4304     = is_template_arg ? TEMPLATE_TYPE_ARG : TYPENAME;
4305   attrs = type_specifiers->attributes;
4306   type_specifiers->attributes = NULL_TREE;
4307   type = grokdeclarator (declarator, type_specifiers, context, 0, &attrs);
4308   if (attrs && type != error_mark_node)
4309     {
4310       if (CLASS_TYPE_P (type))
4311         warning (OPT_Wattributes, "ignoring attributes applied to class type %qT "
4312                  "outside of definition", type);
4313       else if (MAYBE_CLASS_TYPE_P (type))
4314         /* A template type parameter or other dependent type.  */
4315         warning (OPT_Wattributes, "ignoring attributes applied to dependent "
4316                  "type %qT without an associated declaration", type);
4317       else
4318         cplus_decl_attributes (&type, attrs, 0);
4319     }
4320   return type;
4321 }
4322
4323 /* Process a DECLARATOR for a function-scope variable declaration,
4324    namespace-scope variable declaration, or function declaration.
4325    (Function definitions go through start_function; class member
4326    declarations appearing in the body of the class go through
4327    grokfield.)  The DECL corresponding to the DECLARATOR is returned.
4328    If an error occurs, the error_mark_node is returned instead.
4329    
4330    DECLSPECS are the decl-specifiers for the declaration.  INITIALIZED is
4331    SD_INITIALIZED if an explicit initializer is present, or SD_DEFAULTED
4332    for an explicitly defaulted function, or SD_DELETED for an explicitly
4333    deleted function, but 0 (SD_UNINITIALIZED) if this is a variable
4334    implicitly initialized via a default constructor.  ATTRIBUTES and
4335    PREFIX_ATTRIBUTES are GNU attributes associated with this declaration.
4336
4337    The scope represented by the context of the returned DECL is pushed
4338    (if it is not the global namespace) and is assigned to
4339    *PUSHED_SCOPE_P.  The caller is then responsible for calling
4340    pop_scope on *PUSHED_SCOPE_P if it is set.  */
4341
4342 tree
4343 start_decl (const cp_declarator *declarator,
4344             cp_decl_specifier_seq *declspecs,
4345             int initialized,
4346             tree attributes,
4347             tree prefix_attributes,
4348             tree *pushed_scope_p)
4349 {
4350   tree decl;
4351   tree context;
4352   bool was_public;
4353   int flags;
4354   bool alias;
4355
4356   *pushed_scope_p = NULL_TREE;
4357
4358   /* An object declared as __attribute__((deprecated)) suppresses
4359      warnings of uses of other deprecated items.  */
4360   if (lookup_attribute ("deprecated", attributes))
4361     deprecated_state = DEPRECATED_SUPPRESS;
4362
4363   attributes = chainon (attributes, prefix_attributes);
4364
4365   decl = grokdeclarator (declarator, declspecs, NORMAL, initialized,
4366                          &attributes);
4367
4368   deprecated_state = DEPRECATED_NORMAL;
4369
4370   if (decl == NULL_TREE || TREE_CODE (decl) == VOID_TYPE
4371       || decl == error_mark_node)
4372     return error_mark_node;
4373
4374   context = CP_DECL_CONTEXT (decl);
4375   if (context != global_namespace)
4376     *pushed_scope_p = push_scope (context);
4377
4378   if (initialized)
4379     /* Is it valid for this decl to have an initializer at all?
4380        If not, set INITIALIZED to zero, which will indirectly
4381        tell `cp_finish_decl' to ignore the initializer once it is parsed.  */
4382     switch (TREE_CODE (decl))
4383       {
4384       case TYPE_DECL:
4385         error ("typedef %qD is initialized (use decltype instead)", decl);
4386         return error_mark_node;
4387
4388       case FUNCTION_DECL:
4389         if (initialized == SD_DELETED)
4390           /* We'll handle the rest of the semantics later, but we need to
4391              set this now so it's visible to duplicate_decls.  */
4392           DECL_DELETED_FN (decl) = 1;
4393         break;
4394
4395       default:
4396         break;
4397       }
4398
4399   if (initialized)
4400     {
4401       if (! toplevel_bindings_p ()
4402           && DECL_EXTERNAL (decl))
4403         warning (0, "declaration of %q#D has %<extern%> and is initialized",
4404                  decl);
4405       DECL_EXTERNAL (decl) = 0;
4406       if (toplevel_bindings_p ())
4407         TREE_STATIC (decl) = 1;
4408     }
4409   alias = lookup_attribute ("alias", DECL_ATTRIBUTES (decl)) != 0;
4410   
4411   if (alias && TREE_CODE (decl) == FUNCTION_DECL)
4412     record_key_method_defined (decl);
4413
4414   /* If this is a typedef that names the class for linkage purposes
4415      (7.1.3p8), apply any attributes directly to the type.  */
4416   if (TREE_CODE (decl) == TYPE_DECL
4417       && TAGGED_TYPE_P (TREE_TYPE (decl))
4418       && decl == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (decl))))
4419     flags = ATTR_FLAG_TYPE_IN_PLACE;
4420   else
4421     flags = 0;
4422
4423   /* Set attributes here so if duplicate decl, will have proper attributes.  */
4424   cplus_decl_attributes (&decl, attributes, flags);
4425
4426   /* Dllimported symbols cannot be defined.  Static data members (which
4427      can be initialized in-class and dllimported) go through grokfield,
4428      not here, so we don't need to exclude those decls when checking for
4429      a definition.  */
4430   if (initialized && DECL_DLLIMPORT_P (decl))
4431     {
4432       error ("definition of %q#D is marked %<dllimport%>", decl);
4433       DECL_DLLIMPORT_P (decl) = 0;
4434     }
4435
4436   /* If #pragma weak was used, mark the decl weak now.  */
4437   if (!processing_template_decl)
4438     maybe_apply_pragma_weak (decl);
4439
4440   if (TREE_CODE (decl) == FUNCTION_DECL
4441       && DECL_DECLARED_INLINE_P (decl)
4442       && DECL_UNINLINABLE (decl)
4443       && lookup_attribute ("noinline", DECL_ATTRIBUTES (decl)))
4444     warning (0, "inline function %q+D given attribute noinline", decl);
4445
4446   if (TYPE_P (context) && COMPLETE_TYPE_P (complete_type (context)))
4447     {
4448       if (TREE_CODE (decl) == VAR_DECL)
4449         {
4450           tree field = lookup_field (context, DECL_NAME (decl), 0, false);
4451           if (field == NULL_TREE || TREE_CODE (field) != VAR_DECL)
4452             error ("%q#D is not a static member of %q#T", decl, context);
4453           else
4454             {
4455               if (DECL_CONTEXT (field) != context)
4456                 {
4457                   if (!same_type_p (DECL_CONTEXT (field), context))
4458                     permerror (input_location, "ISO C++ does not permit %<%T::%D%> "
4459                                "to be defined as %<%T::%D%>",
4460                                DECL_CONTEXT (field), DECL_NAME (decl),
4461                                context, DECL_NAME (decl));
4462                   DECL_CONTEXT (decl) = DECL_CONTEXT (field);
4463                 }
4464               /* Static data member are tricky; an in-class initialization
4465                  still doesn't provide a definition, so the in-class
4466                  declaration will have DECL_EXTERNAL set, but will have an
4467                  initialization.  Thus, duplicate_decls won't warn
4468                  about this situation, and so we check here.  */
4469               if (initialized && DECL_INITIALIZED_IN_CLASS_P (field))
4470                 error ("duplicate initialization of %qD", decl);
4471               if (duplicate_decls (decl, field, /*newdecl_is_friend=*/false))
4472                 decl = field;
4473               if (decl_spec_seq_has_spec_p (declspecs, ds_constexpr)
4474                   && !DECL_DECLARED_CONSTEXPR_P (field))
4475                 error ("%qD declared %<constexpr%> outside its class", field);
4476             }
4477         }
4478       else
4479         {
4480           tree field = check_classfn (context, decl,
4481                                       (processing_template_decl
4482                                        > template_class_depth (context))
4483                                       ? current_template_parms
4484                                       : NULL_TREE);
4485           if (field && field != error_mark_node
4486               && duplicate_decls (decl, field,
4487                                  /*newdecl_is_friend=*/false))
4488             decl = field;
4489         }
4490
4491       /* cp_finish_decl sets DECL_EXTERNAL if DECL_IN_AGGR_P is set.  */
4492       DECL_IN_AGGR_P (decl) = 0;
4493       /* Do not mark DECL as an explicit specialization if it was not
4494          already marked as an instantiation; a declaration should
4495          never be marked as a specialization unless we know what
4496          template is being specialized.  */
4497       if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
4498         {
4499           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
4500
4501           /* [temp.expl.spec] An explicit specialization of a static data
4502              member of a template is a definition if the declaration
4503              includes an initializer; otherwise, it is a declaration.
4504
4505              We check for processing_specialization so this only applies
4506              to the new specialization syntax.  */
4507           if (!initialized && processing_specialization)
4508             DECL_EXTERNAL (decl) = 1;
4509         }
4510
4511       if (DECL_EXTERNAL (decl) && ! DECL_TEMPLATE_SPECIALIZATION (decl)
4512           /* Aliases are definitions. */
4513           && !alias)
4514         permerror (input_location, "declaration of %q#D outside of class is not definition",
4515                    decl);
4516     }
4517
4518   was_public = TREE_PUBLIC (decl);
4519
4520   /* Enter this declaration into the symbol table.  */
4521   decl = maybe_push_decl (decl);
4522
4523   if (processing_template_decl)
4524     decl = push_template_decl (decl);
4525   if (decl == error_mark_node)
4526     return error_mark_node;
4527
4528   if (TREE_CODE (decl) == VAR_DECL
4529       && DECL_NAMESPACE_SCOPE_P (decl) && !TREE_PUBLIC (decl) && !was_public
4530       && !DECL_THIS_STATIC (decl) && !DECL_ARTIFICIAL (decl))
4531     {
4532       /* This is a const variable with implicit 'static'.  Set
4533          DECL_THIS_STATIC so we can tell it from variables that are
4534          !TREE_PUBLIC because of the anonymous namespace.  */
4535       gcc_assert (CP_TYPE_CONST_P (TREE_TYPE (decl)) || errorcount);
4536       DECL_THIS_STATIC (decl) = 1;
4537     }
4538
4539   if (!processing_template_decl && TREE_CODE (decl) == VAR_DECL)
4540     start_decl_1 (decl, initialized);
4541
4542   return decl;
4543 }
4544
4545 /* Process the declaration of a variable DECL.  INITIALIZED is true
4546    iff DECL is explicitly initialized.  (INITIALIZED is false if the
4547    variable is initialized via an implicitly-called constructor.)
4548    This function must be called for ordinary variables (including, for
4549    example, implicit instantiations of templates), but must not be
4550    called for template declarations.  */
4551
4552 void
4553 start_decl_1 (tree decl, bool initialized)
4554 {
4555   tree type;
4556   bool complete_p;
4557   bool aggregate_definition_p;
4558
4559   gcc_assert (!processing_template_decl);
4560
4561   if (error_operand_p (decl))
4562     return;
4563
4564   gcc_assert (TREE_CODE (decl) == VAR_DECL);
4565
4566   type = TREE_TYPE (decl);
4567   complete_p = COMPLETE_TYPE_P (type);
4568   aggregate_definition_p = MAYBE_CLASS_TYPE_P (type) && !DECL_EXTERNAL (decl);
4569
4570   /* If an explicit initializer is present, or if this is a definition
4571      of an aggregate, then we need a complete type at this point.
4572      (Scalars are always complete types, so there is nothing to
4573      check.)  This code just sets COMPLETE_P; errors (if necessary)
4574      are issued below.  */
4575   if ((initialized || aggregate_definition_p) 
4576       && !complete_p
4577       && COMPLETE_TYPE_P (complete_type (type)))
4578     {
4579       complete_p = true;
4580       /* We will not yet have set TREE_READONLY on DECL if the type
4581          was "const", but incomplete, before this point.  But, now, we
4582          have a complete type, so we can try again.  */
4583       cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
4584     }
4585
4586   if (initialized)
4587     /* Is it valid for this decl to have an initializer at all?  */
4588     {
4589       /* Don't allow initializations for incomplete types except for
4590          arrays which might be completed by the initialization.  */
4591       if (complete_p)
4592         ;                       /* A complete type is ok.  */
4593       else if (type_uses_auto (type))
4594         ;                       /* An auto type is ok.  */
4595       else if (TREE_CODE (type) != ARRAY_TYPE)
4596         {
4597           error ("variable %q#D has initializer but incomplete type", decl);
4598           type = TREE_TYPE (decl) = error_mark_node;
4599         }
4600       else if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (type))))
4601         {
4602           if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
4603             error ("elements of array %q#D have incomplete type", decl);
4604           /* else we already gave an error in start_decl.  */
4605         }
4606     }
4607   else if (aggregate_definition_p && !complete_p)
4608     {
4609       if (type_uses_auto (type))
4610         error ("declaration of %q#D has no initializer", decl);
4611       else
4612         error ("aggregate %q#D has incomplete type and cannot be defined",
4613                decl);
4614       /* Change the type so that assemble_variable will give
4615          DECL an rtl we can live with: (mem (const_int 0)).  */
4616       type = TREE_TYPE (decl) = error_mark_node;
4617     }
4618
4619   /* Create a new scope to hold this declaration if necessary.
4620      Whether or not a new scope is necessary cannot be determined
4621      until after the type has been completed; if the type is a
4622      specialization of a class template it is not until after
4623      instantiation has occurred that TYPE_HAS_NONTRIVIAL_DESTRUCTOR
4624      will be set correctly.  */
4625   maybe_push_cleanup_level (type);
4626 }
4627
4628 /* Handle initialization of references.  DECL, TYPE, and INIT have the
4629    same meaning as in cp_finish_decl.  *CLEANUP must be NULL on entry,
4630    but will be set to a new CLEANUP_STMT if a temporary is created
4631    that must be destroyed subsequently.
4632
4633    Returns an initializer expression to use to initialize DECL, or
4634    NULL if the initialization can be performed statically.
4635
4636    Quotes on semantics can be found in ARM 8.4.3.  */
4637
4638 static tree
4639 grok_reference_init (tree decl, tree type, tree init, int flags)
4640 {
4641   if (init == NULL_TREE)
4642     {
4643       if ((DECL_LANG_SPECIFIC (decl) == 0
4644            || DECL_IN_AGGR_P (decl) == 0)
4645           && ! DECL_THIS_EXTERN (decl))
4646         error ("%qD declared as reference but not initialized", decl);
4647       return NULL_TREE;
4648     }
4649
4650   if (TREE_CODE (init) == TREE_LIST)
4651     init = build_x_compound_expr_from_list (init, ELK_INIT,
4652                                             tf_warning_or_error);
4653
4654   if (TREE_CODE (TREE_TYPE (type)) != ARRAY_TYPE
4655       && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
4656     /* Note: default conversion is only called in very special cases.  */
4657     init = decay_conversion (init, tf_warning_or_error);
4658
4659   /* Convert INIT to the reference type TYPE.  This may involve the
4660      creation of a temporary, whose lifetime must be the same as that
4661      of the reference.  If so, a DECL_EXPR for the temporary will be
4662      added just after the DECL_EXPR for DECL.  That's why we don't set
4663      DECL_INITIAL for local references (instead assigning to them
4664      explicitly); we need to allow the temporary to be initialized
4665      first.  */
4666   return initialize_reference (type, init, flags,
4667                                tf_warning_or_error);
4668 }
4669
4670 /* Designated initializers in arrays are not supported in GNU C++.
4671    The parser cannot detect this error since it does not know whether
4672    a given brace-enclosed initializer is for a class type or for an
4673    array.  This function checks that CE does not use a designated
4674    initializer.  If it does, an error is issued.  Returns true if CE
4675    is valid, i.e., does not have a designated initializer.  */
4676
4677 static bool
4678 check_array_designated_initializer (const constructor_elt *ce,
4679                                     unsigned HOST_WIDE_INT index)
4680 {
4681   /* Designated initializers for array elements are not supported.  */
4682   if (ce->index)
4683     {
4684       /* The parser only allows identifiers as designated
4685          initializers.  */
4686       if (ce->index == error_mark_node)
4687         error ("name used in a GNU-style designated "
4688                "initializer for an array");
4689       else if (TREE_CODE (ce->index) == INTEGER_CST)
4690         {
4691           /* A C99 designator is OK if it matches the current index.  */
4692           if (TREE_INT_CST_LOW (ce->index) == index)
4693             return true;
4694           else
4695             sorry ("non-trivial designated initializers not supported");
4696         }
4697       else
4698         {
4699           gcc_assert (TREE_CODE (ce->index) == IDENTIFIER_NODE);
4700           error ("name %qD used in a GNU-style designated "
4701                  "initializer for an array", ce->index);
4702         }
4703       return false;
4704     }
4705
4706   return true;
4707 }
4708
4709 /* When parsing `int a[] = {1, 2};' we don't know the size of the
4710    array until we finish parsing the initializer.  If that's the
4711    situation we're in, update DECL accordingly.  */
4712
4713 static void
4714 maybe_deduce_size_from_array_init (tree decl, tree init)
4715 {
4716   tree type = TREE_TYPE (decl);
4717
4718   if (TREE_CODE (type) == ARRAY_TYPE
4719       && TYPE_DOMAIN (type) == NULL_TREE
4720       && TREE_CODE (decl) != TYPE_DECL)
4721     {
4722       /* do_default is really a C-ism to deal with tentative definitions.
4723          But let's leave it here to ease the eventual merge.  */
4724       int do_default = !DECL_EXTERNAL (decl);
4725       tree initializer = init ? init : DECL_INITIAL (decl);
4726       int failure = 0;
4727
4728       /* Check that there are no designated initializers in INIT, as
4729          those are not supported in GNU C++, and as the middle-end
4730          will crash if presented with a non-numeric designated
4731          initializer.  */
4732       if (initializer && TREE_CODE (initializer) == CONSTRUCTOR)
4733         {
4734           VEC(constructor_elt,gc) *v = CONSTRUCTOR_ELTS (initializer);
4735           constructor_elt *ce;
4736           HOST_WIDE_INT i;
4737           FOR_EACH_VEC_ELT (constructor_elt, v, i, ce)
4738             if (!check_array_designated_initializer (ce, i))
4739               failure = 1;
4740         }
4741
4742       if (!failure)
4743         {
4744           failure = cp_complete_array_type (&TREE_TYPE (decl), initializer,
4745                                             do_default);
4746           if (failure == 1)
4747             {
4748               error ("initializer fails to determine size of %qD", decl);
4749               TREE_TYPE (decl) = error_mark_node;
4750             }
4751           else if (failure == 2)
4752             {
4753               if (do_default)
4754                 {
4755                   error ("array size missing in %qD", decl);
4756                   TREE_TYPE (decl) = error_mark_node;
4757                 }
4758               /* If a `static' var's size isn't known, make it extern as
4759                  well as static, so it does not get allocated.  If it's not
4760                  `static', then don't mark it extern; finish_incomplete_decl
4761                  will give it a default size and it will get allocated.  */
4762               else if (!pedantic && TREE_STATIC (decl) && !TREE_PUBLIC (decl))
4763                 DECL_EXTERNAL (decl) = 1;
4764             }
4765           else if (failure == 3)
4766             {
4767               error ("zero-size array %qD", decl);
4768               TREE_TYPE (decl) = error_mark_node;
4769             }
4770         }
4771
4772       cp_apply_type_quals_to_decl (cp_type_quals (TREE_TYPE (decl)), decl);
4773
4774       relayout_decl (decl);
4775     }
4776 }
4777
4778 /* Set DECL_SIZE, DECL_ALIGN, etc. for DECL (a VAR_DECL), and issue
4779    any appropriate error messages regarding the layout.  */
4780
4781 static void
4782 layout_var_decl (tree decl)
4783 {
4784   tree type;
4785
4786   type = TREE_TYPE (decl);
4787   if (type == error_mark_node)
4788     return;
4789
4790   /* If we haven't already layed out this declaration, do so now.
4791      Note that we must not call complete type for an external object
4792      because it's type might involve templates that we are not
4793      supposed to instantiate yet.  (And it's perfectly valid to say
4794      `extern X x' for some incomplete type `X'.)  */
4795   if (!DECL_EXTERNAL (decl))
4796     complete_type (type);
4797   if (!DECL_SIZE (decl)
4798       && TREE_TYPE (decl) != error_mark_node
4799       && (COMPLETE_TYPE_P (type)
4800           || (TREE_CODE (type) == ARRAY_TYPE
4801               && !TYPE_DOMAIN (type)
4802               && COMPLETE_TYPE_P (TREE_TYPE (type)))))
4803     layout_decl (decl, 0);
4804
4805   if (!DECL_EXTERNAL (decl) && DECL_SIZE (decl) == NULL_TREE)
4806     {
4807       /* An automatic variable with an incomplete type: that is an error.
4808          Don't talk about array types here, since we took care of that
4809          message in grokdeclarator.  */
4810       error ("storage size of %qD isn%'t known", decl);
4811       TREE_TYPE (decl) = error_mark_node;
4812     }
4813 #if 0
4814   /* Keep this code around in case we later want to control debug info
4815      based on whether a type is "used".  (jason 1999-11-11) */
4816
4817   else if (!DECL_EXTERNAL (decl) && MAYBE_CLASS_TYPE_P (ttype))
4818     /* Let debugger know it should output info for this type.  */
4819     note_debug_info_needed (ttype);
4820
4821   if (TREE_STATIC (decl) && DECL_CLASS_SCOPE_P (decl))
4822     note_debug_info_needed (DECL_CONTEXT (decl));
4823 #endif
4824
4825   if ((DECL_EXTERNAL (decl) || TREE_STATIC (decl))
4826       && DECL_SIZE (decl) != NULL_TREE
4827       && ! TREE_CONSTANT (DECL_SIZE (decl)))
4828     {
4829       if (TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST)
4830         constant_expression_warning (DECL_SIZE (decl));
4831       else
4832         {
4833           error ("storage size of %qD isn%'t constant", decl);
4834           TREE_TYPE (decl) = error_mark_node;
4835         }
4836     }
4837 }
4838
4839 /* If a local static variable is declared in an inline function, or if
4840    we have a weak definition, we must endeavor to create only one
4841    instance of the variable at link-time.  */
4842
4843 void
4844 maybe_commonize_var (tree decl)
4845 {
4846   /* Static data in a function with comdat linkage also has comdat
4847      linkage.  */
4848   if (TREE_STATIC (decl)
4849       /* Don't mess with __FUNCTION__.  */
4850       && ! DECL_ARTIFICIAL (decl)
4851       && DECL_FUNCTION_SCOPE_P (decl)
4852       && vague_linkage_p (DECL_CONTEXT (decl)))
4853     {
4854       if (flag_weak)
4855         {
4856           /* With weak symbols, we simply make the variable COMDAT;
4857              that will cause copies in multiple translations units to
4858              be merged.  */
4859           comdat_linkage (decl);
4860         }
4861       else
4862         {
4863           if (DECL_INITIAL (decl) == NULL_TREE
4864               || DECL_INITIAL (decl) == error_mark_node)
4865             {
4866               /* Without weak symbols, we can use COMMON to merge
4867                  uninitialized variables.  */
4868               TREE_PUBLIC (decl) = 1;
4869               DECL_COMMON (decl) = 1;
4870             }
4871           else
4872             {
4873               /* While for initialized variables, we must use internal
4874                  linkage -- which means that multiple copies will not
4875                  be merged.  */
4876               TREE_PUBLIC (decl) = 0;
4877               DECL_COMMON (decl) = 0;
4878               warning_at (input_location, 0,
4879                           "sorry: semantics of inline function static "
4880                           "data %q+#D are wrong (you%'ll wind up "
4881                           "with multiple copies)", decl);
4882               warning_at (DECL_SOURCE_LOCATION (decl), 0, 
4883                           "  you can work around this by removing "
4884                           "the initializer");
4885             }
4886         }
4887     }
4888   else if (DECL_LANG_SPECIFIC (decl) && DECL_COMDAT (decl))
4889     /* Set it up again; we might have set DECL_INITIAL since the last
4890        time.  */
4891     comdat_linkage (decl);
4892 }
4893
4894 /* Issue an error message if DECL is an uninitialized const variable.  */
4895
4896 static void
4897 check_for_uninitialized_const_var (tree decl)
4898 {
4899   tree type = strip_array_types (TREE_TYPE (decl));
4900
4901   /* ``Unless explicitly declared extern, a const object does not have
4902      external linkage and must be initialized. ($8.4; $12.1)'' ARM
4903      7.1.6 */
4904   if (TREE_CODE (decl) == VAR_DECL
4905       && TREE_CODE (type) != REFERENCE_TYPE
4906       && CP_TYPE_CONST_P (type)
4907       && !DECL_INITIAL (decl))
4908     {
4909       tree field = default_init_uninitialized_part (type);
4910       if (!field)
4911         return;
4912
4913       permerror (DECL_SOURCE_LOCATION (decl),
4914                  "uninitialized const %qD", decl);
4915
4916       if (CLASS_TYPE_P (type))
4917         {
4918           tree defaulted_ctor;
4919
4920           inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)),
4921                   "%q#T has no user-provided default constructor", type);
4922           defaulted_ctor = in_class_defaulted_default_constructor (type);
4923           if (defaulted_ctor)
4924             inform (DECL_SOURCE_LOCATION (defaulted_ctor),
4925                     "constructor is not user-provided because it is "
4926                     "explicitly defaulted in the class body");
4927           inform (0, "and the implicitly-defined constructor does not "
4928                   "initialize %q+#D", field);
4929         }
4930     }
4931 }
4932 \f
4933 /* Structure holding the current initializer being processed by reshape_init.
4934    CUR is a pointer to the current element being processed, END is a pointer
4935    after the last element present in the initializer.  */
4936 typedef struct reshape_iterator_t
4937 {
4938   constructor_elt *cur;
4939   constructor_elt *end;
4940 } reshape_iter;
4941
4942 static tree reshape_init_r (tree, reshape_iter *, bool, tsubst_flags_t);
4943
4944 /* FIELD is a FIELD_DECL or NULL.  In the former case, the value
4945    returned is the next FIELD_DECL (possibly FIELD itself) that can be
4946    initialized.  If there are no more such fields, the return value
4947    will be NULL.  */
4948
4949 tree
4950 next_initializable_field (tree field)
4951 {
4952   while (field
4953          && (TREE_CODE (field) != FIELD_DECL
4954              || (DECL_C_BIT_FIELD (field) && !DECL_NAME (field))
4955              || DECL_ARTIFICIAL (field)))
4956     field = DECL_CHAIN (field);
4957
4958   return field;
4959 }
4960
4961 /* Subroutine of reshape_init_array and reshape_init_vector, which does
4962    the actual work. ELT_TYPE is the element type of the array. MAX_INDEX is an
4963    INTEGER_CST representing the size of the array minus one (the maximum index),
4964    or NULL_TREE if the array was declared without specifying the size. D is
4965    the iterator within the constructor.  */
4966
4967 static tree
4968 reshape_init_array_1 (tree elt_type, tree max_index, reshape_iter *d,
4969                       tsubst_flags_t complain)
4970 {
4971   tree new_init;
4972   bool sized_array_p = (max_index != NULL_TREE);
4973   unsigned HOST_WIDE_INT max_index_cst = 0;
4974   unsigned HOST_WIDE_INT index;
4975
4976   /* The initializer for an array is always a CONSTRUCTOR.  */
4977   new_init = build_constructor (init_list_type_node, NULL);
4978
4979   if (sized_array_p)
4980     {
4981       /* Minus 1 is used for zero sized arrays.  */
4982       if (integer_all_onesp (max_index))
4983         return new_init;
4984
4985       if (host_integerp (max_index, 1))
4986         max_index_cst = tree_low_cst (max_index, 1);
4987       /* sizetype is sign extended, not zero extended.  */
4988       else
4989         max_index_cst = tree_low_cst (fold_convert (size_type_node, max_index),
4990                                       1);
4991     }
4992
4993   /* Loop until there are no more initializers.  */
4994   for (index = 0;
4995        d->cur != d->end && (!sized_array_p || index <= max_index_cst);
4996        ++index)
4997     {
4998       tree elt_init;
4999
5000       check_array_designated_initializer (d->cur, index);
5001       elt_init = reshape_init_r (elt_type, d, /*first_initializer_p=*/false,
5002                                  complain);
5003       if (elt_init == error_mark_node)
5004         return error_mark_node;
5005       CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
5006                               size_int (index), elt_init);
5007       if (!TREE_CONSTANT (elt_init))
5008         TREE_CONSTANT (new_init) = false;
5009     }
5010
5011   return new_init;
5012 }
5013
5014 /* Subroutine of reshape_init_r, processes the initializers for arrays.
5015    Parameters are the same of reshape_init_r.  */
5016
5017 static tree
5018 reshape_init_array (tree type, reshape_iter *d, tsubst_flags_t complain)
5019 {
5020   tree max_index = NULL_TREE;
5021
5022   gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
5023
5024   if (TYPE_DOMAIN (type))
5025     max_index = array_type_nelts (type);
5026
5027   return reshape_init_array_1 (TREE_TYPE (type), max_index, d, complain);
5028 }
5029
5030 /* Subroutine of reshape_init_r, processes the initializers for vectors.
5031    Parameters are the same of reshape_init_r.  */
5032
5033 static tree
5034 reshape_init_vector (tree type, reshape_iter *d, tsubst_flags_t complain)
5035 {
5036   tree max_index = NULL_TREE;
5037
5038   gcc_assert (TREE_CODE (type) == VECTOR_TYPE);
5039
5040   if (COMPOUND_LITERAL_P (d->cur->value))
5041     {
5042       tree value = d->cur->value;
5043       if (!same_type_p (TREE_TYPE (value), type))
5044         {
5045           if (complain & tf_error)
5046             error ("invalid type %qT as initializer for a vector of type %qT",
5047                    TREE_TYPE (d->cur->value), type);
5048           value = error_mark_node;
5049         }
5050       ++d->cur;
5051       return value;
5052     }
5053
5054   /* For a vector, we initialize it as an array of the appropriate size.  */
5055   if (TREE_CODE (type) == VECTOR_TYPE)
5056     max_index = size_int (TYPE_VECTOR_SUBPARTS (type) - 1);
5057
5058   return reshape_init_array_1 (TREE_TYPE (type), max_index, d, complain);
5059 }
5060
5061 /* Subroutine of reshape_init_r, processes the initializers for classes
5062    or union. Parameters are the same of reshape_init_r.  */
5063
5064 static tree
5065 reshape_init_class (tree type, reshape_iter *d, bool first_initializer_p,
5066                     tsubst_flags_t complain)
5067 {
5068   tree field;
5069   tree new_init;
5070
5071   gcc_assert (CLASS_TYPE_P (type));
5072
5073   /* The initializer for a class is always a CONSTRUCTOR.  */
5074   new_init = build_constructor (init_list_type_node, NULL);
5075   field = next_initializable_field (TYPE_FIELDS (type));
5076
5077   if (!field)
5078     {
5079       /* [dcl.init.aggr]
5080
5081         An initializer for an aggregate member that is an
5082         empty class shall have the form of an empty
5083         initializer-list {}.  */
5084       if (!first_initializer_p)
5085         {
5086           if (complain & tf_error)
5087             error ("initializer for %qT must be brace-enclosed", type);
5088           return error_mark_node;
5089         }
5090       return new_init;
5091     }
5092
5093   /* Loop through the initializable fields, gathering initializers.  */
5094   while (d->cur != d->end)
5095     {
5096       tree field_init;
5097
5098       /* Handle designated initializers, as an extension.  */
5099       if (d->cur->index)
5100         {
5101           if (TREE_CODE (d->cur->index) == INTEGER_CST)
5102             {
5103               if (complain & tf_error)
5104                 error ("%<[%E] =%> used in a GNU-style designated initializer"
5105                        " for class %qT", d->cur->index, type);
5106               return error_mark_node;
5107             }
5108
5109           if (TREE_CODE (d->cur->index) == FIELD_DECL)
5110             /* We already reshaped this.  */
5111             gcc_assert (d->cur->index == field);
5112           else
5113             field = lookup_field_1 (type, d->cur->index, /*want_type=*/false);
5114
5115           if (!field || TREE_CODE (field) != FIELD_DECL)
5116             {
5117               if (complain & tf_error)
5118                 error ("%qT has no non-static data member named %qD", type,
5119                        d->cur->index);
5120               return error_mark_node;
5121             }
5122         }
5123
5124       /* If we processed all the member of the class, we are done.  */
5125       if (!field)
5126         break;
5127
5128       field_init = reshape_init_r (TREE_TYPE (field), d,
5129                                    /*first_initializer_p=*/false, complain);
5130       if (field_init == error_mark_node)
5131         return error_mark_node;
5132
5133       CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init), field, field_init);
5134
5135       /* [dcl.init.aggr]
5136
5137         When a union  is  initialized with a brace-enclosed
5138         initializer, the braces shall only contain an
5139         initializer for the first member of the union.  */
5140       if (TREE_CODE (type) == UNION_TYPE)
5141         break;
5142
5143       field = next_initializable_field (DECL_CHAIN (field));
5144     }
5145
5146   return new_init;
5147 }
5148
5149 /* Subroutine of reshape_init_r.  We're in a context where C99 initializer
5150    designators are not valid; either complain or return true to indicate
5151    that reshape_init_r should return error_mark_node.  */
5152
5153 static bool
5154 has_designator_problem (reshape_iter *d, tsubst_flags_t complain)
5155 {
5156   if (d->cur->index)
5157     {
5158       if (complain & tf_error)
5159         error ("C99 designator %qE outside aggregate initializer",
5160                d->cur->index);
5161       else
5162         return true;
5163     }
5164   return false;
5165 }
5166
5167 /* Subroutine of reshape_init, which processes a single initializer (part of
5168    a CONSTRUCTOR). TYPE is the type of the variable being initialized, D is the
5169    iterator within the CONSTRUCTOR which points to the initializer to process.
5170    FIRST_INITIALIZER_P is true if this is the first initializer of the
5171    outermost CONSTRUCTOR node.  */
5172
5173 static tree
5174 reshape_init_r (tree type, reshape_iter *d, bool first_initializer_p,
5175                 tsubst_flags_t complain)
5176 {
5177   tree init = d->cur->value;
5178
5179   if (error_operand_p (init))
5180     return error_mark_node;
5181
5182   if (first_initializer_p && !CP_AGGREGATE_TYPE_P (type)
5183       && has_designator_problem (d, complain))
5184     return error_mark_node;
5185
5186   if (TREE_CODE (type) == COMPLEX_TYPE)
5187     {
5188       /* A complex type can be initialized from one or two initializers,
5189          but braces are not elided.  */
5190       d->cur++;
5191       if (BRACE_ENCLOSED_INITIALIZER_P (init))
5192         {
5193           if (CONSTRUCTOR_NELTS (init) > 2)
5194             {
5195               if (complain & tf_error)
5196                 error ("too many initializers for %qT", type);
5197               else
5198                 return error_mark_node;
5199             }
5200         }
5201       else if (first_initializer_p && d->cur != d->end)
5202         {
5203           VEC(constructor_elt, gc) *v = 0;
5204           CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
5205           CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, d->cur->value);
5206           if (has_designator_problem (d, complain))
5207             return error_mark_node;
5208           d->cur++;
5209           init = build_constructor (init_list_type_node, v);
5210         }
5211       return init;
5212     }
5213
5214   /* A non-aggregate type is always initialized with a single
5215      initializer.  */
5216   if (!CP_AGGREGATE_TYPE_P (type))
5217     {
5218       /* It is invalid to initialize a non-aggregate type with a
5219          brace-enclosed initializer before C++0x.
5220          We need to check for BRACE_ENCLOSED_INITIALIZER_P here because
5221          of g++.old-deja/g++.mike/p7626.C: a pointer-to-member constant is
5222          a CONSTRUCTOR (with a record type).  */
5223       if (TREE_CODE (init) == CONSTRUCTOR
5224           && BRACE_ENCLOSED_INITIALIZER_P (init))  /* p7626.C */
5225         {
5226           if (SCALAR_TYPE_P (type))
5227             {
5228               if (complain & tf_error)
5229                 error ("braces around scalar initializer for type %qT", type);
5230               init = error_mark_node;
5231             }
5232           else
5233             maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
5234         }
5235
5236       d->cur++;
5237       return init;
5238     }
5239
5240   /* [dcl.init.aggr]
5241
5242      All implicit type conversions (clause _conv_) are considered when
5243      initializing the aggregate member with an initializer from an
5244      initializer-list.  If the initializer can initialize a member,
5245      the member is initialized.  Otherwise, if the member is itself a
5246      non-empty subaggregate, brace elision is assumed and the
5247      initializer is considered for the initialization of the first
5248      member of the subaggregate.  */
5249   if (TREE_CODE (init) != CONSTRUCTOR
5250       /* But don't try this for the first initializer, since that would be
5251          looking through the outermost braces; A a2 = { a1 }; is not a
5252          valid aggregate initialization.  */
5253       && !first_initializer_p
5254       && (same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (init))
5255           || can_convert_arg (type, TREE_TYPE (init), init, LOOKUP_NORMAL,
5256                               complain)))
5257     {
5258       d->cur++;
5259       return init;
5260     }
5261
5262   /* [dcl.init.string]
5263
5264       A char array (whether plain char, signed char, or unsigned char)
5265       can be initialized by a string-literal (optionally enclosed in
5266       braces); a wchar_t array can be initialized by a wide
5267       string-literal (optionally enclosed in braces).  */
5268   if (TREE_CODE (type) == ARRAY_TYPE
5269       && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type))))
5270     {
5271       tree str_init = init;
5272
5273       /* Strip one level of braces if and only if they enclose a single
5274          element (as allowed by [dcl.init.string]).  */
5275       if (!first_initializer_p
5276           && TREE_CODE (str_init) == CONSTRUCTOR
5277           && VEC_length (constructor_elt, CONSTRUCTOR_ELTS (str_init)) == 1)
5278         {
5279           str_init = VEC_index (constructor_elt,
5280                                 CONSTRUCTOR_ELTS (str_init), 0).value;
5281         }
5282
5283       /* If it's a string literal, then it's the initializer for the array
5284          as a whole. Otherwise, continue with normal initialization for
5285          array types (one value per array element).  */
5286       if (TREE_CODE (str_init) == STRING_CST)
5287         {
5288           if (has_designator_problem (d, complain))
5289             return error_mark_node;
5290           d->cur++;
5291           return str_init;
5292         }
5293     }
5294
5295   /* The following cases are about aggregates. If we are not within a full
5296      initializer already, and there is not a CONSTRUCTOR, it means that there
5297      is a missing set of braces (that is, we are processing the case for
5298      which reshape_init exists).  */
5299   if (!first_initializer_p)
5300     {
5301       if (TREE_CODE (init) == CONSTRUCTOR)
5302         {
5303           if (TREE_TYPE (init) && TYPE_PTRMEMFUNC_P (TREE_TYPE (init)))
5304             /* There is no need to reshape pointer-to-member function
5305                initializers, as they are always constructed correctly
5306                by the front end.  */
5307            ;
5308           else if (COMPOUND_LITERAL_P (init))
5309           /* For a nested compound literal, there is no need to reshape since
5310              brace elision is not allowed. Even if we decided to allow it,
5311              we should add a call to reshape_init in finish_compound_literal,
5312              before calling digest_init, so changing this code would still
5313              not be necessary.  */
5314             gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (init));
5315           else
5316             {
5317               ++d->cur;
5318               gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (init));
5319               return reshape_init (type, init, complain);
5320             }
5321         }
5322
5323       warning (OPT_Wmissing_braces, "missing braces around initializer for %qT",
5324                type);
5325     }
5326
5327   /* Dispatch to specialized routines.  */
5328   if (CLASS_TYPE_P (type))
5329     return reshape_init_class (type, d, first_initializer_p, complain);
5330   else if (TREE_CODE (type) == ARRAY_TYPE)
5331     return reshape_init_array (type, d, complain);
5332   else if (TREE_CODE (type) == VECTOR_TYPE)
5333     return reshape_init_vector (type, d, complain);
5334   else
5335     gcc_unreachable();
5336 }
5337
5338 /* Undo the brace-elision allowed by [dcl.init.aggr] in a
5339    brace-enclosed aggregate initializer.
5340
5341    INIT is the CONSTRUCTOR containing the list of initializers describing
5342    a brace-enclosed initializer for an entity of the indicated aggregate TYPE.
5343    It may not presently match the shape of the TYPE; for example:
5344
5345      struct S { int a; int b; };
5346      struct S a[] = { 1, 2, 3, 4 };
5347
5348    Here INIT will hold a VEC of four elements, rather than a
5349    VEC of two elements, each itself a VEC of two elements.  This
5350    routine transforms INIT from the former form into the latter.  The
5351    revised CONSTRUCTOR node is returned.  */
5352
5353 tree
5354 reshape_init (tree type, tree init, tsubst_flags_t complain)
5355 {
5356   VEC(constructor_elt, gc) *v;
5357   reshape_iter d;
5358   tree new_init;
5359
5360   gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (init));
5361
5362   v = CONSTRUCTOR_ELTS (init);
5363
5364   /* An empty constructor does not need reshaping, and it is always a valid
5365      initializer.  */
5366   if (VEC_empty (constructor_elt, v))
5367     return init;
5368
5369   /* Recurse on this CONSTRUCTOR.  */
5370   d.cur = &VEC_index (constructor_elt, v, 0);
5371   d.end = d.cur + VEC_length (constructor_elt, v);
5372
5373   new_init = reshape_init_r (type, &d, true, complain);
5374   if (new_init == error_mark_node)
5375     return error_mark_node;
5376
5377   /* Make sure all the element of the constructor were used. Otherwise,
5378      issue an error about exceeding initializers.  */
5379   if (d.cur != d.end)
5380     {
5381       if (complain & tf_error)
5382         error ("too many initializers for %qT", type);
5383       else
5384         return error_mark_node;
5385     }
5386
5387   return new_init;
5388 }
5389
5390 /* Verify array initializer.  Returns true if errors have been reported.  */
5391
5392 bool
5393 check_array_initializer (tree decl, tree type, tree init)
5394 {
5395   tree element_type = TREE_TYPE (type);
5396
5397   /* The array type itself need not be complete, because the
5398      initializer may tell us how many elements are in the array.
5399      But, the elements of the array must be complete.  */
5400   if (!COMPLETE_TYPE_P (complete_type (element_type)))
5401     {
5402       if (decl)
5403         error ("elements of array %q#D have incomplete type", decl);
5404       else
5405         error ("elements of array %q#T have incomplete type", type);
5406       return true;
5407     }
5408   /* It is not valid to initialize a VLA.  */
5409   if (init
5410       && ((COMPLETE_TYPE_P (type) && !TREE_CONSTANT (TYPE_SIZE (type)))
5411           || !TREE_CONSTANT (TYPE_SIZE (element_type))))
5412     {
5413       if (decl)
5414         error ("variable-sized object %qD may not be initialized", decl);
5415       else
5416         error ("variable-sized compound literal");
5417       return true;
5418     }
5419   return false;
5420 }
5421
5422 /* Subroutine of check_initializer; args are passed down from that function.
5423    Set stmts_are_full_exprs_p to 1 across a call to build_aggr_init.  */
5424
5425 static tree
5426 build_aggr_init_full_exprs (tree decl, tree init, int flags)
5427      
5428 {
5429   gcc_assert (stmts_are_full_exprs_p ());
5430   return build_aggr_init (decl, init, flags, tf_warning_or_error);
5431 }
5432
5433 /* Verify INIT (the initializer for DECL), and record the
5434    initialization in DECL_INITIAL, if appropriate.  CLEANUP is as for
5435    grok_reference_init.
5436
5437    If the return value is non-NULL, it is an expression that must be
5438    evaluated dynamically to initialize DECL.  */
5439
5440 static tree
5441 check_initializer (tree decl, tree init, int flags, VEC(tree,gc) **cleanups)
5442 {
5443   tree type = TREE_TYPE (decl);
5444   tree init_code = NULL;
5445   tree extra_init = NULL_TREE;
5446   tree core_type;
5447
5448   /* Things that are going to be initialized need to have complete
5449      type.  */
5450   TREE_TYPE (decl) = type = complete_type (TREE_TYPE (decl));
5451
5452   if (DECL_HAS_VALUE_EXPR_P (decl))
5453     {
5454       /* A variable with DECL_HAS_VALUE_EXPR_P set is just a placeholder,
5455          it doesn't have storage to be initialized.  */
5456       gcc_assert (init == NULL_TREE);
5457       return NULL_TREE;
5458     }
5459
5460   if (type == error_mark_node)
5461     /* We will have already complained.  */
5462     return NULL_TREE;
5463
5464   if (TREE_CODE (type) == ARRAY_TYPE)
5465     {
5466       if (check_array_initializer (decl, type, init))
5467         return NULL_TREE;
5468     }
5469   else if (!COMPLETE_TYPE_P (type))
5470     {
5471       error ("%q#D has incomplete type", decl);
5472       TREE_TYPE (decl) = error_mark_node;
5473       return NULL_TREE;
5474     }
5475   else
5476     /* There is no way to make a variable-sized class type in GNU C++.  */
5477     gcc_assert (TREE_CONSTANT (TYPE_SIZE (type)));
5478
5479   if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
5480     {
5481       int init_len = VEC_length (constructor_elt, CONSTRUCTOR_ELTS (init));
5482       if (SCALAR_TYPE_P (type))
5483         {
5484           if (init_len == 0)
5485             {
5486               maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
5487               init = build_zero_init (type, NULL_TREE, false);
5488             }
5489           else if (init_len != 1 && TREE_CODE (type) != COMPLEX_TYPE)
5490             {
5491               error ("scalar object %qD requires one element in initializer",
5492                      decl);
5493               TREE_TYPE (decl) = error_mark_node;
5494               return NULL_TREE;
5495             }
5496         }
5497     }
5498
5499   if (TREE_CODE (decl) == CONST_DECL)
5500     {
5501       gcc_assert (TREE_CODE (type) != REFERENCE_TYPE);
5502
5503       DECL_INITIAL (decl) = init;
5504
5505       gcc_assert (init != NULL_TREE);
5506       init = NULL_TREE;
5507     }
5508   else if (!init && DECL_REALLY_EXTERN (decl))
5509     ;
5510   else if (init || type_build_ctor_call (type)
5511            || TREE_CODE (type) == REFERENCE_TYPE)
5512     {
5513       if (TREE_CODE (type) == REFERENCE_TYPE)
5514         {
5515           init = grok_reference_init (decl, type, init, flags);
5516           flags |= LOOKUP_ALREADY_DIGESTED;
5517         }
5518       else if (!init)
5519         check_for_uninitialized_const_var (decl);
5520       /* Do not reshape constructors of vectors (they don't need to be
5521          reshaped.  */
5522       else if (BRACE_ENCLOSED_INITIALIZER_P (init))
5523         {
5524           if (is_std_init_list (type))
5525             {
5526               init = perform_implicit_conversion (type, init,
5527                                                   tf_warning_or_error);
5528               flags |= LOOKUP_ALREADY_DIGESTED;
5529             }
5530           else if (TYPE_NON_AGGREGATE_CLASS (type))
5531             {
5532               /* Don't reshape if the class has constructors.  */
5533               if (cxx_dialect == cxx98)
5534                 error ("in C++98 %qD must be initialized by constructor, "
5535                        "not by %<{...}%>",
5536                        decl);
5537             }
5538           else if (TREE_CODE (type) == VECTOR_TYPE && TYPE_VECTOR_OPAQUE (type))
5539             {
5540               error ("opaque vector types cannot be initialized");
5541               init = error_mark_node;
5542             }
5543           else
5544             {
5545               init = reshape_init (type, init, tf_warning_or_error);
5546               if (SCALAR_TYPE_P (type))
5547                 check_narrowing (type, init);
5548             }
5549         }
5550
5551       /* If DECL has an array type without a specific bound, deduce the
5552          array size from the initializer.  */
5553       maybe_deduce_size_from_array_init (decl, init);
5554       type = TREE_TYPE (decl);
5555       if (type == error_mark_node)
5556         return NULL_TREE;
5557
5558       if ((type_build_ctor_call (type) || CLASS_TYPE_P (type))
5559           && !(flags & LOOKUP_ALREADY_DIGESTED)
5560           && !(init && BRACE_ENCLOSED_INITIALIZER_P (init)
5561                && CP_AGGREGATE_TYPE_P (type)))
5562         {
5563           init_code = build_aggr_init_full_exprs (decl, init, flags);
5564
5565           /* If this is a constexpr initializer, expand_default_init will
5566              have returned an INIT_EXPR rather than a CALL_EXPR.  In that
5567              case, pull the initializer back out and pass it down into
5568              store_init_value.  */
5569           while (TREE_CODE (init_code) == EXPR_STMT
5570                  || TREE_CODE (init_code) == CONVERT_EXPR)
5571             init_code = TREE_OPERAND (init_code, 0);
5572           if (TREE_CODE (init_code) == INIT_EXPR)
5573             {
5574               init = TREE_OPERAND (init_code, 1);
5575               init_code = NULL_TREE;
5576               /* Don't call digest_init; it's unnecessary and will complain
5577                  about aggregate initialization of non-aggregate classes.  */
5578               flags |= LOOKUP_ALREADY_DIGESTED;
5579             }
5580           else if (DECL_DECLARED_CONSTEXPR_P (decl))
5581             {
5582               /* Declared constexpr, but no suitable initializer; massage
5583                  init appropriately so we can pass it into store_init_value
5584                  for the error.  */
5585               if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
5586                 init = finish_compound_literal (type, init,
5587                                                 tf_warning_or_error);
5588               else if (CLASS_TYPE_P (type)
5589                        && (!init || TREE_CODE (init) == TREE_LIST))
5590                 {
5591                   init = build_functional_cast (type, init, tf_none);
5592                   if (init != error_mark_node)
5593                     TARGET_EXPR_DIRECT_INIT_P (init) = true;
5594                 }
5595               init_code = NULL_TREE;
5596             }
5597           else
5598             init = NULL_TREE;
5599         }
5600
5601       if (init && TREE_CODE (init) != TREE_VEC)
5602         {
5603           /* In aggregate initialization of a variable, each element
5604              initialization is a full-expression because there is no
5605              enclosing expression.  */
5606           gcc_assert (stmts_are_full_exprs_p ());
5607
5608           init_code = store_init_value (decl, init, cleanups, flags);
5609
5610           if (pedantic && TREE_CODE (type) == ARRAY_TYPE
5611               && DECL_INITIAL (decl)
5612               && TREE_CODE (DECL_INITIAL (decl)) == STRING_CST
5613               && PAREN_STRING_LITERAL_P (DECL_INITIAL (decl)))
5614             warning (0, "array %qD initialized by parenthesized string literal %qE",
5615                      decl, DECL_INITIAL (decl));
5616           init = NULL;
5617         }
5618     }
5619   else
5620     {
5621       if (CLASS_TYPE_P (core_type = strip_array_types (type))
5622           && (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type)
5623               || CLASSTYPE_REF_FIELDS_NEED_INIT (core_type)))
5624         diagnose_uninitialized_cst_or_ref_member (core_type, /*using_new=*/false,
5625                                                   /*complain=*/true);
5626
5627       check_for_uninitialized_const_var (decl);
5628     }
5629
5630   if (init && init != error_mark_node)
5631     init_code = build2 (INIT_EXPR, type, decl, init);
5632
5633   if (extra_init)
5634     init_code = add_stmt_to_compound (extra_init, init_code);
5635
5636   if (init_code && DECL_IN_AGGR_P (decl))
5637     {
5638       static int explained = 0;
5639
5640       if (cxx_dialect < cxx0x)
5641         error ("initializer invalid for static member with constructor");
5642       else
5643         error ("non-constant in-class initialization invalid for static "
5644                "member %qD", decl);
5645       if (!explained)
5646         {
5647           error ("(an out of class initialization is required)");
5648           explained = 1;
5649         }
5650     }
5651
5652   return init_code;
5653 }
5654
5655 /* If DECL is not a local variable, give it RTL.  */
5656
5657 static void
5658 make_rtl_for_nonlocal_decl (tree decl, tree init, const char* asmspec)
5659 {
5660   int toplev = toplevel_bindings_p ();
5661   int defer_p;
5662   const char *filename;
5663
5664   /* Set the DECL_ASSEMBLER_NAME for the object.  */
5665   if (asmspec)
5666     {
5667       /* The `register' keyword, when used together with an
5668          asm-specification, indicates that the variable should be
5669          placed in a particular register.  */
5670       if (TREE_CODE (decl) == VAR_DECL && DECL_REGISTER (decl))
5671         {
5672           set_user_assembler_name (decl, asmspec);
5673           DECL_HARD_REGISTER (decl) = 1;
5674         }
5675       else
5676         {
5677           if (TREE_CODE (decl) == FUNCTION_DECL
5678               && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
5679             set_builtin_user_assembler_name (decl, asmspec);
5680           set_user_assembler_name (decl, asmspec);
5681         }
5682     }
5683
5684   /* Handle non-variables up front.  */
5685   if (TREE_CODE (decl) != VAR_DECL)
5686     {
5687       rest_of_decl_compilation (decl, toplev, at_eof);
5688       return;
5689     }
5690
5691   /* If we see a class member here, it should be a static data
5692      member.  */
5693   if (DECL_LANG_SPECIFIC (decl) && DECL_IN_AGGR_P (decl))
5694     {
5695       gcc_assert (TREE_STATIC (decl));
5696       /* An in-class declaration of a static data member should be
5697          external; it is only a declaration, and not a definition.  */
5698       if (init == NULL_TREE)
5699         gcc_assert (DECL_EXTERNAL (decl) || !TREE_PUBLIC (decl));
5700     }
5701
5702   /* We don't create any RTL for local variables.  */
5703   if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
5704     return;
5705
5706   /* We defer emission of local statics until the corresponding
5707      DECL_EXPR is expanded.  */
5708   defer_p = DECL_FUNCTION_SCOPE_P (decl) || DECL_VIRTUAL_P (decl);
5709
5710   /* We try to defer namespace-scope static constants so that they are
5711      not emitted into the object file unnecessarily.  */
5712   filename = input_filename;
5713   if (!DECL_VIRTUAL_P (decl)
5714       && TREE_READONLY (decl)
5715       && DECL_INITIAL (decl) != NULL_TREE
5716       && DECL_INITIAL (decl) != error_mark_node
5717       && filename != NULL
5718       && ! EMPTY_CONSTRUCTOR_P (DECL_INITIAL (decl))
5719       && toplev
5720       && !TREE_PUBLIC (decl))
5721     {
5722       /* Fool with the linkage of static consts according to #pragma
5723          interface.  */
5724       struct c_fileinfo *finfo = get_fileinfo (filename);
5725       if (!finfo->interface_unknown && !TREE_PUBLIC (decl))
5726         {
5727           TREE_PUBLIC (decl) = 1;
5728           DECL_EXTERNAL (decl) = finfo->interface_only;
5729         }
5730
5731       defer_p = 1;
5732     }
5733   /* Likewise for template instantiations.  */
5734   else if (DECL_LANG_SPECIFIC (decl)
5735            && DECL_IMPLICIT_INSTANTIATION (decl))
5736     defer_p = 1;
5737
5738   /* If we're not deferring, go ahead and assemble the variable.  */
5739   if (!defer_p)
5740     rest_of_decl_compilation (decl, toplev, at_eof);
5741 }
5742
5743 /* walk_tree helper for wrap_temporary_cleanups, below.  */
5744
5745 static tree
5746 wrap_cleanups_r (tree *stmt_p, int *walk_subtrees, void *data)
5747 {
5748   /* Stop at types or full-expression boundaries.  */
5749   if (TYPE_P (*stmt_p)
5750       || TREE_CODE (*stmt_p) == CLEANUP_POINT_EXPR)
5751     {
5752       *walk_subtrees = 0;
5753       return NULL_TREE;
5754     }
5755
5756   if (TREE_CODE (*stmt_p) == TARGET_EXPR)
5757     {
5758       tree guard = (tree)data;
5759       tree tcleanup = TARGET_EXPR_CLEANUP (*stmt_p);
5760
5761       tcleanup = build2 (TRY_CATCH_EXPR, void_type_node, tcleanup, guard);
5762       /* Tell honor_protect_cleanup_actions to handle this as a separate
5763          cleanup.  */
5764       TRY_CATCH_IS_CLEANUP (tcleanup) = 1;
5765  
5766       TARGET_EXPR_CLEANUP (*stmt_p) = tcleanup;
5767     }
5768
5769   return NULL_TREE;
5770 }
5771
5772 /* We're initializing a local variable which has a cleanup GUARD.  If there
5773    are any temporaries used in the initializer INIT of this variable, we
5774    need to wrap their cleanups with TRY_CATCH_EXPR (, GUARD) so that the
5775    variable will be cleaned up properly if one of them throws.
5776
5777    Unfortunately, there's no way to express this properly in terms of
5778    nesting, as the regions for the temporaries overlap the region for the
5779    variable itself; if there are two temporaries, the variable needs to be
5780    the first thing destroyed if either of them throws.  However, we only
5781    want to run the variable's cleanup if it actually got constructed.  So
5782    we need to guard the temporary cleanups with the variable's cleanup if
5783    they are run on the normal path, but not if they are run on the
5784    exceptional path.  We implement this by telling
5785    honor_protect_cleanup_actions to strip the variable cleanup from the
5786    exceptional path.  */
5787
5788 static void
5789 wrap_temporary_cleanups (tree init, tree guard)
5790 {
5791   cp_walk_tree_without_duplicates (&init, wrap_cleanups_r, (void *)guard);
5792 }
5793
5794 /* Generate code to initialize DECL (a local variable).  */
5795
5796 static void
5797 initialize_local_var (tree decl, tree init)
5798 {
5799   tree type = TREE_TYPE (decl);
5800   tree cleanup;
5801   int already_used;
5802
5803   gcc_assert (TREE_CODE (decl) == VAR_DECL
5804               || TREE_CODE (decl) == RESULT_DECL);
5805   gcc_assert (!TREE_STATIC (decl));
5806
5807   if (DECL_SIZE (decl) == NULL_TREE)
5808     {
5809       /* If we used it already as memory, it must stay in memory.  */
5810       DECL_INITIAL (decl) = NULL_TREE;
5811       TREE_ADDRESSABLE (decl) = TREE_USED (decl);
5812       return;
5813     }
5814
5815   if (type == error_mark_node)
5816     return;
5817
5818   /* Compute and store the initial value.  */
5819   already_used = TREE_USED (decl) || TREE_USED (type);
5820   if (TREE_USED (type))
5821     DECL_READ_P (decl) = 1;
5822
5823   /* Generate a cleanup, if necessary.  */
5824   cleanup = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
5825
5826   /* Perform the initialization.  */
5827   if (init)
5828     {
5829       if (TREE_CODE (init) == INIT_EXPR
5830           && !TREE_SIDE_EFFECTS (TREE_OPERAND (init, 1)))
5831         {
5832           /* Stick simple initializers in DECL_INITIAL so that
5833              -Wno-init-self works (c++/34772).  */
5834           gcc_assert (TREE_OPERAND (init, 0) == decl);
5835           DECL_INITIAL (decl) = TREE_OPERAND (init, 1);
5836         }
5837       else
5838         {
5839           int saved_stmts_are_full_exprs_p;
5840
5841           /* If we're only initializing a single object, guard the
5842              destructors of any temporaries used in its initializer with
5843              its destructor.  This isn't right for arrays because each
5844              element initialization is a full-expression.  */
5845           if (cleanup && TREE_CODE (type) != ARRAY_TYPE)
5846             wrap_temporary_cleanups (init, cleanup);
5847
5848           gcc_assert (building_stmt_list_p ());
5849           saved_stmts_are_full_exprs_p = stmts_are_full_exprs_p ();
5850           current_stmt_tree ()->stmts_are_full_exprs_p = 1;
5851           finish_expr_stmt (init);
5852           current_stmt_tree ()->stmts_are_full_exprs_p =
5853             saved_stmts_are_full_exprs_p;
5854         }
5855     }
5856
5857   /* Set this to 0 so we can tell whether an aggregate which was
5858      initialized was ever used.  Don't do this if it has a
5859      destructor, so we don't complain about the 'resource
5860      allocation is initialization' idiom.  Now set
5861      attribute((unused)) on types so decls of that type will be
5862      marked used. (see TREE_USED, above.)  */
5863   if (TYPE_NEEDS_CONSTRUCTING (type)
5864       && ! already_used
5865       && TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
5866       && DECL_NAME (decl))
5867     TREE_USED (decl) = 0;
5868   else if (already_used)
5869     TREE_USED (decl) = 1;
5870
5871   if (cleanup)
5872     finish_decl_cleanup (decl, cleanup);
5873 }
5874
5875 /* DECL is a VAR_DECL for a compiler-generated variable with static
5876    storage duration (like a virtual table) whose initializer is a
5877    compile-time constant.  Initialize the variable and provide it to the
5878    back end.  */
5879
5880 void
5881 initialize_artificial_var (tree decl, VEC(constructor_elt,gc) *v)
5882 {
5883   tree init;
5884   gcc_assert (DECL_ARTIFICIAL (decl));
5885   init = build_constructor (TREE_TYPE (decl), v);
5886   gcc_assert (TREE_CODE (init) == CONSTRUCTOR);
5887   DECL_INITIAL (decl) = init;
5888   DECL_INITIALIZED_P (decl) = 1;
5889   determine_visibility (decl);
5890   layout_var_decl (decl);
5891   maybe_commonize_var (decl);
5892   make_rtl_for_nonlocal_decl (decl, init, /*asmspec=*/NULL);
5893 }
5894
5895 /* INIT is the initializer for a variable, as represented by the
5896    parser.  Returns true iff INIT is type-dependent.  */
5897
5898 static bool
5899 type_dependent_init_p (tree init)
5900 {
5901   if (TREE_CODE (init) == TREE_LIST)
5902     /* A parenthesized initializer, e.g.: int i (3, 2); ? */
5903     return any_type_dependent_elements_p (init);
5904   else if (TREE_CODE (init) == CONSTRUCTOR)
5905   /* A brace-enclosed initializer, e.g.: int i = { 3 }; ? */
5906     {
5907       VEC(constructor_elt, gc) *elts;
5908       size_t nelts;
5909       size_t i;
5910
5911       elts = CONSTRUCTOR_ELTS (init);
5912       nelts = VEC_length (constructor_elt, elts);
5913       for (i = 0; i < nelts; ++i)
5914         if (type_dependent_init_p (VEC_index (constructor_elt,
5915                                               elts, i).value))
5916           return true;
5917     }
5918   else
5919     /* It must be a simple expression, e.g., int i = 3;  */
5920     return type_dependent_expression_p (init);
5921
5922   return false;
5923 }
5924
5925 /* INIT is the initializer for a variable, as represented by the
5926    parser.  Returns true iff INIT is value-dependent.  */
5927
5928 static bool
5929 value_dependent_init_p (tree init)
5930 {
5931   if (TREE_CODE (init) == TREE_LIST)
5932     /* A parenthesized initializer, e.g.: int i (3, 2); ? */
5933     return any_value_dependent_elements_p (init);
5934   else if (TREE_CODE (init) == CONSTRUCTOR)
5935   /* A brace-enclosed initializer, e.g.: int i = { 3 }; ? */
5936     {
5937       VEC(constructor_elt, gc) *elts;
5938       size_t nelts;
5939       size_t i;
5940
5941       elts = CONSTRUCTOR_ELTS (init);
5942       nelts = VEC_length (constructor_elt, elts);
5943       for (i = 0; i < nelts; ++i)
5944         if (value_dependent_init_p (VEC_index (constructor_elt,
5945                                                elts, i).value))
5946           return true;
5947     }
5948   else
5949     /* It must be a simple expression, e.g., int i = 3;  */
5950     return value_dependent_expression_p (init);
5951   
5952   return false;
5953 }
5954
5955 /* Finish processing of a declaration;
5956    install its line number and initial value.
5957    If the length of an array type is not known before,
5958    it must be determined now, from the initial value, or it is an error.
5959
5960    INIT is the initializer (if any) for DECL.  If INIT_CONST_EXPR_P is
5961    true, then INIT is an integral constant expression.
5962
5963    FLAGS is LOOKUP_ONLYCONVERTING if the = init syntax was used, else 0
5964    if the (init) syntax was used.  */
5965
5966 void
5967 cp_finish_decl (tree decl, tree init, bool init_const_expr_p,
5968                 tree asmspec_tree, int flags)
5969 {
5970   tree type;
5971   VEC(tree,gc) *cleanups = NULL;
5972   const char *asmspec = NULL;
5973   int was_readonly = 0;
5974   bool var_definition_p = false;
5975   tree auto_node;
5976
5977   if (decl == error_mark_node)
5978     return;
5979   else if (! decl)
5980     {
5981       if (init)
5982         error ("assignment (not initialization) in declaration");
5983       return;
5984     }
5985
5986   gcc_assert (TREE_CODE (decl) != RESULT_DECL);
5987   /* Parameters are handled by store_parm_decls, not cp_finish_decl.  */
5988   gcc_assert (TREE_CODE (decl) != PARM_DECL);
5989
5990   type = TREE_TYPE (decl);
5991   if (type == error_mark_node)
5992     return;
5993
5994   /* If a name was specified, get the string.  */
5995   if (at_namespace_scope_p ())
5996     asmspec_tree = maybe_apply_renaming_pragma (decl, asmspec_tree);
5997   if (asmspec_tree && asmspec_tree != error_mark_node)
5998     asmspec = TREE_STRING_POINTER (asmspec_tree);
5999
6000   if (current_class_type
6001       && CP_DECL_CONTEXT (decl) == current_class_type
6002       && TYPE_BEING_DEFINED (current_class_type)
6003       && !CLASSTYPE_TEMPLATE_INSTANTIATION (current_class_type)
6004       && (DECL_INITIAL (decl) || init))
6005     DECL_INITIALIZED_IN_CLASS_P (decl) = 1;
6006
6007   if (TREE_CODE (decl) != FUNCTION_DECL
6008       && (auto_node = type_uses_auto (type)))
6009     {
6010       tree d_init;
6011       if (init == NULL_TREE)
6012         {
6013           error ("declaration of %q#D has no initializer", decl);
6014           TREE_TYPE (decl) = error_mark_node;
6015           return;
6016         }
6017       d_init = init;
6018       if (TREE_CODE (d_init) == TREE_LIST)
6019         d_init = build_x_compound_expr_from_list (d_init, ELK_INIT,
6020                                                   tf_warning_or_error);
6021       d_init = resolve_nondeduced_context (d_init);
6022       type = TREE_TYPE (decl) = do_auto_deduction (type, d_init,
6023                                                    auto_node);
6024       if (type == error_mark_node)
6025         return;
6026     }
6027
6028   if (!ensure_literal_type_for_constexpr_object (decl))
6029     DECL_DECLARED_CONSTEXPR_P (decl) = 0;
6030
6031   if (TREE_CODE (decl) == VAR_DECL
6032       && DECL_CLASS_SCOPE_P (decl)
6033       && DECL_INITIALIZED_IN_CLASS_P (decl))
6034     check_static_variable_definition (decl, type);
6035
6036   if (init && TREE_CODE (decl) == FUNCTION_DECL)
6037     {
6038       tree clone;
6039       if (init == ridpointers[(int)RID_DELETE])
6040         {
6041           /* FIXME check this is 1st decl.  */
6042           DECL_DELETED_FN (decl) = 1;
6043           DECL_DECLARED_INLINE_P (decl) = 1;
6044           DECL_INITIAL (decl) = error_mark_node;
6045           FOR_EACH_CLONE (clone, decl)
6046             {
6047               DECL_DELETED_FN (clone) = 1;
6048               DECL_DECLARED_INLINE_P (clone) = 1;
6049               DECL_INITIAL (clone) = error_mark_node;
6050             }
6051           init = NULL_TREE;
6052         }
6053       else if (init == ridpointers[(int)RID_DEFAULT])
6054         {
6055           if (defaultable_fn_check (decl))
6056             DECL_DEFAULTED_FN (decl) = 1;
6057           else
6058             DECL_INITIAL (decl) = NULL_TREE;
6059         }
6060     }
6061
6062   if (init && TREE_CODE (decl) == VAR_DECL)
6063     {
6064       DECL_NONTRIVIALLY_INITIALIZED_P (decl) = 1;
6065       /* If DECL is a reference, then we want to know whether init is a
6066          reference constant; init_const_expr_p as passed tells us whether
6067          it's an rvalue constant.  */
6068       if (TREE_CODE (type) == REFERENCE_TYPE)
6069         init_const_expr_p = potential_constant_expression (init);
6070       if (init_const_expr_p)
6071         {
6072           /* Set these flags now for templates.  We'll update the flags in
6073              store_init_value for instantiations.  */
6074           DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
6075           if (decl_maybe_constant_var_p (decl))
6076             TREE_CONSTANT (decl) = 1;
6077         }
6078     }
6079
6080   if (processing_template_decl)
6081     {
6082       bool type_dependent_p;
6083
6084       /* Add this declaration to the statement-tree.  */
6085       if (at_function_scope_p ())
6086         add_decl_expr (decl);
6087
6088       type_dependent_p = dependent_type_p (type);
6089
6090       if (check_for_bare_parameter_packs (init))
6091         {
6092           init = NULL_TREE;
6093           DECL_INITIAL (decl) = NULL_TREE;
6094         }
6095
6096       /* Generally, initializers in templates are expanded when the
6097          template is instantiated.  But, if DECL is a variable constant
6098          then it can be used in future constant expressions, so its value
6099          must be available. */
6100
6101       if (TREE_CODE (decl) != VAR_DECL || dependent_type_p (type))
6102         /* We can't do anything if the decl has dependent type.  */;
6103       else if (init
6104                && init_const_expr_p
6105                && !type_dependent_p
6106                && decl_maybe_constant_var_p (decl)
6107                && !type_dependent_init_p (init)
6108                && !value_dependent_init_p (init))
6109         {
6110           /* This variable seems to be a non-dependent constant, so process
6111              its initializer.  If check_initializer returns non-null the
6112              initialization wasn't constant after all.  */
6113           tree init_code;
6114           cleanups = make_tree_vector ();
6115           init_code = check_initializer (decl, init, flags, &cleanups);
6116           if (init_code == NULL_TREE)
6117             init = NULL_TREE;
6118           release_tree_vector (cleanups);
6119         }
6120       else if (!DECL_PRETTY_FUNCTION_P (decl))
6121         {
6122           /* Deduce array size even if the initializer is dependent.  */
6123           maybe_deduce_size_from_array_init (decl, init);
6124           /* And complain about multiple initializers.  */
6125           if (init && TREE_CODE (init) == TREE_LIST && TREE_CHAIN (init)
6126               && !MAYBE_CLASS_TYPE_P (type))
6127             init = build_x_compound_expr_from_list (init, ELK_INIT,
6128                                                     tf_warning_or_error);
6129         }
6130
6131       if (init)
6132         DECL_INITIAL (decl) = init;
6133       return;
6134     }
6135
6136   /* Just store non-static data member initializers for later.  */
6137   if (init && TREE_CODE (decl) == FIELD_DECL)
6138     DECL_INITIAL (decl) = init;
6139
6140   /* Take care of TYPE_DECLs up front.  */
6141   if (TREE_CODE (decl) == TYPE_DECL)
6142     {
6143       if (type != error_mark_node
6144           && MAYBE_CLASS_TYPE_P (type) && DECL_NAME (decl))
6145         {
6146           if (TREE_TYPE (DECL_NAME (decl)) && TREE_TYPE (decl) != type)
6147             warning (0, "shadowing previous type declaration of %q#D", decl);
6148           set_identifier_type_value (DECL_NAME (decl), decl);
6149         }
6150
6151       /* If we have installed this as the canonical typedef for this
6152          type, and that type has not been defined yet, delay emitting
6153          the debug information for it, as we will emit it later.  */
6154       if (TYPE_MAIN_DECL (TREE_TYPE (decl)) == decl
6155           && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
6156         TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
6157
6158       rest_of_decl_compilation (decl, DECL_FILE_SCOPE_P (decl),
6159                                 at_eof);
6160       return;
6161     }
6162
6163   /* A reference will be modified here, as it is initialized.  */
6164   if (! DECL_EXTERNAL (decl)
6165       && TREE_READONLY (decl)
6166       && TREE_CODE (type) == REFERENCE_TYPE)
6167     {
6168       was_readonly = 1;
6169       TREE_READONLY (decl) = 0;
6170     }
6171
6172   if (TREE_CODE (decl) == VAR_DECL)
6173     {
6174       /* Only variables with trivial initialization and destruction can
6175          have thread-local storage.  */
6176       if (DECL_THREAD_LOCAL_P (decl)
6177           && (type_has_nontrivial_default_init (TREE_TYPE (decl))
6178               || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl))))
6179         error ("%qD cannot be thread-local because it has non-trivial "
6180                "type %qT", decl, TREE_TYPE (decl));
6181       /* If this is a local variable that will need a mangled name,
6182          register it now.  We must do this before processing the
6183          initializer for the variable, since the initialization might
6184          require a guard variable, and since the mangled name of the
6185          guard variable will depend on the mangled name of this
6186          variable.  */
6187       if (DECL_FUNCTION_SCOPE_P (decl)
6188           && TREE_STATIC (decl)
6189           && !DECL_ARTIFICIAL (decl))
6190         {
6191           push_local_name (decl);
6192           if (DECL_CONSTRUCTOR_P (current_function_decl)
6193               || DECL_DESTRUCTOR_P (current_function_decl))
6194             /* Normally local_decls is populated during GIMPLE lowering,
6195                but [cd]tors are never actually compiled directly.  We need
6196                to put statics on the list so we can deal with the label
6197                address extension.  FIXME.  */
6198             add_local_decl (cfun, decl);
6199         }
6200
6201       /* Convert the initializer to the type of DECL, if we have not
6202          already initialized DECL.  */
6203       if (!DECL_INITIALIZED_P (decl)
6204           /* If !DECL_EXTERNAL then DECL is being defined.  In the
6205              case of a static data member initialized inside the
6206              class-specifier, there can be an initializer even if DECL
6207              is *not* defined.  */
6208           && (!DECL_EXTERNAL (decl) || init))
6209         {
6210           if (TYPE_FOR_JAVA (type) && MAYBE_CLASS_TYPE_P (type))
6211             {
6212               tree jclass
6213                 = IDENTIFIER_GLOBAL_VALUE (get_identifier ("jclass"));
6214               /* Allow libjava/prims.cc define primitive classes.  */
6215               if (init != NULL_TREE
6216                   || jclass == NULL_TREE
6217                   || TREE_CODE (jclass) != TYPE_DECL
6218                   || !POINTER_TYPE_P (TREE_TYPE (jclass))
6219                   || !same_type_ignoring_top_level_qualifiers_p
6220                                         (type, TREE_TYPE (TREE_TYPE (jclass))))
6221                 error ("Java object %qD not allocated with %<new%>", decl);
6222               init = NULL_TREE;
6223             }
6224           cleanups = make_tree_vector ();
6225           init = check_initializer (decl, init, flags, &cleanups);
6226           /* Thread-local storage cannot be dynamically initialized.  */
6227           if (DECL_THREAD_LOCAL_P (decl) && init)
6228             {
6229               error ("%qD is thread-local and so cannot be dynamically "
6230                      "initialized", decl);
6231               init = NULL_TREE;
6232             }
6233
6234           /* Check that the initializer for a static data member was a
6235              constant.  Although we check in the parser that the
6236              initializer is an integral constant expression, we do not
6237              simplify division-by-zero at the point at which it
6238              occurs.  Therefore, in:
6239
6240                struct S { static const int i = 7 / 0; };
6241
6242              we issue an error at this point.  It would
6243              probably be better to forbid division by zero in
6244              integral constant expressions.  */
6245           if (DECL_EXTERNAL (decl) && init)
6246             {
6247               error ("%qD cannot be initialized by a non-constant expression"
6248                      " when being declared", decl);
6249               DECL_INITIALIZED_IN_CLASS_P (decl) = 0;
6250               init = NULL_TREE;
6251             }
6252
6253           /* Handle:
6254
6255              [dcl.init]
6256
6257              The memory occupied by any object of static storage
6258              duration is zero-initialized at program startup before
6259              any other initialization takes place.
6260
6261              We cannot create an appropriate initializer until after
6262              the type of DECL is finalized.  If DECL_INITIAL is set,
6263              then the DECL is statically initialized, and any
6264              necessary zero-initialization has already been performed.  */
6265           if (TREE_STATIC (decl) && !DECL_INITIAL (decl))
6266             DECL_INITIAL (decl) = build_zero_init (TREE_TYPE (decl),
6267                                                    /*nelts=*/NULL_TREE,
6268                                                    /*static_storage_p=*/true);
6269           /* Remember that the initialization for this variable has
6270              taken place.  */
6271           DECL_INITIALIZED_P (decl) = 1;
6272           /* This declaration is the definition of this variable,
6273              unless we are initializing a static data member within
6274              the class specifier.  */
6275           if (!DECL_EXTERNAL (decl))
6276             var_definition_p = true;
6277         }
6278       /* If the variable has an array type, lay out the type, even if
6279          there is no initializer.  It is valid to index through the
6280          array, and we must get TYPE_ALIGN set correctly on the array
6281          type.  */
6282       else if (TREE_CODE (type) == ARRAY_TYPE)
6283         layout_type (type);
6284
6285       if (TREE_STATIC (decl)
6286           && !at_function_scope_p ()
6287           && current_function_decl == NULL)
6288         /* So decl is a global variable or a static member of a
6289            non local class. Record the types it uses
6290            so that we can decide later to emit debug info for them.  */
6291         record_types_used_by_current_var_decl (decl);
6292     }
6293   else if (TREE_CODE (decl) == FIELD_DECL
6294            && TYPE_FOR_JAVA (type) && MAYBE_CLASS_TYPE_P (type))
6295     error ("non-static data member %qD has Java class type", decl);
6296
6297   /* Add this declaration to the statement-tree.  This needs to happen
6298      after the call to check_initializer so that the DECL_EXPR for a
6299      reference temp is added before the DECL_EXPR for the reference itself.  */
6300   if (DECL_FUNCTION_SCOPE_P (decl))
6301     add_decl_expr (decl);
6302
6303   /* Let the middle end know about variables and functions -- but not
6304      static data members in uninstantiated class templates.  */
6305   if (TREE_CODE (decl) == VAR_DECL
6306       || TREE_CODE (decl) == FUNCTION_DECL)
6307     {
6308       if (TREE_CODE (decl) == VAR_DECL)
6309         {
6310           layout_var_decl (decl);
6311           maybe_commonize_var (decl);
6312         }
6313
6314       /* This needs to happen after the linkage is set. */
6315       determine_visibility (decl);
6316
6317       if (var_definition_p && TREE_STATIC (decl))
6318         {
6319           /* If a TREE_READONLY variable needs initialization
6320              at runtime, it is no longer readonly and we need to
6321              avoid MEM_READONLY_P being set on RTL created for it.  */
6322           if (init)
6323             {
6324               if (TREE_READONLY (decl))
6325                 TREE_READONLY (decl) = 0;
6326               was_readonly = 0;
6327             }
6328           else if (was_readonly)
6329             TREE_READONLY (decl) = 1;
6330         }
6331
6332       make_rtl_for_nonlocal_decl (decl, init, asmspec);
6333
6334       /* Check for abstractness of the type. Notice that there is no
6335          need to strip array types here since the check for those types
6336          is already done within create_array_type_for_decl.  */
6337       if (TREE_CODE (type) == FUNCTION_TYPE
6338           || TREE_CODE (type) == METHOD_TYPE)
6339         abstract_virtuals_error (decl, TREE_TYPE (type));
6340       else
6341         abstract_virtuals_error (decl, type);
6342
6343       if (TREE_TYPE (decl) == error_mark_node)
6344         /* No initialization required.  */
6345         ;
6346       else if (TREE_CODE (decl) == FUNCTION_DECL)
6347         {
6348           if (init)
6349             {
6350               if (init == ridpointers[(int)RID_DEFAULT])
6351                 {
6352                   /* An out-of-class default definition is defined at
6353                      the point where it is explicitly defaulted.  */
6354                   if (DECL_DELETED_FN (decl))
6355                     maybe_explain_implicit_delete (decl);
6356                   else if (DECL_INITIAL (decl) == error_mark_node)
6357                     synthesize_method (decl);
6358                 }
6359               else
6360                 error ("function %q#D is initialized like a variable", decl);
6361             }
6362           /* else no initialization required.  */
6363         }
6364       else if (DECL_EXTERNAL (decl)
6365                && ! (DECL_LANG_SPECIFIC (decl)
6366                      && DECL_NOT_REALLY_EXTERN (decl)))
6367         {
6368           if (init)
6369             DECL_INITIAL (decl) = init;
6370         }
6371       /* A variable definition.  */
6372       else if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
6373         /* Initialize the local variable.  */
6374         initialize_local_var (decl, init);
6375
6376       /* If a variable is defined, and then a subsequent
6377          definition with external linkage is encountered, we will
6378          get here twice for the same variable.  We want to avoid
6379          calling expand_static_init more than once.  For variables
6380          that are not static data members, we can call
6381          expand_static_init only when we actually process the
6382          initializer.  It is not legal to redeclare a static data
6383          member, so this issue does not arise in that case.  */
6384       else if (var_definition_p && TREE_STATIC (decl))
6385         expand_static_init (decl, init);
6386     }
6387
6388   /* If a CLEANUP_STMT was created to destroy a temporary bound to a
6389      reference, insert it in the statement-tree now.  */
6390   if (cleanups)
6391     {
6392       unsigned i; tree t;
6393       FOR_EACH_VEC_ELT (tree, cleanups, i, t)
6394         push_cleanup (decl, t, false);
6395       release_tree_vector (cleanups);
6396     }
6397
6398   if (was_readonly)
6399     TREE_READONLY (decl) = 1;
6400
6401   invoke_plugin_callbacks (PLUGIN_FINISH_DECL, decl);
6402 }
6403
6404 /* Returns a declaration for a VAR_DECL as if:
6405
6406      extern "C" TYPE NAME;
6407
6408    had been seen.  Used to create compiler-generated global
6409    variables.  */
6410
6411 static tree
6412 declare_global_var (tree name, tree type)
6413 {
6414   tree decl;
6415
6416   push_to_top_level ();
6417   decl = build_decl (input_location, VAR_DECL, name, type);
6418   TREE_PUBLIC (decl) = 1;
6419   DECL_EXTERNAL (decl) = 1;
6420   DECL_ARTIFICIAL (decl) = 1;
6421   /* If the user has explicitly declared this variable (perhaps
6422      because the code we are compiling is part of a low-level runtime
6423      library), then it is possible that our declaration will be merged
6424      with theirs by pushdecl.  */
6425   decl = pushdecl (decl);
6426   cp_finish_decl (decl, NULL_TREE, false, NULL_TREE, 0);
6427   pop_from_top_level ();
6428
6429   return decl;
6430 }
6431
6432 /* Returns the type for the argument to "__cxa_atexit" (or "atexit",
6433    if "__cxa_atexit" is not being used) corresponding to the function
6434    to be called when the program exits.  */
6435
6436 static tree
6437 get_atexit_fn_ptr_type (void)
6438 {
6439   tree fn_type;
6440
6441   if (!atexit_fn_ptr_type_node)
6442     {
6443       tree arg_type;
6444       if (flag_use_cxa_atexit 
6445           && !targetm.cxx.use_atexit_for_cxa_atexit ())
6446         /* The parameter to "__cxa_atexit" is "void (*)(void *)".  */
6447         arg_type = ptr_type_node;
6448       else
6449         /* The parameter to "atexit" is "void (*)(void)".  */
6450         arg_type = NULL_TREE;
6451       
6452       fn_type = build_function_type_list (void_type_node,
6453                                           arg_type, NULL_TREE);
6454       atexit_fn_ptr_type_node = build_pointer_type (fn_type);
6455     }
6456
6457   return atexit_fn_ptr_type_node;
6458 }
6459
6460 /* Returns a pointer to the `atexit' function.  Note that if
6461    FLAG_USE_CXA_ATEXIT is nonzero, then this will actually be the new
6462    `__cxa_atexit' function specified in the IA64 C++ ABI.  */
6463
6464 static tree
6465 get_atexit_node (void)
6466 {
6467   tree atexit_fndecl;
6468   tree fn_type;
6469   tree fn_ptr_type;
6470   const char *name;
6471   bool use_aeabi_atexit;
6472
6473   if (atexit_node)
6474     return atexit_node;
6475
6476   if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
6477     {
6478       /* The declaration for `__cxa_atexit' is:
6479
6480            int __cxa_atexit (void (*)(void *), void *, void *)
6481
6482          We build up the argument types and then the function type
6483          itself.  */
6484       tree argtype0, argtype1, argtype2;
6485
6486       use_aeabi_atexit = targetm.cxx.use_aeabi_atexit ();
6487       /* First, build the pointer-to-function type for the first
6488          argument.  */
6489       fn_ptr_type = get_atexit_fn_ptr_type ();
6490       /* Then, build the rest of the argument types.  */
6491       argtype2 = ptr_type_node;
6492       if (use_aeabi_atexit)
6493         {
6494           argtype1 = fn_ptr_type;
6495           argtype0 = ptr_type_node;
6496         }
6497       else
6498         {
6499           argtype1 = ptr_type_node;
6500           argtype0 = fn_ptr_type;
6501         }
6502       /* And the final __cxa_atexit type.  */
6503       fn_type = build_function_type_list (integer_type_node,
6504                                           argtype0, argtype1, argtype2,
6505                                           NULL_TREE);
6506       fn_ptr_type = build_pointer_type (fn_type);
6507       if (use_aeabi_atexit)
6508         name = "__aeabi_atexit";
6509       else
6510         name = "__cxa_atexit";
6511     }
6512   else
6513     {
6514       /* The declaration for `atexit' is:
6515
6516            int atexit (void (*)());
6517
6518          We build up the argument types and then the function type
6519          itself.  */
6520       fn_ptr_type = get_atexit_fn_ptr_type ();
6521       /* Build the final atexit type.  */
6522       fn_type = build_function_type_list (integer_type_node,
6523                                           fn_ptr_type, NULL_TREE);
6524       name = "atexit";
6525     }
6526
6527   /* Now, build the function declaration.  */
6528   push_lang_context (lang_name_c);
6529   atexit_fndecl = build_library_fn_ptr (name, fn_type);
6530   mark_used (atexit_fndecl);
6531   pop_lang_context ();
6532   atexit_node = decay_conversion (atexit_fndecl, tf_warning_or_error);
6533
6534   return atexit_node;
6535 }
6536
6537 /* Returns the __dso_handle VAR_DECL.  */
6538
6539 static tree
6540 get_dso_handle_node (void)
6541 {
6542   if (dso_handle_node)
6543     return dso_handle_node;
6544
6545   /* Declare the variable.  */
6546   dso_handle_node = declare_global_var (get_identifier ("__dso_handle"),
6547                                         ptr_type_node);
6548
6549 #ifdef HAVE_GAS_HIDDEN
6550   DECL_VISIBILITY (dso_handle_node) = VISIBILITY_HIDDEN;
6551   DECL_VISIBILITY_SPECIFIED (dso_handle_node) = 1;
6552 #endif
6553
6554   return dso_handle_node;
6555 }
6556
6557 /* Begin a new function with internal linkage whose job will be simply
6558    to destroy some particular variable.  */
6559
6560 static GTY(()) int start_cleanup_cnt;
6561
6562 static tree
6563 start_cleanup_fn (void)
6564 {
6565   char name[32];
6566   tree fntype;
6567   tree fndecl;
6568   bool use_cxa_atexit = flag_use_cxa_atexit
6569                         && !targetm.cxx.use_atexit_for_cxa_atexit ();
6570
6571   push_to_top_level ();
6572
6573   /* No need to mangle this.  */
6574   push_lang_context (lang_name_c);
6575
6576   /* Build the name of the function.  */
6577   sprintf (name, "__tcf_%d", start_cleanup_cnt++);
6578   /* Build the function declaration.  */
6579   fntype = TREE_TYPE (get_atexit_fn_ptr_type ());
6580   fndecl = build_lang_decl (FUNCTION_DECL, get_identifier (name), fntype);
6581   /* It's a function with internal linkage, generated by the
6582      compiler.  */
6583   TREE_PUBLIC (fndecl) = 0;
6584   DECL_ARTIFICIAL (fndecl) = 1;
6585   /* Make the function `inline' so that it is only emitted if it is
6586      actually needed.  It is unlikely that it will be inlined, since
6587      it is only called via a function pointer, but we avoid unnecessary
6588      emissions this way.  */
6589   DECL_DECLARED_INLINE_P (fndecl) = 1;
6590   DECL_INTERFACE_KNOWN (fndecl) = 1;
6591   /* Build the parameter.  */
6592   if (use_cxa_atexit)
6593     {
6594       tree parmdecl;
6595
6596       parmdecl = cp_build_parm_decl (NULL_TREE, ptr_type_node);
6597       DECL_CONTEXT (parmdecl) = fndecl;
6598       TREE_USED (parmdecl) = 1;
6599       DECL_READ_P (parmdecl) = 1;
6600       DECL_ARGUMENTS (fndecl) = parmdecl;
6601     }
6602
6603   pushdecl (fndecl);
6604   start_preparsed_function (fndecl, NULL_TREE, SF_PRE_PARSED);
6605
6606   pop_lang_context ();
6607
6608   return current_function_decl;
6609 }
6610
6611 /* Finish the cleanup function begun by start_cleanup_fn.  */
6612
6613 static void
6614 end_cleanup_fn (void)
6615 {
6616   expand_or_defer_fn (finish_function (0));
6617
6618   pop_from_top_level ();
6619 }
6620
6621 /* Generate code to handle the destruction of DECL, an object with
6622    static storage duration.  */
6623
6624 tree
6625 register_dtor_fn (tree decl)
6626 {
6627   tree cleanup;
6628   tree compound_stmt;
6629   tree fcall;
6630   tree type;
6631   bool use_dtor;
6632   tree arg0, arg1 = NULL_TREE, arg2 = NULL_TREE;
6633
6634   type = TREE_TYPE (decl);
6635   if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
6636     return void_zero_node;
6637
6638   /* If we're using "__cxa_atexit" (or "__aeabi_atexit"), and DECL is
6639      a class object, we can just pass the destructor to
6640      "__cxa_atexit"; we don't have to build a temporary function to do
6641      the cleanup.  */
6642   use_dtor = (flag_use_cxa_atexit 
6643               && !targetm.cxx.use_atexit_for_cxa_atexit ()
6644               && CLASS_TYPE_P (type));
6645   if (use_dtor)
6646     {
6647       int idx;
6648
6649       /* Find the destructor.  */
6650       idx = lookup_fnfields_1 (type, complete_dtor_identifier);
6651       gcc_assert (idx >= 0);
6652       cleanup = VEC_index (tree, CLASSTYPE_METHOD_VEC (type), idx);
6653       /* Make sure it is accessible.  */
6654       perform_or_defer_access_check (TYPE_BINFO (type), cleanup, cleanup,
6655                                      tf_warning_or_error);
6656     }
6657   else
6658     {
6659       /* Call build_cleanup before we enter the anonymous function so
6660          that any access checks will be done relative to the current
6661          scope, rather than the scope of the anonymous function.  */
6662       build_cleanup (decl);
6663   
6664       /* Now start the function.  */
6665       cleanup = start_cleanup_fn ();
6666       
6667       /* Now, recompute the cleanup.  It may contain SAVE_EXPRs that refer
6668          to the original function, rather than the anonymous one.  That
6669          will make the back end think that nested functions are in use,
6670          which causes confusion.  */
6671       push_deferring_access_checks (dk_no_check);
6672       fcall = build_cleanup (decl);
6673       pop_deferring_access_checks ();
6674       
6675       /* Create the body of the anonymous function.  */
6676       compound_stmt = begin_compound_stmt (BCS_FN_BODY);
6677       finish_expr_stmt (fcall);
6678       finish_compound_stmt (compound_stmt);
6679       end_cleanup_fn ();
6680     }
6681
6682   /* Call atexit with the cleanup function.  */
6683   mark_used (cleanup);
6684   cleanup = build_address (cleanup);
6685   if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
6686     {
6687       tree addr;
6688
6689       if (use_dtor)
6690         {
6691           /* We must convert CLEANUP to the type that "__cxa_atexit"
6692              expects.  */
6693           cleanup = build_nop (get_atexit_fn_ptr_type (), cleanup);
6694           /* "__cxa_atexit" will pass the address of DECL to the
6695              cleanup function.  */
6696           mark_used (decl);
6697           addr = build_address (decl);
6698           /* The declared type of the parameter to "__cxa_atexit" is
6699              "void *".  For plain "T*", we could just let the
6700              machinery in cp_build_function_call convert it -- but if the
6701              type is "cv-qualified T *", then we need to convert it
6702              before passing it in, to avoid spurious errors.  */
6703           addr = build_nop (ptr_type_node, addr);
6704         }
6705       else
6706         /* Since the cleanup functions we build ignore the address
6707            they're given, there's no reason to pass the actual address
6708            in, and, in general, it's cheaper to pass NULL than any
6709            other value.  */
6710         addr = null_pointer_node;
6711       arg2 = cp_build_addr_expr (get_dso_handle_node (),
6712                                  tf_warning_or_error);
6713       if (targetm.cxx.use_aeabi_atexit ())
6714         {
6715           arg1 = cleanup;
6716           arg0 = addr;
6717         }
6718       else
6719         {
6720           arg1 = addr;
6721           arg0 = cleanup;
6722         }
6723     }
6724   else
6725     arg0 = cleanup;
6726   return cp_build_function_call_nary (get_atexit_node (), tf_warning_or_error,
6727                                       arg0, arg1, arg2, NULL_TREE);
6728 }
6729
6730 /* DECL is a VAR_DECL with static storage duration.  INIT, if present,
6731    is its initializer.  Generate code to handle the construction
6732    and destruction of DECL.  */
6733
6734 static void
6735 expand_static_init (tree decl, tree init)
6736 {
6737   gcc_assert (TREE_CODE (decl) == VAR_DECL);
6738   gcc_assert (TREE_STATIC (decl));
6739
6740   /* Some variables require no dynamic initialization.  */
6741   if (!init
6742       && TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
6743     return;
6744
6745   if (DECL_FUNCTION_SCOPE_P (decl))
6746     {
6747       /* Emit code to perform this initialization but once.  */
6748       tree if_stmt = NULL_TREE, inner_if_stmt = NULL_TREE;
6749       tree then_clause = NULL_TREE, inner_then_clause = NULL_TREE;
6750       tree guard, guard_addr;
6751       tree flag, begin;
6752
6753       /* Emit code to perform this initialization but once.  This code
6754          looks like:
6755
6756            static <type> guard;
6757            if (!guard.first_byte) {
6758              if (__cxa_guard_acquire (&guard)) {
6759                bool flag = false;
6760                try {
6761                  // Do initialization.
6762                  flag = true; __cxa_guard_release (&guard);
6763                  // Register variable for destruction at end of program.
6764                } catch {
6765                  if (!flag) __cxa_guard_abort (&guard);
6766                }
6767            }
6768
6769          Note that the `flag' variable is only set to 1 *after* the
6770          initialization is complete.  This ensures that an exception,
6771          thrown during the construction, will cause the variable to
6772          reinitialized when we pass through this code again, as per:
6773
6774            [stmt.dcl]
6775
6776            If the initialization exits by throwing an exception, the
6777            initialization is not complete, so it will be tried again
6778            the next time control enters the declaration.
6779
6780          This process should be thread-safe, too; multiple threads
6781          should not be able to initialize the variable more than
6782          once.  */
6783
6784       /* Create the guard variable.  */
6785       guard = get_guard (decl);
6786
6787       /* This optimization isn't safe on targets with relaxed memory
6788          consistency.  On such targets we force synchronization in
6789          __cxa_guard_acquire.  */
6790       if (!targetm.relaxed_ordering || !flag_threadsafe_statics)
6791         {
6792           /* Begin the conditional initialization.  */
6793           if_stmt = begin_if_stmt ();
6794           finish_if_stmt_cond (get_guard_cond (guard), if_stmt);
6795           then_clause = begin_compound_stmt (BCS_NO_SCOPE);
6796         }
6797
6798       if (flag_threadsafe_statics)
6799         {
6800           tree vfntype = NULL_TREE;
6801           tree acquire_name, release_name, abort_name;
6802           tree acquire_fn, release_fn, abort_fn;
6803           guard_addr = build_address (guard);
6804
6805           acquire_name = get_identifier ("__cxa_guard_acquire");
6806           release_name = get_identifier ("__cxa_guard_release");
6807           abort_name = get_identifier ("__cxa_guard_abort");
6808           acquire_fn = identifier_global_value (acquire_name);
6809           release_fn = identifier_global_value (release_name);
6810           abort_fn = identifier_global_value (abort_name);
6811           if (!acquire_fn)
6812             acquire_fn = push_library_fn
6813               (acquire_name, build_function_type_list (integer_type_node,
6814                                                        TREE_TYPE (guard_addr),
6815                                                        NULL_TREE),
6816                NULL_TREE);
6817           if (!release_fn || !abort_fn)
6818             vfntype = build_function_type_list (void_type_node,
6819                                                 TREE_TYPE (guard_addr),
6820                                                 NULL_TREE);
6821           if (!release_fn)
6822             release_fn = push_library_fn (release_name, vfntype, NULL_TREE);
6823           if (!abort_fn)
6824             abort_fn = push_library_fn (abort_name, vfntype, NULL_TREE);
6825
6826           inner_if_stmt = begin_if_stmt ();
6827           finish_if_stmt_cond (build_call_n (acquire_fn, 1, guard_addr),
6828                                inner_if_stmt);
6829
6830           inner_then_clause = begin_compound_stmt (BCS_NO_SCOPE);
6831           begin = get_target_expr (boolean_false_node);
6832           flag = TARGET_EXPR_SLOT (begin);
6833
6834           TARGET_EXPR_CLEANUP (begin)
6835             = build3 (COND_EXPR, void_type_node, flag,
6836                       void_zero_node,
6837                       build_call_n (abort_fn, 1, guard_addr));
6838           CLEANUP_EH_ONLY (begin) = 1;
6839
6840           /* Do the initialization itself.  */
6841           init = add_stmt_to_compound (begin, init);
6842           init = add_stmt_to_compound
6843             (init, build2 (MODIFY_EXPR, void_type_node, flag, boolean_true_node));
6844           init = add_stmt_to_compound
6845             (init, build_call_n (release_fn, 1, guard_addr));
6846         }
6847       else
6848         init = add_stmt_to_compound (init, set_guard (guard));
6849
6850       /* Use atexit to register a function for destroying this static
6851          variable.  */
6852       init = add_stmt_to_compound (init, register_dtor_fn (decl));
6853
6854       finish_expr_stmt (init);
6855
6856       if (flag_threadsafe_statics)
6857         {
6858           finish_compound_stmt (inner_then_clause);
6859           finish_then_clause (inner_if_stmt);
6860           finish_if_stmt (inner_if_stmt);
6861         }
6862
6863       if (!targetm.relaxed_ordering || !flag_threadsafe_statics)
6864         {
6865           finish_compound_stmt (then_clause);
6866           finish_then_clause (if_stmt);
6867           finish_if_stmt (if_stmt);
6868         }
6869     }
6870   else
6871     static_aggregates = tree_cons (init, decl, static_aggregates);
6872 }
6873
6874 \f
6875 /* Make TYPE a complete type based on INITIAL_VALUE.
6876    Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
6877    2 if there was no information (in which case assume 0 if DO_DEFAULT),
6878    3 if the initializer list is empty (in pedantic mode). */
6879
6880 int
6881 cp_complete_array_type (tree *ptype, tree initial_value, bool do_default)
6882 {
6883   int failure;
6884   tree type, elt_type;
6885
6886   if (initial_value)
6887     {
6888       unsigned HOST_WIDE_INT i;
6889       tree value;
6890
6891       /* An array of character type can be initialized from a
6892          brace-enclosed string constant.
6893
6894          FIXME: this code is duplicated from reshape_init. Probably
6895          we should just call reshape_init here?  */
6896       if (char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (*ptype)))
6897           && TREE_CODE (initial_value) == CONSTRUCTOR
6898           && !VEC_empty (constructor_elt, CONSTRUCTOR_ELTS (initial_value)))
6899         {
6900           VEC(constructor_elt,gc) *v = CONSTRUCTOR_ELTS (initial_value);
6901           tree value = VEC_index (constructor_elt, v, 0).value;
6902
6903           if (TREE_CODE (value) == STRING_CST
6904               && VEC_length (constructor_elt, v) == 1)
6905             initial_value = value;
6906         }
6907
6908       /* If any of the elements are parameter packs, we can't actually
6909          complete this type now because the array size is dependent.  */
6910       if (TREE_CODE (initial_value) == CONSTRUCTOR)
6911         {
6912           FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (initial_value), 
6913                                       i, value)
6914             {
6915               if (PACK_EXPANSION_P (value))
6916                 return 0;
6917             }
6918         }
6919     }
6920
6921   failure = complete_array_type (ptype, initial_value, do_default);
6922
6923   /* We can create the array before the element type is complete, which
6924      means that we didn't have these two bits set in the original type
6925      either.  In completing the type, we are expected to propagate these
6926      bits.  See also complete_type which does the same thing for arrays
6927      of fixed size.  */
6928   type = *ptype;
6929   if (TYPE_DOMAIN (type))
6930     {
6931       elt_type = TREE_TYPE (type);
6932       TYPE_NEEDS_CONSTRUCTING (type) = TYPE_NEEDS_CONSTRUCTING (elt_type);
6933       TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
6934         = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (elt_type);
6935     }
6936
6937   return failure;
6938 }
6939
6940 /* As above, but either give an error or reject zero-size arrays, depending
6941    on COMPLAIN.  */
6942
6943 int
6944 cp_complete_array_type_or_error (tree *ptype, tree initial_value,
6945                                  bool do_default, tsubst_flags_t complain)
6946 {
6947   int failure;
6948   bool sfinae = !(complain & tf_error);
6949   /* In SFINAE context we can't be lenient about zero-size arrays.  */
6950   if (sfinae)
6951     ++pedantic;
6952   failure = cp_complete_array_type (ptype, initial_value, do_default);
6953   if (sfinae)
6954     --pedantic;
6955   if (failure)
6956     {
6957       if (sfinae)
6958         /* Not an error.  */;
6959       else if (failure == 1)
6960         error ("initializer fails to determine size of %qT", *ptype);
6961       else if (failure == 2)
6962         {
6963           if (do_default)
6964             error ("array size missing in %qT", *ptype);
6965         }
6966       else if (failure == 3)
6967         error ("zero-size array %qT", *ptype);
6968       *ptype = error_mark_node;
6969     }
6970   return failure;
6971 }
6972 \f
6973 /* Return zero if something is declared to be a member of type
6974    CTYPE when in the context of CUR_TYPE.  STRING is the error
6975    message to print in that case.  Otherwise, quietly return 1.  */
6976
6977 static int
6978 member_function_or_else (tree ctype, tree cur_type, enum overload_flags flags)
6979 {
6980   if (ctype && ctype != cur_type)
6981     {
6982       if (flags == DTOR_FLAG)
6983         error ("destructor for alien class %qT cannot be a member", ctype);
6984       else
6985         error ("constructor for alien class %qT cannot be a member", ctype);
6986       return 0;
6987     }
6988   return 1;
6989 }
6990 \f
6991 /* Subroutine of `grokdeclarator'.  */
6992
6993 /* Generate errors possibly applicable for a given set of specifiers.
6994    This is for ARM $7.1.2.  */
6995
6996 static void
6997 bad_specifiers (tree object,
6998                 enum bad_spec_place type,
6999                 int virtualp,
7000                 int quals,
7001                 int inlinep,
7002                 int friendp,
7003                 int raises)
7004 {
7005   switch (type)
7006     {
7007       case BSP_VAR:
7008         if (virtualp)
7009           error ("%qD declared as a %<virtual%> variable", object);
7010         if (inlinep)
7011           error ("%qD declared as an %<inline%> variable", object);
7012         if (quals)
7013           error ("%<const%> and %<volatile%> function specifiers on "
7014                  "%qD invalid in variable declaration", object);
7015         break;
7016       case BSP_PARM:
7017         if (virtualp)
7018           error ("%qD declared as a %<virtual%> parameter", object);
7019         if (inlinep)
7020           error ("%qD declared as an %<inline%> parameter", object);
7021         if (quals)
7022           error ("%<const%> and %<volatile%> function specifiers on "
7023                  "%qD invalid in parameter declaration", object);
7024         break;
7025       case BSP_TYPE:
7026         if (virtualp)
7027           error ("%qD declared as a %<virtual%> type", object);
7028         if (inlinep)
7029           error ("%qD declared as an %<inline%> type", object);
7030         if (quals)
7031           error ("%<const%> and %<volatile%> function specifiers on "
7032                  "%qD invalid in type declaration", object);
7033         break;
7034       case BSP_FIELD:
7035         if (virtualp)
7036           error ("%qD declared as a %<virtual%> field", object);
7037         if (inlinep)
7038           error ("%qD declared as an %<inline%> field", object);
7039         if (quals)
7040           error ("%<const%> and %<volatile%> function specifiers on "
7041                  "%qD invalid in field declaration", object);
7042         break;
7043       default:
7044         gcc_unreachable();
7045     }
7046   if (friendp)
7047     error ("%q+D declared as a friend", object);
7048   if (raises
7049       && (TREE_CODE (object) == TYPE_DECL
7050           || (!TYPE_PTRFN_P (TREE_TYPE (object))
7051               && !TYPE_REFFN_P (TREE_TYPE (object))
7052               && !TYPE_PTRMEMFUNC_P (TREE_TYPE (object)))))
7053     error ("%q+D declared with an exception specification", object);
7054 }
7055
7056 /* DECL is a member function or static data member and is presently
7057    being defined.  Check that the definition is taking place in a
7058    valid namespace.  */
7059
7060 static void
7061 check_class_member_definition_namespace (tree decl)
7062 {
7063   /* These checks only apply to member functions and static data
7064      members.  */
7065   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
7066               || TREE_CODE (decl) == VAR_DECL);
7067   /* We check for problems with specializations in pt.c in
7068      check_specialization_namespace, where we can issue better
7069      diagnostics.  */
7070   if (processing_specialization)
7071     return;
7072   /* There are no restrictions on the placement of
7073      explicit instantiations.  */
7074   if (processing_explicit_instantiation)
7075     return;
7076   /* [class.mfct]
7077
7078      A member function definition that appears outside of the
7079      class definition shall appear in a namespace scope enclosing
7080      the class definition.
7081
7082      [class.static.data]
7083
7084      The definition for a static data member shall appear in a
7085      namespace scope enclosing the member's class definition.  */
7086   if (!is_ancestor (current_namespace, DECL_CONTEXT (decl)))
7087     permerror (input_location, "definition of %qD is not in namespace enclosing %qT",
7088                decl, DECL_CONTEXT (decl));
7089 }
7090
7091 /* Build a PARM_DECL for the "this" parameter.  TYPE is the
7092    METHOD_TYPE for a non-static member function; QUALS are the
7093    cv-qualifiers that apply to the function.  */
7094
7095 tree
7096 build_this_parm (tree type, cp_cv_quals quals)
7097 {
7098   tree this_type;
7099   tree qual_type;
7100   tree parm;
7101   cp_cv_quals this_quals;
7102
7103   if (CLASS_TYPE_P (type))
7104     {
7105       this_type
7106         = cp_build_qualified_type (type, quals & ~TYPE_QUAL_RESTRICT);
7107       this_type = build_pointer_type (this_type);
7108     }
7109   else
7110     this_type = type_of_this_parm (type);
7111   /* The `this' parameter is implicitly `const'; it cannot be
7112      assigned to.  */
7113   this_quals = (quals & TYPE_QUAL_RESTRICT) | TYPE_QUAL_CONST;
7114   qual_type = cp_build_qualified_type (this_type, this_quals);
7115   parm = build_artificial_parm (this_identifier, qual_type);
7116   cp_apply_type_quals_to_decl (this_quals, parm);
7117   return parm;
7118 }
7119
7120 /* DECL is a static member function.  Complain if it was declared
7121    with function-cv-quals.  */
7122
7123 static void
7124 check_static_quals (tree decl, cp_cv_quals quals)
7125 {
7126   if (quals != TYPE_UNQUALIFIED)
7127     error ("static member function %q#D declared with type qualifiers",
7128            decl);
7129 }
7130
7131 /* CTYPE is class type, or null if non-class.
7132    TYPE is type this FUNCTION_DECL should have, either FUNCTION_TYPE
7133    or METHOD_TYPE.
7134    DECLARATOR is the function's name.
7135    PARMS is a chain of PARM_DECLs for the function.
7136    VIRTUALP is truthvalue of whether the function is virtual or not.
7137    FLAGS are to be passed through to `grokclassfn'.
7138    QUALS are qualifiers indicating whether the function is `const'
7139    or `volatile'.
7140    RAISES is a list of exceptions that this function can raise.
7141    CHECK is 1 if we must find this method in CTYPE, 0 if we should
7142    not look, and -1 if we should not call `grokclassfn' at all.
7143
7144    SFK is the kind of special function (if any) for the new function.
7145
7146    Returns `NULL_TREE' if something goes wrong, after issuing
7147    applicable error messages.  */
7148
7149 static tree
7150 grokfndecl (tree ctype,
7151             tree type,
7152             tree declarator,
7153             tree parms,
7154             tree orig_declarator,
7155             int virtualp,
7156             enum overload_flags flags,
7157             cp_cv_quals quals,
7158             tree raises,
7159             int check,
7160             int friendp,
7161             int publicp,
7162             int inlinep,
7163             special_function_kind sfk,
7164             bool funcdef_flag,
7165             int template_count,
7166             tree in_namespace,
7167             tree* attrlist,
7168             location_t location)
7169 {
7170   tree decl;
7171   int staticp = ctype && TREE_CODE (type) == FUNCTION_TYPE;
7172   tree t;
7173
7174   if (raises)
7175     type = build_exception_variant (type, raises);
7176
7177   decl = build_lang_decl (FUNCTION_DECL, declarator, type);
7178
7179   /* If we have an explicit location, use it, otherwise use whatever
7180      build_lang_decl used (probably input_location).  */
7181   if (location != UNKNOWN_LOCATION)
7182     DECL_SOURCE_LOCATION (decl) = location;
7183
7184   if (TREE_CODE (type) == METHOD_TYPE)
7185     {
7186       tree parm;
7187       parm = build_this_parm (type, quals);
7188       DECL_CHAIN (parm) = parms;
7189       parms = parm;
7190     }
7191   DECL_ARGUMENTS (decl) = parms;
7192   for (t = parms; t; t = DECL_CHAIN (t))
7193     DECL_CONTEXT (t) = decl;
7194   /* Propagate volatile out from type to decl.  */
7195   if (TYPE_VOLATILE (type))
7196     TREE_THIS_VOLATILE (decl) = 1;
7197
7198   /* Setup decl according to sfk.  */
7199   switch (sfk)
7200     {
7201     case sfk_constructor:
7202     case sfk_copy_constructor:
7203     case sfk_move_constructor:
7204       DECL_CONSTRUCTOR_P (decl) = 1;
7205       break;
7206     case sfk_destructor:
7207       DECL_DESTRUCTOR_P (decl) = 1;
7208       break;
7209     default:
7210       break;
7211     }
7212
7213   /* If pointers to member functions use the least significant bit to
7214      indicate whether a function is virtual, ensure a pointer
7215      to this function will have that bit clear.  */
7216   if (TARGET_PTRMEMFUNC_VBIT_LOCATION == ptrmemfunc_vbit_in_pfn
7217       && TREE_CODE (type) == METHOD_TYPE
7218       && DECL_ALIGN (decl) < 2 * BITS_PER_UNIT)
7219     DECL_ALIGN (decl) = 2 * BITS_PER_UNIT;
7220
7221   if (friendp
7222       && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)
7223     {
7224       if (funcdef_flag)
7225         error
7226           ("defining explicit specialization %qD in friend declaration",
7227            orig_declarator);
7228       else
7229         {
7230           tree fns = TREE_OPERAND (orig_declarator, 0);
7231           tree args = TREE_OPERAND (orig_declarator, 1);
7232
7233           if (PROCESSING_REAL_TEMPLATE_DECL_P ())
7234             {
7235               /* Something like `template <class T> friend void f<T>()'.  */
7236               error ("invalid use of template-id %qD in declaration "
7237                      "of primary template",
7238                      orig_declarator);
7239               return NULL_TREE;
7240             }
7241
7242
7243           /* A friend declaration of the form friend void f<>().  Record
7244              the information in the TEMPLATE_ID_EXPR.  */
7245           SET_DECL_IMPLICIT_INSTANTIATION (decl);
7246
7247           if (TREE_CODE (fns) == COMPONENT_REF)
7248             {
7249               /* Due to bison parser ickiness, we will have already looked
7250                  up an operator_name or PFUNCNAME within the current class
7251                  (see template_id in parse.y). If the current class contains
7252                  such a name, we'll get a COMPONENT_REF here. Undo that.  */
7253
7254               gcc_assert (TREE_TYPE (TREE_OPERAND (fns, 0))
7255                           == current_class_type);
7256               fns = TREE_OPERAND (fns, 1);
7257             }
7258           gcc_assert (TREE_CODE (fns) == IDENTIFIER_NODE
7259                       || TREE_CODE (fns) == OVERLOAD);
7260           DECL_TEMPLATE_INFO (decl) = build_template_info (fns, args);
7261
7262           for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
7263             if (TREE_PURPOSE (t)
7264                 && TREE_CODE (TREE_PURPOSE (t)) == DEFAULT_ARG)
7265             {
7266               error ("default arguments are not allowed in declaration "
7267                      "of friend template specialization %qD",
7268                      decl);
7269               return NULL_TREE;
7270             }
7271
7272           if (inlinep)
7273             {
7274               error ("%<inline%> is not allowed in declaration of friend "
7275                      "template specialization %qD",
7276                      decl);
7277               return NULL_TREE;
7278             }
7279         }
7280     }
7281
7282   /* If this decl has namespace scope, set that up.  */
7283   if (in_namespace)
7284     set_decl_namespace (decl, in_namespace, friendp);
7285   else if (!ctype)
7286     DECL_CONTEXT (decl) = FROB_CONTEXT (current_decl_namespace ());
7287
7288   /* `main' and builtins have implicit 'C' linkage.  */
7289   if ((MAIN_NAME_P (declarator)
7290        || (IDENTIFIER_LENGTH (declarator) > 10
7291            && IDENTIFIER_POINTER (declarator)[0] == '_'
7292            && IDENTIFIER_POINTER (declarator)[1] == '_'
7293            && strncmp (IDENTIFIER_POINTER (declarator)+2, "builtin_", 8) == 0))
7294       && current_lang_name == lang_name_cplusplus
7295       && ctype == NULL_TREE
7296       && DECL_FILE_SCOPE_P (decl))
7297     SET_DECL_LANGUAGE (decl, lang_c);
7298
7299   /* Should probably propagate const out from type to decl I bet (mrs).  */
7300   if (staticp)
7301     {
7302       DECL_STATIC_FUNCTION_P (decl) = 1;
7303       DECL_CONTEXT (decl) = ctype;
7304     }
7305
7306   if (ctype)
7307     {
7308       DECL_CONTEXT (decl) = ctype;
7309       if (funcdef_flag)
7310         check_class_member_definition_namespace (decl);
7311     }
7312
7313   if (ctype == NULL_TREE && DECL_MAIN_P (decl))
7314     {
7315       if (processing_template_decl)
7316         error ("cannot declare %<::main%> to be a template");
7317       if (inlinep)
7318         error ("cannot declare %<::main%> to be inline");
7319       if (!publicp)
7320         error ("cannot declare %<::main%> to be static");
7321       inlinep = 0;
7322       publicp = 1;
7323     }
7324
7325   /* Members of anonymous types and local classes have no linkage; make
7326      them internal.  If a typedef is made later, this will be changed.  */
7327   if (ctype && (TYPE_ANONYMOUS_P (ctype)
7328                 || decl_function_context (TYPE_MAIN_DECL (ctype))))
7329     publicp = 0;
7330
7331   if (publicp && cxx_dialect == cxx98)
7332     {
7333       /* [basic.link]: A name with no linkage (notably, the name of a class
7334          or enumeration declared in a local scope) shall not be used to
7335          declare an entity with linkage.
7336
7337          DR 757 relaxes this restriction for C++0x.  */
7338       t = no_linkage_check (TREE_TYPE (decl),
7339                             /*relaxed_p=*/false);
7340       if (t)
7341         {
7342           if (TYPE_ANONYMOUS_P (t))
7343             {
7344               if (DECL_EXTERN_C_P (decl))
7345                 /* Allow this; it's pretty common in C.  */;
7346               else
7347                 {
7348                   permerror (input_location, "anonymous type with no linkage "
7349                              "used to declare function %q#D with linkage",
7350                              decl);
7351                   if (DECL_ORIGINAL_TYPE (TYPE_NAME (t)))
7352                     permerror (input_location, "%q+#D does not refer to the unqualified "
7353                                "type, so it is not used for linkage",
7354                                TYPE_NAME (t));
7355                 }
7356             }
7357           else
7358             permerror (input_location, "type %qT with no linkage used to "
7359                        "declare function %q#D with linkage", t, decl);
7360         }
7361     }
7362
7363   TREE_PUBLIC (decl) = publicp;
7364   if (! publicp)
7365     {
7366       DECL_INTERFACE_KNOWN (decl) = 1;
7367       DECL_NOT_REALLY_EXTERN (decl) = 1;
7368     }
7369
7370   /* If the declaration was declared inline, mark it as such.  */
7371   if (inlinep)
7372     DECL_DECLARED_INLINE_P (decl) = 1;
7373   if (inlinep & 2)
7374     DECL_DECLARED_CONSTEXPR_P (decl) = true;
7375
7376   DECL_EXTERNAL (decl) = 1;
7377   if (quals && TREE_CODE (type) == FUNCTION_TYPE)
7378     {
7379       error (ctype
7380              ? G_("static member function %qD cannot have cv-qualifier")
7381              : G_("non-member function %qD cannot have cv-qualifier"),
7382              decl);
7383       quals = TYPE_UNQUALIFIED;
7384     }
7385
7386   if (IDENTIFIER_OPNAME_P (DECL_NAME (decl))
7387       && !grok_op_properties (decl, /*complain=*/true))
7388     return NULL_TREE;
7389   else if (UDLIT_OPER_P (DECL_NAME (decl)))
7390     {
7391       bool long_long_unsigned_p;
7392       bool long_double_p;
7393       const char *suffix = NULL;
7394       /* [over.literal]/6: Literal operators shall not have C linkage. */
7395       if (DECL_LANGUAGE (decl) == lang_c)
7396         {
7397           error ("literal operator with C linkage");
7398           return NULL_TREE;
7399         }
7400
7401       if (DECL_NAMESPACE_SCOPE_P (decl))
7402         {
7403           if (!check_literal_operator_args (decl, &long_long_unsigned_p,
7404                                             &long_double_p))
7405             {
7406               error ("%qD has invalid argument list", decl);
7407               return NULL_TREE;
7408             }
7409
7410           suffix = UDLIT_OP_SUFFIX (DECL_NAME (decl));
7411           if (long_long_unsigned_p)
7412             {
7413               if (cpp_interpret_int_suffix (suffix, strlen (suffix)))
7414                 warning (0, "integer suffix %<%s%>"
7415                             " shadowed by implementation", suffix);
7416             }
7417           else if (long_double_p)
7418             {
7419               if (cpp_interpret_float_suffix (suffix, strlen (suffix)))
7420                 warning (0, "floating point suffix %<%s%>"
7421                             " shadowed by implementation", suffix);
7422             }
7423         }
7424       else
7425         {
7426           error ("%qD must be a non-member function", decl);
7427           return NULL_TREE;
7428         }
7429     }
7430
7431   if (funcdef_flag)
7432     /* Make the init_value nonzero so pushdecl knows this is not
7433        tentative.  error_mark_node is replaced later with the BLOCK.  */
7434     DECL_INITIAL (decl) = error_mark_node;
7435
7436   if (TYPE_NOTHROW_P (type) || nothrow_libfn_p (decl))
7437     TREE_NOTHROW (decl) = 1;
7438
7439   /* Caller will do the rest of this.  */
7440   if (check < 0)
7441     return decl;
7442
7443   if (ctype != NULL_TREE)
7444     grokclassfn (ctype, decl, flags);
7445
7446   /* 12.4/3  */
7447   if (cxx_dialect >= cxx0x
7448       && DECL_DESTRUCTOR_P (decl)
7449       && !TYPE_BEING_DEFINED (DECL_CONTEXT (decl))
7450       && !processing_template_decl)
7451     deduce_noexcept_on_destructor (decl);
7452
7453   decl = check_explicit_specialization (orig_declarator, decl,
7454                                         template_count,
7455                                         2 * funcdef_flag +
7456                                         4 * (friendp != 0));
7457   if (decl == error_mark_node)
7458     return NULL_TREE;
7459
7460   if (DECL_STATIC_FUNCTION_P (decl))
7461     check_static_quals (decl, quals);
7462
7463   if (attrlist)
7464     {
7465       cplus_decl_attributes (&decl, *attrlist, 0);
7466       *attrlist = NULL_TREE;
7467     }
7468
7469   /* Check main's type after attributes have been applied.  */
7470   if (ctype == NULL_TREE && DECL_MAIN_P (decl))
7471     {
7472       if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
7473                         integer_type_node))
7474         {
7475           tree oldtypeargs = TYPE_ARG_TYPES (TREE_TYPE (decl));
7476           tree newtype;
7477           error ("%<::main%> must return %<int%>");
7478           newtype = build_function_type (integer_type_node, oldtypeargs);
7479           TREE_TYPE (decl) = newtype;
7480         }
7481       if (warn_main)
7482         check_main_parameter_types (decl);
7483     }
7484
7485   if (ctype != NULL_TREE
7486       && (! TYPE_FOR_JAVA (ctype) || check_java_method (decl))
7487       && check)
7488     {
7489       tree old_decl = check_classfn (ctype, decl,
7490                                      (processing_template_decl
7491                                       > template_class_depth (ctype))
7492                                      ? current_template_parms
7493                                      : NULL_TREE);
7494
7495       if (old_decl == error_mark_node)
7496         return NULL_TREE;
7497
7498       if (old_decl)
7499         {
7500           tree ok;
7501           tree pushed_scope;
7502
7503           if (TREE_CODE (old_decl) == TEMPLATE_DECL)
7504             /* Because grokfndecl is always supposed to return a
7505                FUNCTION_DECL, we pull out the DECL_TEMPLATE_RESULT
7506                here.  We depend on our callers to figure out that its
7507                really a template that's being returned.  */
7508             old_decl = DECL_TEMPLATE_RESULT (old_decl);
7509
7510           if (DECL_STATIC_FUNCTION_P (old_decl)
7511               && TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
7512             {
7513               /* Remove the `this' parm added by grokclassfn.  */
7514               revert_static_member_fn (decl);
7515               check_static_quals (decl, quals);
7516             }
7517           if (DECL_ARTIFICIAL (old_decl))
7518             {
7519               error ("definition of implicitly-declared %qD", old_decl);
7520               return NULL_TREE;
7521             }
7522           else if (DECL_DEFAULTED_FN (old_decl))
7523             {
7524               error ("definition of explicitly-defaulted %q+D", decl);
7525               error ("%q+#D explicitly defaulted here", old_decl);
7526               return NULL_TREE;
7527             }
7528
7529           /* Since we've smashed OLD_DECL to its
7530              DECL_TEMPLATE_RESULT, we must do the same to DECL.  */
7531           if (TREE_CODE (decl) == TEMPLATE_DECL)
7532             decl = DECL_TEMPLATE_RESULT (decl);
7533
7534           /* Attempt to merge the declarations.  This can fail, in
7535              the case of some invalid specialization declarations.  */
7536           pushed_scope = push_scope (ctype);
7537           ok = duplicate_decls (decl, old_decl, friendp);
7538           if (pushed_scope)
7539             pop_scope (pushed_scope);
7540           if (!ok)
7541             {
7542               error ("no %q#D member function declared in class %qT",
7543                      decl, ctype);
7544               return NULL_TREE;
7545             }
7546           return old_decl;
7547         }
7548     }
7549
7550   if (DECL_CONSTRUCTOR_P (decl) && !grok_ctor_properties (ctype, decl))
7551     return NULL_TREE;
7552
7553   if (ctype == NULL_TREE || check)
7554     return decl;
7555
7556   if (virtualp)
7557     DECL_VIRTUAL_P (decl) = 1;
7558
7559   return decl;
7560 }
7561
7562 /* decl is a FUNCTION_DECL.
7563    specifiers are the parsed virt-specifiers.
7564
7565    Set flags to reflect the virt-specifiers.
7566
7567    Returns decl.  */
7568
7569 static tree
7570 set_virt_specifiers (tree decl, cp_virt_specifiers specifiers)
7571 {
7572   if (decl == NULL_TREE)
7573     return decl;
7574   if (specifiers & VIRT_SPEC_OVERRIDE)
7575     DECL_OVERRIDE_P (decl) = 1;
7576   if (specifiers & VIRT_SPEC_FINAL)
7577     DECL_FINAL_P (decl) = 1;
7578   return decl;
7579 }
7580
7581 /* DECL is a VAR_DECL for a static data member.  Set flags to reflect
7582    the linkage that DECL will receive in the object file.  */
7583
7584 static void
7585 set_linkage_for_static_data_member (tree decl)
7586 {
7587   /* A static data member always has static storage duration and
7588      external linkage.  Note that static data members are forbidden in
7589      local classes -- the only situation in which a class has
7590      non-external linkage.  */
7591   TREE_PUBLIC (decl) = 1;
7592   TREE_STATIC (decl) = 1;
7593   /* For non-template classes, static data members are always put
7594      out in exactly those files where they are defined, just as
7595      with ordinary namespace-scope variables.  */
7596   if (!processing_template_decl)
7597     DECL_INTERFACE_KNOWN (decl) = 1;
7598 }
7599
7600 /* Create a VAR_DECL named NAME with the indicated TYPE.
7601
7602    If SCOPE is non-NULL, it is the class type or namespace containing
7603    the variable.  If SCOPE is NULL, the variable should is created in
7604    the innermost enclosings scope.  */
7605
7606 static tree
7607 grokvardecl (tree type,
7608              tree name,
7609              const cp_decl_specifier_seq *declspecs,
7610              int initialized,
7611              int constp,
7612              tree scope)
7613 {
7614   tree decl;
7615   tree explicit_scope;
7616
7617   gcc_assert (!name || TREE_CODE (name) == IDENTIFIER_NODE);
7618
7619   /* Compute the scope in which to place the variable, but remember
7620      whether or not that scope was explicitly specified by the user.   */
7621   explicit_scope = scope;
7622   if (!scope)
7623     {
7624       /* An explicit "extern" specifier indicates a namespace-scope
7625          variable.  */
7626       if (declspecs->storage_class == sc_extern)
7627         scope = current_decl_namespace ();
7628       else if (!at_function_scope_p ())
7629         scope = current_scope ();
7630     }
7631
7632   if (scope
7633       && (/* If the variable is a namespace-scope variable declared in a
7634              template, we need DECL_LANG_SPECIFIC.  */
7635           (TREE_CODE (scope) == NAMESPACE_DECL && processing_template_decl)
7636           /* Similarly for namespace-scope variables with language linkage
7637              other than C++.  */
7638           || (TREE_CODE (scope) == NAMESPACE_DECL
7639               && current_lang_name != lang_name_cplusplus)
7640           /* Similarly for static data members.  */
7641           || TYPE_P (scope)))
7642     decl = build_lang_decl (VAR_DECL, name, type);
7643   else
7644     decl = build_decl (input_location, VAR_DECL, name, type);
7645
7646   if (explicit_scope && TREE_CODE (explicit_scope) == NAMESPACE_DECL)
7647     set_decl_namespace (decl, explicit_scope, 0);
7648   else
7649     DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
7650
7651   if (declspecs->storage_class == sc_extern)
7652     {
7653       DECL_THIS_EXTERN (decl) = 1;
7654       DECL_EXTERNAL (decl) = !initialized;
7655     }
7656
7657   if (DECL_CLASS_SCOPE_P (decl))
7658     {
7659       set_linkage_for_static_data_member (decl);
7660       /* This function is only called with out-of-class definitions.  */
7661       DECL_EXTERNAL (decl) = 0;
7662       check_class_member_definition_namespace (decl);
7663     }
7664   /* At top level, either `static' or no s.c. makes a definition
7665      (perhaps tentative), and absence of `static' makes it public.  */
7666   else if (toplevel_bindings_p ())
7667     {
7668       TREE_PUBLIC (decl) = (declspecs->storage_class != sc_static
7669                             && (DECL_THIS_EXTERN (decl) || ! constp));
7670       TREE_STATIC (decl) = ! DECL_EXTERNAL (decl);
7671     }
7672   /* Not at top level, only `static' makes a static definition.  */
7673   else
7674     {
7675       TREE_STATIC (decl) = declspecs->storage_class == sc_static;
7676       TREE_PUBLIC (decl) = DECL_EXTERNAL (decl);
7677     }
7678
7679   if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
7680     DECL_TLS_MODEL (decl) = decl_default_tls_model (decl);
7681
7682   /* If the type of the decl has no linkage, make sure that we'll
7683      notice that in mark_used.  */
7684   if (cxx_dialect > cxx98
7685       && decl_linkage (decl) != lk_none
7686       && DECL_LANG_SPECIFIC (decl) == NULL
7687       && !DECL_EXTERN_C_P (decl)
7688       && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
7689     retrofit_lang_decl (decl);
7690
7691   if (TREE_PUBLIC (decl))
7692     {
7693       /* [basic.link]: A name with no linkage (notably, the name of a class
7694          or enumeration declared in a local scope) shall not be used to
7695          declare an entity with linkage.
7696
7697          DR 757 relaxes this restriction for C++0x.  */
7698       tree t = (cxx_dialect > cxx98 ? NULL_TREE
7699                 : no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false));
7700       if (t)
7701         {
7702           if (TYPE_ANONYMOUS_P (t))
7703             {
7704               if (DECL_EXTERN_C_P (decl))
7705                 /* Allow this; it's pretty common in C.  */
7706                 ;
7707               else
7708                 {
7709                   /* DRs 132, 319 and 389 seem to indicate types with
7710                      no linkage can only be used to declare extern "C"
7711                      entities.  Since it's not always an error in the
7712                      ISO C++ 90 Standard, we only issue a warning.  */
7713                   warning (0, "anonymous type with no linkage used to declare "
7714                            "variable %q#D with linkage", decl);
7715                   if (DECL_ORIGINAL_TYPE (TYPE_NAME (t)))
7716                     warning (0, "%q+#D does not refer to the unqualified "
7717                              "type, so it is not used for linkage",
7718                              TYPE_NAME (t));
7719                 }
7720             }
7721           else
7722             warning (0, "type %qT with no linkage used to declare variable "
7723                      "%q#D with linkage", t, decl);
7724         }
7725     }
7726   else
7727     DECL_INTERFACE_KNOWN (decl) = 1;
7728
7729   return decl;
7730 }
7731
7732 /* Create and return a canonical pointer to member function type, for
7733    TYPE, which is a POINTER_TYPE to a METHOD_TYPE.  */
7734
7735 tree
7736 build_ptrmemfunc_type (tree type)
7737 {
7738   tree field, fields;
7739   tree t;
7740   tree unqualified_variant = NULL_TREE;
7741
7742   if (type == error_mark_node)
7743     return type;
7744
7745   /* If a canonical type already exists for this type, use it.  We use
7746      this method instead of type_hash_canon, because it only does a
7747      simple equality check on the list of field members.  */
7748
7749   if ((t = TYPE_GET_PTRMEMFUNC_TYPE (type)))
7750     return t;
7751
7752   /* Make sure that we always have the unqualified pointer-to-member
7753      type first.  */
7754   if (cp_type_quals (type) != TYPE_UNQUALIFIED)
7755     unqualified_variant
7756       = build_ptrmemfunc_type (TYPE_MAIN_VARIANT (type));
7757
7758   t = make_class_type (RECORD_TYPE);
7759   xref_basetypes (t, NULL_TREE);
7760
7761   /* Let the front end know this is a pointer to member function...  */
7762   TYPE_PTRMEMFUNC_FLAG (t) = 1;
7763   /* ... and not really a class type.  */
7764   SET_CLASS_TYPE_P (t, 0);
7765
7766   field = build_decl (input_location, FIELD_DECL, pfn_identifier, type);
7767   fields = field;
7768
7769   field = build_decl (input_location, FIELD_DECL, delta_identifier, 
7770                       delta_type_node);
7771   DECL_CHAIN (field) = fields;
7772   fields = field;
7773
7774   finish_builtin_struct (t, "__ptrmemfunc_type", fields, ptr_type_node);
7775
7776   /* Zap out the name so that the back end will give us the debugging
7777      information for this anonymous RECORD_TYPE.  */
7778   TYPE_NAME (t) = NULL_TREE;
7779
7780   /* If this is not the unqualified form of this pointer-to-member
7781      type, set the TYPE_MAIN_VARIANT for this type to be the
7782      unqualified type.  Since they are actually RECORD_TYPEs that are
7783      not variants of each other, we must do this manually.
7784      As we just built a new type there is no need to do yet another copy.  */
7785   if (cp_type_quals (type) != TYPE_UNQUALIFIED)
7786     {
7787       int type_quals = cp_type_quals (type);
7788       TYPE_READONLY (t) = (type_quals & TYPE_QUAL_CONST) != 0;
7789       TYPE_VOLATILE (t) = (type_quals & TYPE_QUAL_VOLATILE) != 0;
7790       TYPE_RESTRICT (t) = (type_quals & TYPE_QUAL_RESTRICT) != 0;
7791       TYPE_MAIN_VARIANT (t) = unqualified_variant;
7792       TYPE_NEXT_VARIANT (t) = TYPE_NEXT_VARIANT (unqualified_variant);
7793       TYPE_NEXT_VARIANT (unqualified_variant) = t;
7794       TREE_TYPE (TYPE_BINFO (t)) = t;
7795     }
7796
7797   /* Cache this pointer-to-member type so that we can find it again
7798      later.  */
7799   TYPE_SET_PTRMEMFUNC_TYPE (type, t);
7800
7801   if (TYPE_STRUCTURAL_EQUALITY_P (type))
7802     SET_TYPE_STRUCTURAL_EQUALITY (t);
7803   else if (TYPE_CANONICAL (type) != type)
7804     TYPE_CANONICAL (t) = build_ptrmemfunc_type (TYPE_CANONICAL (type));
7805
7806   return t;
7807 }
7808
7809 /* Create and return a pointer to data member type.  */
7810
7811 tree
7812 build_ptrmem_type (tree class_type, tree member_type)
7813 {
7814   if (TREE_CODE (member_type) == METHOD_TYPE)
7815     {
7816       cp_cv_quals quals = type_memfn_quals (member_type);
7817       member_type = build_memfn_type (member_type, class_type, quals);
7818       return build_ptrmemfunc_type (build_pointer_type (member_type));
7819     }
7820   else
7821     {
7822       gcc_assert (TREE_CODE (member_type) != FUNCTION_TYPE);
7823       return build_offset_type (class_type, member_type);
7824     }
7825 }
7826
7827 /* DECL is a VAR_DECL defined in-class, whose TYPE is also given.
7828    Check to see that the definition is valid.  Issue appropriate error
7829    messages.  Return 1 if the definition is particularly bad, or 0
7830    otherwise.  */
7831
7832 static int
7833 check_static_variable_definition (tree decl, tree type)
7834 {
7835   /* Can't check yet if we don't know the type.  */
7836   if (dependent_type_p (type))
7837     return 0;
7838   /* If DECL is declared constexpr, we'll do the appropriate checks
7839      in check_initializer.  */
7840   if (DECL_P (decl) && DECL_DECLARED_CONSTEXPR_P (decl))
7841     return 0;
7842   else if (cxx_dialect >= cxx0x && !INTEGRAL_OR_ENUMERATION_TYPE_P (type))
7843     {
7844       if (!COMPLETE_TYPE_P (type))
7845         error ("in-class initialization of static data member %q#D of "
7846                "incomplete type", decl);
7847       else if (literal_type_p (type))
7848         permerror (input_location,
7849                    "%<constexpr%> needed for in-class initialization of "
7850                    "static data member %q#D of non-integral type", decl);
7851       else
7852         error ("in-class initialization of static data member %q#D of "
7853                "non-literal type", decl);
7854       return 1;
7855     }
7856
7857   /* Motion 10 at San Diego: If a static const integral data member is
7858      initialized with an integral constant expression, the initializer
7859      may appear either in the declaration (within the class), or in
7860      the definition, but not both.  If it appears in the class, the
7861      member is a member constant.  The file-scope definition is always
7862      required.  */
7863   if (!ARITHMETIC_TYPE_P (type) && TREE_CODE (type) != ENUMERAL_TYPE)
7864     {
7865       error ("invalid in-class initialization of static data member "
7866              "of non-integral type %qT",
7867              type);
7868       return 1;
7869     }
7870   else if (!CP_TYPE_CONST_P (type))
7871     error ("ISO C++ forbids in-class initialization of non-const "
7872            "static member %qD",
7873            decl);
7874   else if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type))
7875     pedwarn (input_location, OPT_Wpedantic, "ISO C++ forbids initialization of member constant "
7876              "%qD of non-integral type %qT", decl, type);
7877
7878   return 0;
7879 }
7880
7881 /* *expr_p is part of the TYPE_SIZE of a variably-sized array.  If any
7882    SAVE_EXPRs in *expr_p wrap expressions with side-effects, break those
7883    expressions out into temporary variables so that walk_tree doesn't
7884    step into them (c++/15764).  */
7885
7886 static tree
7887 stabilize_save_expr_r (tree *expr_p, int *walk_subtrees, void *data)
7888 {
7889   struct pointer_set_t *pset = (struct pointer_set_t *)data;
7890   tree expr = *expr_p;
7891   if (TREE_CODE (expr) == SAVE_EXPR)
7892     {
7893       tree op = TREE_OPERAND (expr, 0);
7894       cp_walk_tree (&op, stabilize_save_expr_r, data, pset);
7895       if (TREE_SIDE_EFFECTS (op))
7896         TREE_OPERAND (expr, 0) = get_temp_regvar (TREE_TYPE (op), op);
7897       *walk_subtrees = 0;
7898     }
7899   else if (!EXPR_P (expr) || !TREE_SIDE_EFFECTS (expr))
7900     *walk_subtrees = 0;
7901   return NULL;
7902 }
7903
7904 /* Entry point for the above.  */
7905
7906 static void
7907 stabilize_vla_size (tree size)
7908 {
7909   struct pointer_set_t *pset = pointer_set_create ();
7910   /* Break out any function calls into temporary variables.  */
7911   cp_walk_tree (&size, stabilize_save_expr_r, pset, pset);
7912 }
7913
7914 /* Given the SIZE (i.e., number of elements) in an array, compute an
7915    appropriate index type for the array.  If non-NULL, NAME is the
7916    name of the thing being declared.  */
7917
7918 tree
7919 compute_array_index_type (tree name, tree size, tsubst_flags_t complain)
7920 {
7921   tree itype;
7922   tree osize = size;
7923   tree abi_1_itype = NULL_TREE;
7924
7925   if (error_operand_p (size))
7926     return error_mark_node;
7927
7928   if (!type_dependent_expression_p (size))
7929     {
7930       tree type = TREE_TYPE (size);
7931
7932       mark_rvalue_use (size);
7933
7934       if (cxx_dialect < cxx0x && TREE_CODE (size) == NOP_EXPR
7935           && TREE_SIDE_EFFECTS (size))
7936         /* In C++98, we mark a non-constant array bound with a magic
7937            NOP_EXPR with TREE_SIDE_EFFECTS; don't fold in that case.  */;
7938       else
7939         {
7940           size = fold_non_dependent_expr (size);
7941
7942           if (CLASS_TYPE_P (type)
7943               && CLASSTYPE_LITERAL_P (type))
7944             {
7945               size = build_expr_type_conversion (WANT_INT, size, true);
7946               if (!size)
7947                 {
7948                   if (!(complain & tf_error))
7949                     return error_mark_node;
7950                   if (name)
7951                     error ("size of array %qD has non-integral type %qT",
7952                            name, type);
7953                   else
7954                     error ("size of array has non-integral type %qT", type);
7955                   size = integer_one_node;
7956                 }
7957               if (size == error_mark_node)
7958                 return error_mark_node;
7959               type = TREE_TYPE (size);
7960               /* We didn't support this case in GCC 3.2, so don't bother
7961                  trying to model it now in ABI v1.  */
7962               abi_1_itype = error_mark_node;
7963             }
7964
7965           size = maybe_constant_value (size);
7966           if (!TREE_CONSTANT (size))
7967             size = osize;
7968         }
7969
7970       if (error_operand_p (size))
7971         return error_mark_node;
7972
7973       /* The array bound must be an integer type.  */
7974       if (!INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
7975         {
7976           if (!(complain & tf_error))
7977             return error_mark_node;
7978           if (name)
7979             error ("size of array %qD has non-integral type %qT", name, type);
7980           else
7981             error ("size of array has non-integral type %qT", type);
7982           size = integer_one_node;
7983           type = TREE_TYPE (size);
7984         }
7985     }
7986
7987   /* A type is dependent if it is...an array type constructed from any
7988      dependent type or whose size is specified by a constant expression
7989      that is value-dependent.  */
7990   /* We can only call value_dependent_expression_p on integral constant
7991      expressions; treat non-constant expressions as dependent, too.  */
7992   if (processing_template_decl
7993       && (type_dependent_expression_p (size)
7994           || !TREE_CONSTANT (size) || value_dependent_expression_p (size)))
7995     {
7996       /* We cannot do any checking for a SIZE that isn't known to be
7997          constant. Just build the index type and mark that it requires
7998          structural equality checks.  */
7999       itype = build_index_type (build_min (MINUS_EXPR, sizetype,
8000                                            size, integer_one_node));
8001       TYPE_DEPENDENT_P (itype) = 1;
8002       TYPE_DEPENDENT_P_VALID (itype) = 1;
8003       SET_TYPE_STRUCTURAL_EQUALITY (itype);
8004       return itype;
8005     }
8006   
8007   if (!abi_version_at_least (2) && processing_template_decl
8008       && abi_1_itype == NULL_TREE)
8009     /* For abi-1, we handled all instances in templates the same way,
8010        even when they were non-dependent. This affects the manglings
8011        produced.  So, we do the normal checking for non-dependent
8012        sizes, but at the end we'll return the same type that abi-1
8013        would have, but with TYPE_CANONICAL set to the "right"
8014        value that the current ABI would provide. */
8015     abi_1_itype = build_index_type (build_min (MINUS_EXPR, sizetype,
8016                                                osize, integer_one_node));
8017
8018   /* Normally, the array-bound will be a constant.  */
8019   if (TREE_CODE (size) == INTEGER_CST)
8020     {
8021       /* Check to see if the array bound overflowed.  Make that an
8022          error, no matter how generous we're being.  */
8023       constant_expression_error (size);
8024
8025       /* An array must have a positive number of elements.  */
8026       if (INT_CST_LT (size, integer_zero_node))
8027         {
8028           if (!(complain & tf_error))
8029             return error_mark_node;
8030           if (name)
8031             error ("size of array %qD is negative", name);
8032           else
8033             error ("size of array is negative");
8034           size = integer_one_node;
8035         }
8036       /* As an extension we allow zero-sized arrays.  */
8037       else if (integer_zerop (size))
8038         {
8039           if (!(complain & tf_error))
8040             /* We must fail if performing argument deduction (as
8041                indicated by the state of complain), so that
8042                another substitution can be found.  */
8043             return error_mark_node;
8044           else if (in_system_header)
8045             /* Allow them in system headers because glibc uses them.  */;
8046           else if (name)
8047             pedwarn (input_location, OPT_Wpedantic, "ISO C++ forbids zero-size array %qD", name);
8048           else
8049             pedwarn (input_location, OPT_Wpedantic, "ISO C++ forbids zero-size array");
8050         }
8051     }
8052   else if (TREE_CONSTANT (size)
8053            /* We don't allow VLAs at non-function scopes, or during
8054               tentative template substitution.  */
8055            || !at_function_scope_p () || !(complain & tf_error))
8056     {
8057       if (!(complain & tf_error))
8058         return error_mark_node;
8059       /* `(int) &fn' is not a valid array bound.  */
8060       if (name)
8061         error ("size of array %qD is not an integral constant-expression",
8062                name);
8063       else
8064         error ("size of array is not an integral constant-expression");
8065       size = integer_one_node;
8066     }
8067   else if (pedantic && warn_vla != 0)
8068     {
8069       if (name)
8070         pedwarn (input_location, OPT_Wvla, "ISO C++ forbids variable length array %qD", name);
8071       else
8072         pedwarn (input_location, OPT_Wvla, "ISO C++ forbids variable length array");
8073     }
8074   else if (warn_vla > 0)
8075     {
8076       if (name)
8077         warning (OPT_Wvla, 
8078                  "variable length array %qD is used", name);
8079       else
8080         warning (OPT_Wvla, 
8081                  "variable length array is used");
8082     }
8083
8084   if (processing_template_decl && !TREE_CONSTANT (size))
8085     /* A variable sized array.  */
8086     itype = build_min (MINUS_EXPR, sizetype, size, integer_one_node);
8087   else
8088     {
8089       HOST_WIDE_INT saved_processing_template_decl;
8090
8091       /* Compute the index of the largest element in the array.  It is
8092          one less than the number of elements in the array.  We save
8093          and restore PROCESSING_TEMPLATE_DECL so that computations in
8094          cp_build_binary_op will be appropriately folded.  */
8095       saved_processing_template_decl = processing_template_decl;
8096       processing_template_decl = 0;
8097       itype = cp_build_binary_op (input_location,
8098                                   MINUS_EXPR,
8099                                   cp_convert (ssizetype, size, complain),
8100                                   cp_convert (ssizetype, integer_one_node,
8101                                               complain),
8102                                   complain);
8103       itype = fold (itype);
8104       processing_template_decl = saved_processing_template_decl;
8105
8106       if (!TREE_CONSTANT (itype))
8107         /* A variable sized array.  */
8108         itype = variable_size (itype);
8109       /* Make sure that there was no overflow when creating to a signed
8110          index type.  (For example, on a 32-bit machine, an array with
8111          size 2^32 - 1 is too big.)  */
8112       else if (TREE_CODE (itype) == INTEGER_CST
8113                && TREE_OVERFLOW (itype))
8114         {
8115           if (!(complain & tf_error))
8116             return error_mark_node;
8117           error ("overflow in array dimension");
8118           TREE_OVERFLOW (itype) = 0;
8119         }
8120     }
8121
8122   /* Create and return the appropriate index type.  */
8123   if (abi_1_itype && abi_1_itype != error_mark_node)
8124     {
8125       tree t = build_index_type (itype);
8126       TYPE_CANONICAL (abi_1_itype) = TYPE_CANONICAL (t);
8127       itype = abi_1_itype;
8128     }
8129   else
8130     itype = build_index_type (itype);
8131
8132   /* If the index type were dependent, we would have returned early, so
8133      remember that it isn't.  */
8134   TYPE_DEPENDENT_P (itype) = 0;
8135   TYPE_DEPENDENT_P_VALID (itype) = 1;
8136   return itype;
8137 }
8138
8139 /* Returns the scope (if any) in which the entity declared by
8140    DECLARATOR will be located.  If the entity was declared with an
8141    unqualified name, NULL_TREE is returned.  */
8142
8143 tree
8144 get_scope_of_declarator (const cp_declarator *declarator)
8145 {
8146   while (declarator && declarator->kind != cdk_id)
8147     declarator = declarator->declarator;
8148
8149   /* If the declarator-id is a SCOPE_REF, the scope in which the
8150      declaration occurs is the first operand.  */
8151   if (declarator
8152       && declarator->u.id.qualifying_scope)
8153     return declarator->u.id.qualifying_scope;
8154
8155   /* Otherwise, the declarator is not a qualified name; the entity will
8156      be declared in the current scope.  */
8157   return NULL_TREE;
8158 }
8159
8160 /* Returns an ARRAY_TYPE for an array with SIZE elements of the
8161    indicated TYPE.  If non-NULL, NAME is the NAME of the declaration
8162    with this type.  */
8163
8164 static tree
8165 create_array_type_for_decl (tree name, tree type, tree size)
8166 {
8167   tree itype = NULL_TREE;
8168
8169   /* If things have already gone awry, bail now.  */
8170   if (type == error_mark_node || size == error_mark_node)
8171     return error_mark_node;
8172
8173   /* 8.3.4/1: If the type of the identifier of D contains the auto
8174      type-specifier, the program is ill-formed.  */
8175   if (pedantic && type_uses_auto (type))
8176     pedwarn (input_location, OPT_Wpedantic,
8177              "declaration of %qD as array of %<auto%>", name);
8178
8179   /* If there are some types which cannot be array elements,
8180      issue an error-message and return.  */
8181   switch (TREE_CODE (type))
8182     {
8183     case VOID_TYPE:
8184       if (name)
8185         error ("declaration of %qD as array of void", name);
8186       else
8187         error ("creating array of void");
8188       return error_mark_node;
8189
8190     case FUNCTION_TYPE:
8191       if (name)
8192         error ("declaration of %qD as array of functions", name);
8193       else
8194         error ("creating array of functions");
8195       return error_mark_node;
8196
8197     case REFERENCE_TYPE:
8198       if (name)
8199         error ("declaration of %qD as array of references", name);
8200       else
8201         error ("creating array of references");
8202       return error_mark_node;
8203
8204     case METHOD_TYPE:
8205       if (name)
8206         error ("declaration of %qD as array of function members", name);
8207       else
8208         error ("creating array of function members");
8209       return error_mark_node;
8210
8211     default:
8212       break;
8213     }
8214
8215   /* [dcl.array]
8216
8217      The constant expressions that specify the bounds of the arrays
8218      can be omitted only for the first member of the sequence.  */
8219   if (TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type))
8220     {
8221       if (name)
8222         error ("declaration of %qD as multidimensional array must "
8223                "have bounds for all dimensions except the first",
8224                name);
8225       else
8226         error ("multidimensional array must have bounds for all "
8227                "dimensions except the first");
8228
8229       return error_mark_node;
8230     }
8231
8232   /* Figure out the index type for the array.  */
8233   if (size)
8234     itype = compute_array_index_type (name, size, tf_warning_or_error);
8235
8236   /* [dcl.array]
8237      T is called the array element type; this type shall not be [...] an
8238      abstract class type.  */
8239   abstract_virtuals_error (name, type);
8240
8241   return build_cplus_array_type (type, itype);
8242 }
8243
8244 /* Check that it's OK to declare a function with the indicated TYPE.
8245    SFK indicates the kind of special function (if any) that this
8246    function is.  OPTYPE is the type given in a conversion operator
8247    declaration, or the class type for a constructor/destructor.
8248    Returns the actual return type of the function; that
8249    may be different than TYPE if an error occurs, or for certain
8250    special functions.  */
8251
8252 static tree
8253 check_special_function_return_type (special_function_kind sfk,
8254                                     tree type,
8255                                     tree optype)
8256 {
8257   switch (sfk)
8258     {
8259     case sfk_constructor:
8260       if (type)
8261         error ("return type specification for constructor invalid");
8262
8263       if (targetm.cxx.cdtor_returns_this () && !TYPE_FOR_JAVA (optype))
8264         type = build_pointer_type (optype);
8265       else
8266         type = void_type_node;
8267       break;
8268
8269     case sfk_destructor:
8270       if (type)
8271         error ("return type specification for destructor invalid");
8272       /* We can't use the proper return type here because we run into
8273          problems with ambiguous bases and covariant returns.
8274          Java classes are left unchanged because (void *) isn't a valid
8275          Java type, and we don't want to change the Java ABI.  */
8276       if (targetm.cxx.cdtor_returns_this () && !TYPE_FOR_JAVA (optype))
8277         type = build_pointer_type (void_type_node);
8278       else
8279         type = void_type_node;
8280       break;
8281
8282     case sfk_conversion:
8283       if (type)
8284         error ("return type specified for %<operator %T%>",  optype);
8285       type = optype;
8286       break;
8287
8288     default:
8289       gcc_unreachable ();
8290     }
8291
8292   return type;
8293 }
8294
8295 /* A variable or data member (whose unqualified name is IDENTIFIER)
8296    has been declared with the indicated TYPE.  If the TYPE is not
8297    acceptable, issue an error message and return a type to use for
8298    error-recovery purposes.  */
8299
8300 tree
8301 check_var_type (tree identifier, tree type)
8302 {
8303   if (VOID_TYPE_P (type))
8304     {
8305       if (!identifier)
8306         error ("unnamed variable or field declared void");
8307       else if (TREE_CODE (identifier) == IDENTIFIER_NODE)
8308         {
8309           gcc_assert (!IDENTIFIER_OPNAME_P (identifier));
8310           error ("variable or field %qE declared void", identifier);
8311         }
8312       else
8313         error ("variable or field declared void");
8314       type = error_mark_node;
8315     }
8316
8317   return type;
8318 }
8319
8320 /* Given declspecs and a declarator (abstract or otherwise), determine
8321    the name and type of the object declared and construct a DECL node
8322    for it.
8323
8324    DECLSPECS points to the representation of declaration-specifier
8325    sequence that precedes declarator.
8326
8327    DECL_CONTEXT says which syntactic context this declaration is in:
8328      NORMAL for most contexts.  Make a VAR_DECL or FUNCTION_DECL or TYPE_DECL.
8329      FUNCDEF for a function definition.  Like NORMAL but a few different
8330       error messages in each case.  Return value may be zero meaning
8331       this definition is too screwy to try to parse.
8332      MEMFUNCDEF for a function definition.  Like FUNCDEF but prepares to
8333       handle member functions (which have FIELD context).
8334       Return value may be zero meaning this definition is too screwy to
8335       try to parse.
8336      PARM for a parameter declaration (either within a function prototype
8337       or before a function body).  Make a PARM_DECL, or return void_type_node.
8338      TPARM for a template parameter declaration.
8339      CATCHPARM for a parameter declaration before a catch clause.
8340      TYPENAME if for a typename (in a cast or sizeof).
8341       Don't make a DECL node; just return the ..._TYPE node.
8342      FIELD for a struct or union field; make a FIELD_DECL.
8343      BITFIELD for a field with specified width.
8344
8345    INITIALIZED is as for start_decl.
8346
8347    ATTRLIST is a pointer to the list of attributes, which may be NULL
8348    if there are none; *ATTRLIST may be modified if attributes from inside
8349    the declarator should be applied to the declaration.
8350
8351    When this function is called, scoping variables (such as
8352    CURRENT_CLASS_TYPE) should reflect the scope in which the
8353    declaration occurs, not the scope in which the new declaration will
8354    be placed.  For example, on:
8355
8356      void S::f() { ... }
8357
8358    when grokdeclarator is called for `S::f', the CURRENT_CLASS_TYPE
8359    should not be `S'.
8360
8361    Returns a DECL (if a declarator is present), a TYPE (if there is no
8362    declarator, in cases like "struct S;"), or the ERROR_MARK_NODE if an
8363    error occurs. */
8364
8365 tree
8366 grokdeclarator (const cp_declarator *declarator,
8367                 const cp_decl_specifier_seq *declspecs,
8368                 enum decl_context decl_context,
8369                 int initialized,
8370                 tree* attrlist)
8371 {
8372   tree type = NULL_TREE;
8373   int longlong = 0;
8374   int explicit_int128 = 0;
8375   int virtualp, explicitp, friendp, inlinep, staticp;
8376   int explicit_int = 0;
8377   int explicit_char = 0;
8378   int defaulted_int = 0;
8379   tree dependent_name = NULL_TREE;
8380
8381   tree typedef_decl = NULL_TREE;
8382   const char *name = NULL;
8383   tree typedef_type = NULL_TREE;
8384   /* True if this declarator is a function definition.  */
8385   bool funcdef_flag = false;
8386   cp_declarator_kind innermost_code = cdk_error;
8387   int bitfield = 0;
8388 #if 0
8389   /* See the code below that used this.  */
8390   tree decl_attr = NULL_TREE;
8391 #endif
8392
8393   /* Keep track of what sort of function is being processed
8394      so that we can warn about default return values, or explicit
8395      return values which do not match prescribed defaults.  */
8396   special_function_kind sfk = sfk_none;
8397
8398   tree dname = NULL_TREE;
8399   tree ctor_return_type = NULL_TREE;
8400   enum overload_flags flags = NO_SPECIAL;
8401   /* cv-qualifiers that apply to the declarator, for a declaration of
8402      a member function.  */
8403   cp_cv_quals memfn_quals = TYPE_UNQUALIFIED;
8404   /* virt-specifiers that apply to the declarator, for a declaration of
8405      a member function.  */
8406   cp_virt_specifiers virt_specifiers = VIRT_SPEC_UNSPECIFIED;
8407   /* cv-qualifiers that apply to the type specified by the DECLSPECS.  */
8408   int type_quals;
8409   tree raises = NULL_TREE;
8410   int template_count = 0;
8411   tree returned_attrs = NULL_TREE;
8412   tree parms = NULL_TREE;
8413   const cp_declarator *id_declarator;
8414   /* The unqualified name of the declarator; either an
8415      IDENTIFIER_NODE, BIT_NOT_EXPR, or TEMPLATE_ID_EXPR.  */
8416   tree unqualified_id;
8417   /* The class type, if any, in which this entity is located,
8418      or NULL_TREE if none.  Note that this value may be different from
8419      the current class type; for example if an attempt is made to declare
8420      "A::f" inside "B", this value will be "A".  */
8421   tree ctype = current_class_type;
8422   /* The NAMESPACE_DECL for the namespace in which this entity is
8423      located.  If an unqualified name is used to declare the entity,
8424      this value will be NULL_TREE, even if the entity is located at
8425      namespace scope.  */
8426   tree in_namespace = NULL_TREE;
8427   cp_storage_class storage_class;
8428   bool unsigned_p, signed_p, short_p, long_p, thread_p;
8429   bool type_was_error_mark_node = false;
8430   bool parameter_pack_p = declarator? declarator->parameter_pack_p : false;
8431   bool template_type_arg = false;
8432   bool template_parm_flag = false;
8433   bool constexpr_p = decl_spec_seq_has_spec_p (declspecs, ds_constexpr);
8434   const char *errmsg;
8435
8436   signed_p = decl_spec_seq_has_spec_p (declspecs, ds_signed);
8437   unsigned_p = decl_spec_seq_has_spec_p (declspecs, ds_unsigned);
8438   short_p = decl_spec_seq_has_spec_p (declspecs, ds_short);
8439   long_p = decl_spec_seq_has_spec_p (declspecs, ds_long);
8440   longlong = decl_spec_seq_has_spec_p (declspecs, ds_long_long);
8441   explicit_int128 = declspecs->explicit_int128_p;
8442   thread_p = decl_spec_seq_has_spec_p (declspecs, ds_thread);
8443
8444   if (decl_context == FUNCDEF)
8445     funcdef_flag = true, decl_context = NORMAL;
8446   else if (decl_context == MEMFUNCDEF)
8447     funcdef_flag = true, decl_context = FIELD;
8448   else if (decl_context == BITFIELD)
8449     bitfield = 1, decl_context = FIELD;
8450   else if (decl_context == TEMPLATE_TYPE_ARG)
8451     template_type_arg = true, decl_context = TYPENAME;
8452   else if (decl_context == TPARM)
8453     template_parm_flag = true, decl_context = PARM;
8454
8455   if (initialized > 1)
8456     funcdef_flag = true;
8457
8458   /* Look inside a declarator for the name being declared
8459      and get it as a string, for an error message.  */
8460   for (id_declarator = declarator;
8461        id_declarator;
8462        id_declarator = id_declarator->declarator)
8463     {
8464       if (id_declarator->kind != cdk_id)
8465         innermost_code = id_declarator->kind;
8466
8467       switch (id_declarator->kind)
8468         {
8469         case cdk_function:
8470           if (id_declarator->declarator
8471               && id_declarator->declarator->kind == cdk_id)
8472             {
8473               sfk = id_declarator->declarator->u.id.sfk;
8474               if (sfk == sfk_destructor)
8475                 flags = DTOR_FLAG;
8476             }
8477           break;
8478
8479         case cdk_id:
8480           {
8481             tree qualifying_scope = id_declarator->u.id.qualifying_scope;
8482             tree decl = id_declarator->u.id.unqualified_name;
8483             if (!decl)
8484               break;
8485             if (qualifying_scope)
8486               {
8487                 if (at_function_scope_p ())
8488                   {
8489                     /* [dcl.meaning] 
8490
8491                        A declarator-id shall not be qualified except
8492                        for ... 
8493
8494                        None of the cases are permitted in block
8495                        scope.  */
8496                     if (qualifying_scope == global_namespace)
8497                       error ("invalid use of qualified-name %<::%D%>",
8498                              decl);
8499                     else if (TYPE_P (qualifying_scope))
8500                       error ("invalid use of qualified-name %<%T::%D%>",
8501                              qualifying_scope, decl);
8502                     else 
8503                       error ("invalid use of qualified-name %<%D::%D%>",
8504                              qualifying_scope, decl);
8505                     return error_mark_node;
8506                   }
8507                 else if (TYPE_P (qualifying_scope))
8508                   {
8509                     ctype = qualifying_scope;
8510                     if (!MAYBE_CLASS_TYPE_P (ctype))
8511                       {
8512                         error ("%q#T is not a class or a namespace", ctype);
8513                         ctype = NULL_TREE;
8514                       }
8515                     else if (innermost_code != cdk_function
8516                              && current_class_type
8517                              && !UNIQUELY_DERIVED_FROM_P (ctype,
8518                                                           current_class_type))
8519                       {
8520                         error ("type %qT is not derived from type %qT",
8521                                ctype, current_class_type);
8522                         return error_mark_node;
8523                       }
8524                   }
8525                 else if (TREE_CODE (qualifying_scope) == NAMESPACE_DECL)
8526                   in_namespace = qualifying_scope;
8527               }
8528             switch (TREE_CODE (decl))
8529               {
8530               case BIT_NOT_EXPR:
8531                 {
8532                   tree type;
8533
8534                   if (innermost_code != cdk_function)
8535                     {
8536                       error ("declaration of %qD as non-function", decl);
8537                       return error_mark_node;
8538                     }
8539                   else if (!qualifying_scope
8540                            && !(current_class_type && at_class_scope_p ()))
8541                     {
8542                       error ("declaration of %qD as non-member", decl);
8543                       return error_mark_node;
8544                     }
8545
8546                   type = TREE_OPERAND (decl, 0);
8547                   if (TYPE_P (type))
8548                     type = constructor_name (type);
8549                   name = identifier_to_locale (IDENTIFIER_POINTER (type));
8550                   dname = decl;
8551                 }
8552                 break;
8553
8554               case TEMPLATE_ID_EXPR:
8555                 {
8556                   tree fns = TREE_OPERAND (decl, 0);
8557
8558                   dname = fns;
8559                   if (TREE_CODE (dname) != IDENTIFIER_NODE)
8560                     {
8561                       gcc_assert (is_overloaded_fn (dname));
8562                       dname = DECL_NAME (get_first_fn (dname));
8563                     }
8564                 }
8565                 /* Fall through.  */
8566
8567               case IDENTIFIER_NODE:
8568                 if (TREE_CODE (decl) == IDENTIFIER_NODE)
8569                   dname = decl;
8570
8571                 if (C_IS_RESERVED_WORD (dname))
8572                   {
8573                     error ("declarator-id missing; using reserved word %qD",
8574                            dname);
8575                     name = identifier_to_locale (IDENTIFIER_POINTER (dname));
8576                   }
8577                 else if (!IDENTIFIER_TYPENAME_P (dname))
8578                   name = identifier_to_locale (IDENTIFIER_POINTER (dname));
8579                 else
8580                   {
8581                     gcc_assert (flags == NO_SPECIAL);
8582                     flags = TYPENAME_FLAG;
8583                     ctor_return_type = TREE_TYPE (dname);
8584                     sfk = sfk_conversion;
8585                     if (is_typename_at_global_scope (dname))
8586                       name = identifier_to_locale (IDENTIFIER_POINTER (dname));
8587                     else
8588                       name = "<invalid operator>";
8589                   }
8590                 break;
8591
8592               default:
8593                 gcc_unreachable ();
8594               }
8595             break;
8596           }
8597
8598         case cdk_array:
8599         case cdk_pointer:
8600         case cdk_reference:
8601         case cdk_ptrmem:
8602           break;
8603
8604         case cdk_error:
8605           return error_mark_node;
8606
8607         default:
8608           gcc_unreachable ();
8609         }
8610       if (id_declarator->kind == cdk_id)
8611         break;
8612     }
8613
8614   /* [dcl.fct.edf]
8615
8616      The declarator in a function-definition shall have the form
8617      D1 ( parameter-declaration-clause) ...  */
8618   if (funcdef_flag && innermost_code != cdk_function)
8619     {
8620       error ("function definition does not declare parameters");
8621       return error_mark_node;
8622     }
8623
8624   if (((dname && IDENTIFIER_OPNAME_P (dname)) || flags == TYPENAME_FLAG)
8625       && innermost_code != cdk_function
8626       && ! (ctype && !declspecs->any_specifiers_p))
8627     {
8628       error ("declaration of %qD as non-function", dname);
8629       return error_mark_node;
8630     }
8631
8632   if (dname
8633       && TREE_CODE (dname) == IDENTIFIER_NODE
8634       && UDLIT_OPER_P (dname)
8635       && innermost_code != cdk_function)
8636     {
8637       error ("declaration of %qD as non-function", dname);
8638       return error_mark_node;
8639     }
8640
8641   if (dname && IDENTIFIER_OPNAME_P (dname))
8642     {
8643       if (decl_spec_seq_has_spec_p (declspecs, ds_typedef))
8644         {
8645           error ("declaration of %qD as %<typedef%>", dname);
8646           return error_mark_node;
8647         }
8648       else if (decl_context == PARM || decl_context == CATCHPARM)
8649         {
8650           error ("declaration of %qD as parameter", dname);
8651           return error_mark_node;
8652         }
8653     }
8654
8655   /* Anything declared one level down from the top level
8656      must be one of the parameters of a function
8657      (because the body is at least two levels down).  */
8658
8659   /* This heuristic cannot be applied to C++ nodes! Fixed, however,
8660      by not allowing C++ class definitions to specify their parameters
8661      with xdecls (must be spec.d in the parmlist).
8662
8663      Since we now wait to push a class scope until we are sure that
8664      we are in a legitimate method context, we must set oldcname
8665      explicitly (since current_class_name is not yet alive).
8666
8667      We also want to avoid calling this a PARM if it is in a namespace.  */
8668
8669   if (decl_context == NORMAL && !toplevel_bindings_p ())
8670     {
8671       cp_binding_level *b = current_binding_level;
8672       current_binding_level = b->level_chain;
8673       if (current_binding_level != 0 && toplevel_bindings_p ())
8674         decl_context = PARM;
8675       current_binding_level = b;
8676     }
8677
8678   if (name == NULL)
8679     name = decl_context == PARM ? "parameter" : "type name";
8680
8681   if (constexpr_p && decl_spec_seq_has_spec_p (declspecs, ds_typedef))
8682     {
8683       error ("%<constexpr%> cannot appear in a typedef declaration");
8684       return error_mark_node;
8685     }
8686
8687   /* If there were multiple types specified in the decl-specifier-seq,
8688      issue an error message.  */
8689   if (declspecs->multiple_types_p)
8690     {
8691       error ("two or more data types in declaration of %qs", name);
8692       return error_mark_node;
8693     }
8694
8695   if (declspecs->conflicting_specifiers_p)
8696     {
8697       error ("conflicting specifiers in declaration of %qs", name);
8698       return error_mark_node;
8699     }
8700
8701   /* Extract the basic type from the decl-specifier-seq.  */
8702   type = declspecs->type;
8703   if (type == error_mark_node)
8704     {
8705       type = NULL_TREE;
8706       type_was_error_mark_node = true;
8707     }
8708   /* If the entire declaration is itself tagged as deprecated then
8709      suppress reports of deprecated items.  */
8710   if (type && TREE_DEPRECATED (type)
8711       && deprecated_state != DEPRECATED_SUPPRESS)
8712     warn_deprecated_use (type, NULL_TREE);
8713   if (type && TREE_CODE (type) == TYPE_DECL)
8714     {
8715       typedef_decl = type;
8716       type = TREE_TYPE (typedef_decl);
8717       if (TREE_DEPRECATED (type)
8718           && DECL_ARTIFICIAL (typedef_decl)
8719           && deprecated_state != DEPRECATED_SUPPRESS)
8720         warn_deprecated_use (type, NULL_TREE);
8721     }
8722   /* No type at all: default to `int', and set DEFAULTED_INT
8723      because it was not a user-defined typedef.  */
8724   if (type == NULL_TREE && (signed_p || unsigned_p || long_p || short_p))
8725     {
8726       /* These imply 'int'.  */
8727       type = integer_type_node;
8728       defaulted_int = 1;
8729     }
8730   /* Gather flags.  */
8731   explicit_int = declspecs->explicit_int_p;
8732   explicit_char = declspecs->explicit_char_p;
8733
8734 #if 0
8735   /* See the code below that used this.  */
8736   if (typedef_decl)
8737     decl_attr = DECL_ATTRIBUTES (typedef_decl);
8738 #endif
8739   typedef_type = type;
8740
8741
8742   if (sfk != sfk_conversion)
8743     ctor_return_type = ctype;
8744
8745   if (sfk != sfk_none)
8746     type = check_special_function_return_type (sfk, type,
8747                                                ctor_return_type);
8748   else if (type == NULL_TREE)
8749     {
8750       int is_main;
8751
8752       explicit_int = -1;
8753
8754       /* We handle `main' specially here, because 'main () { }' is so
8755          common.  With no options, it is allowed.  With -Wreturn-type,
8756          it is a warning.  It is only an error with -pedantic-errors.  */
8757       is_main = (funcdef_flag
8758                  && dname && TREE_CODE (dname) == IDENTIFIER_NODE
8759                  && MAIN_NAME_P (dname)
8760                  && ctype == NULL_TREE
8761                  && in_namespace == NULL_TREE
8762                  && current_namespace == global_namespace);
8763
8764       if (type_was_error_mark_node)
8765         /* We've already issued an error, don't complain more.  */;
8766       else if (in_system_header || flag_ms_extensions)
8767         /* Allow it, sigh.  */;
8768       else if (! is_main)
8769         permerror (input_location, "ISO C++ forbids declaration of %qs with no type", name);
8770       else if (pedantic)
8771         pedwarn (input_location, OPT_Wpedantic,
8772                  "ISO C++ forbids declaration of %qs with no type", name);
8773       else
8774         warning (OPT_Wreturn_type,
8775                  "ISO C++ forbids declaration of %qs with no type", name);
8776
8777       type = integer_type_node;
8778     }
8779
8780   ctype = NULL_TREE;
8781
8782   if (explicit_int128)
8783     {
8784       if (int128_integer_type_node == NULL_TREE)
8785         {
8786           error ("%<__int128%> is not supported by this target");
8787           explicit_int128 = false;
8788         }
8789       else if (pedantic && ! in_system_header)
8790         pedwarn (input_location, OPT_Wpedantic,
8791                  "ISO C++ does not support %<__int128%> for %qs", name);
8792     }
8793
8794   /* Now process the modifiers that were specified
8795      and check for invalid combinations.  */
8796
8797   /* Long double is a special combination.  */
8798   if (long_p && !longlong && TYPE_MAIN_VARIANT (type) == double_type_node)
8799     {
8800       long_p = false;
8801       type = cp_build_qualified_type (long_double_type_node,
8802                                       cp_type_quals (type));
8803     }
8804
8805   /* Check all other uses of type modifiers.  */
8806
8807   if (unsigned_p || signed_p || long_p || short_p)
8808     {
8809       int ok = 0;
8810
8811       if ((signed_p || unsigned_p) && TREE_CODE (type) != INTEGER_TYPE)
8812         error ("%<signed%> or %<unsigned%> invalid for %qs", name);
8813       else if (signed_p && unsigned_p)
8814         error ("%<signed%> and %<unsigned%> specified together for %qs", name);
8815       else if (longlong && TREE_CODE (type) != INTEGER_TYPE)
8816         error ("%<long long%> invalid for %qs", name);
8817       else if (long_p && TREE_CODE (type) == REAL_TYPE)
8818         error ("%<long%> invalid for %qs", name);
8819       else if (short_p && TREE_CODE (type) == REAL_TYPE)
8820         error ("%<short%> invalid for %qs", name);
8821       else if ((long_p || short_p) && TREE_CODE (type) != INTEGER_TYPE)
8822         error ("%<long%> or %<short%> invalid for %qs", name);
8823       else if ((long_p || short_p || explicit_char || explicit_int) && explicit_int128)
8824         error ("%<long%>, %<int%>, %<short%>, or %<char%> invalid for %qs", name);
8825       else if ((long_p || short_p) && explicit_char)
8826         error ("%<long%> or %<short%> specified with char for %qs", name);
8827       else if (long_p && short_p)
8828         error ("%<long%> and %<short%> specified together for %qs", name);
8829       else if (type == char16_type_node || type == char32_type_node)
8830         {
8831           if (signed_p || unsigned_p)
8832             error ("%<signed%> or %<unsigned%> invalid for %qs", name);
8833           else if (short_p || long_p)
8834             error ("%<short%> or %<long%> invalid for %qs", name);
8835         }
8836       else
8837         {
8838           ok = 1;
8839           if (!explicit_int && !defaulted_int && !explicit_char && !explicit_int128 && pedantic)
8840             {
8841               pedwarn (input_location, OPT_Wpedantic, 
8842                        "long, short, signed or unsigned used invalidly for %qs",
8843                        name);
8844               if (flag_pedantic_errors)
8845                 ok = 0;
8846             }
8847         }
8848
8849       /* Discard the type modifiers if they are invalid.  */
8850       if (! ok)
8851         {
8852           unsigned_p = false;
8853           signed_p = false;
8854           long_p = false;
8855           short_p = false;
8856           longlong = 0;
8857         }
8858     }
8859
8860   /* Decide whether an integer type is signed or not.
8861      Optionally treat bitfields as signed by default.  */
8862   if (unsigned_p
8863       /* [class.bit]
8864
8865          It is implementation-defined whether a plain (neither
8866          explicitly signed or unsigned) char, short, int, or long
8867          bit-field is signed or unsigned.
8868
8869          Naturally, we extend this to long long as well.  Note that
8870          this does not include wchar_t.  */
8871       || (bitfield && !flag_signed_bitfields
8872           && !signed_p
8873           /* A typedef for plain `int' without `signed' can be
8874              controlled just like plain `int', but a typedef for
8875              `signed int' cannot be so controlled.  */
8876           && !(typedef_decl
8877                && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl))
8878           && TREE_CODE (type) == INTEGER_TYPE
8879           && !same_type_p (TYPE_MAIN_VARIANT (type), wchar_type_node)))
8880     {
8881       if (explicit_int128)
8882         type = int128_unsigned_type_node;
8883       else if (longlong)
8884         type = long_long_unsigned_type_node;
8885       else if (long_p)
8886         type = long_unsigned_type_node;
8887       else if (short_p)
8888         type = short_unsigned_type_node;
8889       else if (type == char_type_node)
8890         type = unsigned_char_type_node;
8891       else if (typedef_decl)
8892         type = unsigned_type_for (type);
8893       else
8894         type = unsigned_type_node;
8895     }
8896   else if (signed_p && type == char_type_node)
8897     type = signed_char_type_node;
8898   else if (explicit_int128)
8899     type = int128_integer_type_node;
8900   else if (longlong)
8901     type = long_long_integer_type_node;
8902   else if (long_p)
8903     type = long_integer_type_node;
8904   else if (short_p)
8905     type = short_integer_type_node;
8906
8907   if (decl_spec_seq_has_spec_p (declspecs, ds_complex))
8908     {
8909       if (TREE_CODE (type) != INTEGER_TYPE && TREE_CODE (type) != REAL_TYPE)
8910         error ("complex invalid for %qs", name);
8911       /* If we just have "complex", it is equivalent to
8912          "complex double", but if any modifiers at all are specified it is
8913          the complex form of TYPE.  E.g, "complex short" is
8914          "complex short int".  */
8915       else if (defaulted_int && ! longlong && ! explicit_int128
8916                && ! (long_p || short_p || signed_p || unsigned_p))
8917         type = complex_double_type_node;
8918       else if (type == integer_type_node)
8919         type = complex_integer_type_node;
8920       else if (type == float_type_node)
8921         type = complex_float_type_node;
8922       else if (type == double_type_node)
8923         type = complex_double_type_node;
8924       else if (type == long_double_type_node)
8925         type = complex_long_double_type_node;
8926       else
8927         type = build_complex_type (type);
8928     }
8929
8930   type_quals = TYPE_UNQUALIFIED;
8931   if (decl_spec_seq_has_spec_p (declspecs, ds_const))
8932     type_quals |= TYPE_QUAL_CONST;
8933   if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
8934     type_quals |= TYPE_QUAL_VOLATILE;
8935   if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
8936     type_quals |= TYPE_QUAL_RESTRICT;
8937   if (sfk == sfk_conversion && type_quals != TYPE_UNQUALIFIED)
8938     error ("qualifiers are not allowed on declaration of %<operator %T%>",
8939            ctor_return_type);
8940
8941   /* If we're using the injected-class-name to form a compound type or a
8942      declaration, replace it with the underlying class so we don't get
8943      redundant typedefs in the debug output.  But if we are returning the
8944      type unchanged, leave it alone so that it's available to
8945      maybe_get_template_decl_from_type_decl.  */
8946   if (CLASS_TYPE_P (type)
8947       && DECL_SELF_REFERENCE_P (TYPE_NAME (type))
8948       && type == TREE_TYPE (TYPE_NAME (type))
8949       && (declarator || type_quals))
8950     type = DECL_ORIGINAL_TYPE (TYPE_NAME (type));
8951
8952   type_quals |= cp_type_quals (type);
8953   type = cp_build_qualified_type_real
8954     (type, type_quals, ((typedef_decl && !DECL_ARTIFICIAL (typedef_decl)
8955                          ? tf_ignore_bad_quals : 0) | tf_warning_or_error));
8956   /* We might have ignored or rejected some of the qualifiers.  */
8957   type_quals = cp_type_quals (type);
8958
8959   staticp = 0;
8960   inlinep = decl_spec_seq_has_spec_p (declspecs, ds_inline);
8961   virtualp =  decl_spec_seq_has_spec_p (declspecs, ds_virtual);
8962   explicitp = decl_spec_seq_has_spec_p (declspecs, ds_explicit);
8963
8964   storage_class = declspecs->storage_class;
8965   if (storage_class == sc_static)
8966     staticp = 1 + (decl_context == FIELD);
8967
8968   if (virtualp && staticp == 2)
8969     {
8970       error ("member %qD cannot be declared both virtual and static", dname);
8971       storage_class = sc_none;
8972       staticp = 0;
8973     }
8974   friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
8975
8976   if (dependent_name && !friendp)
8977     {
8978       error ("%<%T::%D%> is not a valid declarator", ctype, dependent_name);
8979       return error_mark_node;
8980     }
8981
8982   /* Issue errors about use of storage classes for parameters.  */
8983   if (decl_context == PARM)
8984     {
8985       if (decl_spec_seq_has_spec_p (declspecs, ds_typedef))
8986         {
8987           error ("typedef declaration invalid in parameter declaration");
8988           return error_mark_node;
8989         }
8990       else if (template_parm_flag && storage_class != sc_none)
8991         {
8992           error ("storage class specified for template parameter %qs", name);
8993           return error_mark_node;
8994         }
8995       else if (storage_class == sc_static
8996                || storage_class == sc_extern
8997                || thread_p)
8998         error ("storage class specifiers invalid in parameter declarations");
8999
9000       /* Function parameters cannot be constexpr.  If we saw one, moan
9001          and pretend it wasn't there.  */
9002       if (constexpr_p)
9003         {
9004           error ("a parameter cannot be declared %<constexpr%>");
9005           constexpr_p = 0;
9006         }
9007     }
9008
9009   /* Give error if `virtual' is used outside of class declaration.  */
9010   if (virtualp
9011       && (current_class_name == NULL_TREE || decl_context != FIELD))
9012     {
9013       error ("%<virtual%> outside class declaration");
9014       virtualp = 0;
9015     }
9016
9017   /* Static anonymous unions are dealt with here.  */
9018   if (staticp && decl_context == TYPENAME
9019       && declspecs->type
9020       && ANON_AGGR_TYPE_P (declspecs->type))
9021     decl_context = FIELD;
9022
9023   /* Warn about storage classes that are invalid for certain
9024      kinds of declarations (parameters, typenames, etc.).  */
9025   if (thread_p
9026       && ((storage_class
9027            && storage_class != sc_extern
9028            && storage_class != sc_static)
9029           || decl_spec_seq_has_spec_p (declspecs, ds_typedef)))
9030     {
9031       error ("multiple storage classes in declaration of %qs", name);
9032       thread_p = false;
9033     }
9034   if (decl_context != NORMAL
9035       && ((storage_class != sc_none
9036            && storage_class != sc_mutable)
9037           || thread_p))
9038     {
9039       if ((decl_context == PARM || decl_context == CATCHPARM)
9040           && (storage_class == sc_register
9041               || storage_class == sc_auto))
9042         ;
9043       else if (decl_spec_seq_has_spec_p (declspecs, ds_typedef))
9044         ;
9045       else if (decl_context == FIELD
9046                /* C++ allows static class elements.  */
9047                && storage_class == sc_static)
9048         /* C++ also allows inlines and signed and unsigned elements,
9049            but in those cases we don't come in here.  */
9050         ;
9051       else
9052         {
9053           if (decl_context == FIELD)
9054             error ("storage class specified for %qs", name);
9055           else
9056             {
9057               if (decl_context == PARM || decl_context == CATCHPARM)
9058                 error ("storage class specified for parameter %qs", name);
9059               else
9060                 error ("storage class specified for typename");
9061             }
9062           if (storage_class == sc_register
9063               || storage_class == sc_auto
9064               || storage_class == sc_extern
9065               || thread_p)
9066             storage_class = sc_none;
9067         }
9068     }
9069   else if (storage_class == sc_extern && funcdef_flag
9070            && ! toplevel_bindings_p ())
9071     error ("nested function %qs declared %<extern%>", name);
9072   else if (toplevel_bindings_p ())
9073     {
9074       if (storage_class == sc_auto)
9075         error ("top-level declaration of %qs specifies %<auto%>", name);
9076     }
9077   else if (thread_p
9078            && storage_class != sc_extern
9079            && storage_class != sc_static)
9080     {
9081       error ("function-scope %qs implicitly auto and declared %<__thread%>",
9082              name);
9083       thread_p = false;
9084     }
9085
9086   if (storage_class && friendp)
9087     {
9088       error ("storage class specifiers invalid in friend function declarations");
9089       storage_class = sc_none;
9090       staticp = 0;
9091     }
9092
9093   if (!id_declarator)
9094     unqualified_id = NULL_TREE;
9095   else
9096     {
9097       unqualified_id = id_declarator->u.id.unqualified_name;
9098       switch (TREE_CODE (unqualified_id))
9099         {
9100         case BIT_NOT_EXPR:
9101           unqualified_id = TREE_OPERAND (unqualified_id, 0);
9102           if (TYPE_P (unqualified_id))
9103             unqualified_id = constructor_name (unqualified_id);
9104           break;
9105
9106         case IDENTIFIER_NODE:
9107         case TEMPLATE_ID_EXPR:
9108           break;
9109
9110         default:
9111           gcc_unreachable ();
9112         }
9113     }
9114
9115   /* Determine the type of the entity declared by recurring on the
9116      declarator.  */
9117   for (; declarator; declarator = declarator->declarator)
9118     {
9119       const cp_declarator *inner_declarator;
9120       tree attrs;
9121
9122       if (type == error_mark_node)
9123         return error_mark_node;
9124
9125       attrs = declarator->attributes;
9126       if (attrs)
9127         {
9128           int attr_flags;
9129
9130           attr_flags = 0;
9131           if (declarator == NULL || declarator->kind == cdk_id)
9132             attr_flags |= (int) ATTR_FLAG_DECL_NEXT;
9133           if (declarator->kind == cdk_function)
9134             attr_flags |= (int) ATTR_FLAG_FUNCTION_NEXT;
9135           if (declarator->kind == cdk_array)
9136             attr_flags |= (int) ATTR_FLAG_ARRAY_NEXT;
9137           returned_attrs = decl_attributes (&type,
9138                                             chainon (returned_attrs, attrs),
9139                                             attr_flags);
9140         }
9141
9142       if (declarator->kind == cdk_id)
9143         break;
9144
9145       inner_declarator = declarator->declarator;
9146
9147       switch (declarator->kind)
9148         {
9149         case cdk_array:
9150           type = create_array_type_for_decl (dname, type,
9151                                              declarator->u.array.bounds);
9152           break;
9153
9154         case cdk_function:
9155           {
9156             tree arg_types;
9157             int funcdecl_p;
9158
9159             /* Declaring a function type.
9160                Make sure we have a valid type for the function to return.  */
9161
9162             if (type_quals != TYPE_UNQUALIFIED)
9163               {
9164                 if (SCALAR_TYPE_P (type) || VOID_TYPE_P (type))
9165                   warning (OPT_Wignored_qualifiers,
9166                            "type qualifiers ignored on function return type");
9167                 /* We now know that the TYPE_QUALS don't apply to the
9168                    decl, but to its return type.  */
9169                 type_quals = TYPE_UNQUALIFIED;
9170               }
9171             errmsg = targetm.invalid_return_type (type);
9172             if (errmsg)
9173               {
9174                 error (errmsg);
9175                 type = integer_type_node;
9176               }
9177
9178             /* Error about some types functions can't return.  */
9179
9180             if (TREE_CODE (type) == FUNCTION_TYPE)
9181               {
9182                 error ("%qs declared as function returning a function", name);
9183                 return error_mark_node;
9184               }
9185             if (TREE_CODE (type) == ARRAY_TYPE)
9186               {
9187                 error ("%qs declared as function returning an array", name);
9188                 return error_mark_node;
9189               }
9190             /* When decl_context == NORMAL we emit a better error message
9191                later in abstract_virtuals_error.  */
9192             if (decl_context == TYPENAME && ABSTRACT_CLASS_TYPE_P (type))
9193               error ("%qs declared as function returning an abstract "
9194                      "class type", name);
9195
9196             /* Pick up type qualifiers which should be applied to `this'.  */
9197             memfn_quals = declarator->u.function.qualifiers;
9198             /* Pick up virt-specifiers.  */
9199             virt_specifiers = declarator->u.function.virt_specifiers;
9200             /* Pick up the exception specifications.  */
9201             raises = declarator->u.function.exception_specification;
9202             /* If the exception-specification is ill-formed, let's pretend
9203                there wasn't one.  */
9204             if (raises == error_mark_node)
9205               raises = NULL_TREE;
9206
9207             /* Say it's a definition only for the CALL_EXPR
9208                closest to the identifier.  */
9209             funcdecl_p = inner_declarator && inner_declarator->kind == cdk_id;
9210
9211             /* Handle a late-specified return type.  */
9212             if (funcdecl_p)
9213               {
9214                 if (type_uses_auto (type))
9215                   {
9216                     if (!declarator->u.function.late_return_type)
9217                       {
9218                         if (current_class_type
9219                             && LAMBDA_TYPE_P (current_class_type))
9220                           /* OK for C++11 lambdas.  */;
9221                         else if (cxx_dialect < cxx1y)
9222                           pedwarn (input_location, 0, "%qs function uses "
9223                                    "%<auto%> type specifier without trailing "
9224                                    "return type", name);
9225                       }
9226                     else if (!is_auto (type))
9227                       {
9228                         error ("%qs function with trailing return type has"
9229                                " %qT as its type rather than plain %<auto%>",
9230                                name, type);
9231                         return error_mark_node;
9232                       }
9233                   }
9234                 else if (declarator->u.function.late_return_type)
9235                   {
9236                     if (cxx_dialect < cxx0x)
9237                       /* Not using maybe_warn_cpp0x because this should
9238                          always be an error.  */
9239                       error ("trailing return type only available with "
9240                              "-std=c++11 or -std=gnu++11");
9241                     else
9242                       error ("%qs function with trailing return type not "
9243                              "declared with %<auto%> type specifier", name);
9244                     return error_mark_node;
9245                   }
9246               }
9247             type = splice_late_return_type
9248               (type, declarator->u.function.late_return_type);
9249             if (type == error_mark_node)
9250               return error_mark_node;
9251
9252             if (ctype == NULL_TREE
9253                 && decl_context == FIELD
9254                 && funcdecl_p
9255                 && (friendp == 0 || dname == current_class_name))
9256               ctype = current_class_type;
9257
9258             if (ctype && (sfk == sfk_constructor
9259                           || sfk == sfk_destructor))
9260               {
9261                 /* We are within a class's scope. If our declarator name
9262                    is the same as the class name, and we are defining
9263                    a function, then it is a constructor/destructor, and
9264                    therefore returns a void type.  */
9265
9266                 /* ISO C++ 12.4/2.  A destructor may not be declared
9267                    const or volatile.  A destructor may not be
9268                    static.
9269
9270                    ISO C++ 12.1.  A constructor may not be declared
9271                    const or volatile.  A constructor may not be
9272                    virtual.  A constructor may not be static.  */
9273                 if (staticp == 2)
9274                   error ((flags == DTOR_FLAG)
9275                          ? G_("destructor cannot be static member function")
9276                          : G_("constructor cannot be static member function"));
9277                 if (memfn_quals)
9278                   {
9279                     error ((flags == DTOR_FLAG)
9280                            ? G_("destructors may not be cv-qualified")
9281                            : G_("constructors may not be cv-qualified"));
9282                     memfn_quals = TYPE_UNQUALIFIED;
9283                   }
9284
9285                 if (decl_context == FIELD
9286                     && !member_function_or_else (ctype,
9287                                                  current_class_type,
9288                                                  flags))
9289                   return error_mark_node;
9290
9291                 if (flags != DTOR_FLAG)
9292                   {
9293                     /* It's a constructor.  */
9294                     if (explicitp == 1)
9295                       explicitp = 2;
9296                     if (virtualp)
9297                       {
9298                         permerror (input_location, "constructors cannot be declared virtual");
9299                         virtualp = 0;
9300                       }
9301                     if (decl_context == FIELD
9302                         && sfk != sfk_constructor)
9303                       return error_mark_node;
9304                   }
9305                 if (decl_context == FIELD)
9306                   staticp = 0;
9307               }
9308             else if (friendp)
9309               {
9310                 if (initialized)
9311                   error ("can%'t initialize friend function %qs", name);
9312                 if (virtualp)
9313                   {
9314                     /* Cannot be both friend and virtual.  */
9315                     error ("virtual functions cannot be friends");
9316                     friendp = 0;
9317                   }
9318                 if (decl_context == NORMAL)
9319                   error ("friend declaration not in class definition");
9320                 if (current_function_decl && funcdef_flag)
9321                   error ("can%'t define friend function %qs in a local "
9322                          "class definition",
9323                          name);
9324               }
9325             else if (ctype && sfk == sfk_conversion)
9326               {
9327                 if (explicitp == 1)
9328                   {
9329                     maybe_warn_cpp0x (CPP0X_EXPLICIT_CONVERSION);
9330                     explicitp = 2;
9331                   }
9332               }
9333
9334             arg_types = grokparms (declarator->u.function.parameters,
9335                                    &parms);
9336
9337             if (inner_declarator
9338                 && inner_declarator->kind == cdk_id
9339                 && inner_declarator->u.id.sfk == sfk_destructor
9340                 && arg_types != void_list_node)
9341               {
9342                 error ("destructors may not have parameters");
9343                 arg_types = void_list_node;
9344                 parms = NULL_TREE;
9345               }
9346
9347             type = build_function_type (type, arg_types);
9348           }
9349           break;
9350
9351         case cdk_pointer:
9352         case cdk_reference:
9353         case cdk_ptrmem:
9354           /* Filter out pointers-to-references and references-to-references.
9355              We can get these if a TYPE_DECL is used.  */
9356
9357           if (TREE_CODE (type) == REFERENCE_TYPE)
9358             {
9359               if (declarator->kind != cdk_reference)
9360                 {
9361                   error ("cannot declare pointer to %q#T", type);
9362                   type = TREE_TYPE (type);
9363                 }
9364
9365               /* In C++0x, we allow reference to reference declarations
9366                  that occur indirectly through typedefs [7.1.3/8 dcl.typedef]
9367                  and template type arguments [14.3.1/4 temp.arg.type]. The
9368                  check for direct reference to reference declarations, which
9369                  are still forbidden, occurs below. Reasoning behind the change
9370                  can be found in DR106, DR540, and the rvalue reference
9371                  proposals. */
9372               else if (cxx_dialect == cxx98)
9373                 {
9374                   error ("cannot declare reference to %q#T", type);
9375                   type = TREE_TYPE (type);
9376                 }
9377             }
9378           else if (VOID_TYPE_P (type))
9379             {
9380               if (declarator->kind == cdk_reference)
9381                 error ("cannot declare reference to %q#T", type);
9382               else if (declarator->kind == cdk_ptrmem)
9383                 error ("cannot declare pointer to %q#T member", type);
9384             }
9385
9386           /* We now know that the TYPE_QUALS don't apply to the decl,
9387              but to the target of the pointer.  */
9388           type_quals = TYPE_UNQUALIFIED;
9389
9390           if (declarator->kind == cdk_ptrmem
9391               && (TREE_CODE (type) == FUNCTION_TYPE
9392                   || (memfn_quals && TREE_CODE (type) == METHOD_TYPE)))
9393             {
9394               memfn_quals |= type_memfn_quals (type);
9395               type = build_memfn_type (type,
9396                                        declarator->u.pointer.class_type,
9397                                        memfn_quals);
9398               if (type == error_mark_node)
9399                 return error_mark_node;
9400               memfn_quals = TYPE_UNQUALIFIED;
9401             }
9402
9403           if (TREE_CODE (type) == FUNCTION_TYPE
9404               && type_memfn_quals (type) != TYPE_UNQUALIFIED)
9405             error (declarator->kind == cdk_reference
9406                    ? G_("cannot declare reference to qualified function type %qT")
9407                    : G_("cannot declare pointer to qualified function type %qT"),
9408                    type);
9409
9410           /* When the pointed-to type involves components of variable size,
9411              care must be taken to ensure that the size evaluation code is
9412              emitted early enough to dominate all the possible later uses
9413              and late enough for the variables on which it depends to have
9414              been assigned.
9415
9416              This is expected to happen automatically when the pointed-to
9417              type has a name/declaration of it's own, but special attention
9418              is required if the type is anonymous.
9419
9420              We handle the NORMAL and FIELD contexts here by inserting a
9421              dummy statement that just evaluates the size at a safe point
9422              and ensures it is not deferred until e.g. within a deeper
9423              conditional context (c++/43555).
9424
9425              We expect nothing to be needed here for PARM or TYPENAME.
9426              Evaluating the size at this point for TYPENAME would
9427              actually be incorrect, as we might be in the middle of an
9428              expression with side effects on the pointed-to type size
9429              "arguments" prior to the pointer declaration point and the
9430              size evaluation could end up prior to the side effects.  */
9431
9432           if (!TYPE_NAME (type)
9433               && (decl_context == NORMAL || decl_context == FIELD)
9434               && at_function_scope_p ()
9435               && variably_modified_type_p (type, NULL_TREE))
9436             {
9437               /* First break out any side-effects.  */
9438               stabilize_vla_size (TYPE_SIZE (type));
9439               /* And then force evaluation of the SAVE_EXPR.  */
9440               finish_expr_stmt (TYPE_SIZE (type));
9441             }
9442
9443           if (declarator->kind == cdk_reference)
9444             {
9445               /* In C++0x, the type we are creating a reference to might be
9446                  a typedef which is itself a reference type. In that case,
9447                  we follow the reference collapsing rules in
9448                  [7.1.3/8 dcl.typedef] to create the final reference type:
9449
9450                  "If a typedef TD names a type that is a reference to a type
9451                  T, an attempt to create the type 'lvalue reference to cv TD'
9452                  creates the type 'lvalue reference to T,' while an attempt
9453                  to create the type "rvalue reference to cv TD' creates the
9454                  type TD."
9455               */
9456               if (VOID_TYPE_P (type))
9457                 /* We already gave an error.  */;
9458               else if (TREE_CODE (type) == REFERENCE_TYPE)
9459                 {
9460                   if (declarator->u.reference.rvalue_ref)
9461                     /* Leave type alone.  */;
9462                   else
9463                     type = cp_build_reference_type (TREE_TYPE (type), false);
9464                 }
9465               else
9466                 type = cp_build_reference_type
9467                   (type, declarator->u.reference.rvalue_ref);
9468
9469               /* In C++0x, we need this check for direct reference to
9470                  reference declarations, which are forbidden by
9471                  [8.3.2/5 dcl.ref]. Reference to reference declarations
9472                  are only allowed indirectly through typedefs and template
9473                  type arguments. Example:
9474
9475                    void foo(int & &);      // invalid ref-to-ref decl
9476
9477                    typedef int & int_ref;
9478                    void foo(int_ref &);    // valid ref-to-ref decl
9479               */
9480               if (inner_declarator && inner_declarator->kind == cdk_reference)
9481                 error ("cannot declare reference to %q#T, which is not "
9482                        "a typedef or a template type argument", type);
9483             }
9484           else if (TREE_CODE (type) == METHOD_TYPE)
9485             type = build_ptrmemfunc_type (build_pointer_type (type));
9486           else if (declarator->kind == cdk_ptrmem)
9487             {
9488               gcc_assert (TREE_CODE (declarator->u.pointer.class_type)
9489                           != NAMESPACE_DECL);
9490               if (declarator->u.pointer.class_type == error_mark_node)
9491                 /* We will already have complained.  */
9492                 type = error_mark_node;
9493               else
9494                 type = build_ptrmem_type (declarator->u.pointer.class_type,
9495                                           type);
9496             }
9497           else
9498             type = build_pointer_type (type);
9499
9500           /* Process a list of type modifier keywords (such as
9501              const or volatile) that were given inside the `*' or `&'.  */
9502
9503           if (declarator->u.pointer.qualifiers)
9504             {
9505               type
9506                 = cp_build_qualified_type (type,
9507                                            declarator->u.pointer.qualifiers);
9508               type_quals = cp_type_quals (type);
9509             }
9510           ctype = NULL_TREE;
9511           break;
9512
9513         case cdk_error:
9514           break;
9515
9516         default:
9517           gcc_unreachable ();
9518         }
9519     }
9520
9521   /* We need to stabilize side-effects in VLA sizes for regular array
9522      declarations too, not just pointers to arrays.  */
9523   if (type != error_mark_node && !TYPE_NAME (type)
9524       && (decl_context == NORMAL || decl_context == FIELD)
9525       && at_function_scope_p ()
9526       && variably_modified_type_p (type, NULL_TREE))
9527     stabilize_vla_size (TYPE_SIZE (type));
9528
9529   /* A `constexpr' specifier used in an object declaration declares
9530      the object as `const'.  */
9531   if (constexpr_p && innermost_code != cdk_function)
9532     {
9533       if (type_quals & TYPE_QUAL_VOLATILE)
9534         error ("both %<volatile%> and %<constexpr%> cannot be used here");
9535       if (TREE_CODE (type) != REFERENCE_TYPE)
9536         {
9537           type_quals |= TYPE_QUAL_CONST;
9538           type = cp_build_qualified_type (type, type_quals);
9539         }
9540     }
9541
9542   if (unqualified_id && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR
9543       && TREE_CODE (type) != FUNCTION_TYPE
9544       && TREE_CODE (type) != METHOD_TYPE)
9545     {
9546       error ("template-id %qD used as a declarator",
9547              unqualified_id);
9548       unqualified_id = dname;
9549     }
9550
9551   /* If TYPE is a FUNCTION_TYPE, but the function name was explicitly
9552      qualified with a class-name, turn it into a METHOD_TYPE, unless
9553      we know that the function is static.  We take advantage of this
9554      opportunity to do other processing that pertains to entities
9555      explicitly declared to be class members.  Note that if DECLARATOR
9556      is non-NULL, we know it is a cdk_id declarator; otherwise, we
9557      would not have exited the loop above.  */
9558   if (declarator
9559       && declarator->u.id.qualifying_scope
9560       && MAYBE_CLASS_TYPE_P (declarator->u.id.qualifying_scope))
9561     {
9562       ctype = declarator->u.id.qualifying_scope;
9563       ctype = TYPE_MAIN_VARIANT (ctype);
9564       template_count = num_template_headers_for_class (ctype);
9565
9566       if (ctype == current_class_type)
9567         {
9568           if (friendp)
9569             {
9570               permerror (input_location, "member functions are implicitly friends of their class");
9571               friendp = 0;
9572             }
9573           else
9574             permerror (declarator->id_loc, 
9575                           "extra qualification %<%T::%> on member %qs",
9576                           ctype, name);
9577         }
9578       else if (/* If the qualifying type is already complete, then we
9579                   can skip the following checks.  */
9580                !COMPLETE_TYPE_P (ctype)
9581                && (/* If the function is being defined, then
9582                       qualifying type must certainly be complete.  */
9583                    funcdef_flag
9584                    /* A friend declaration of "T::f" is OK, even if
9585                       "T" is a template parameter.  But, if this
9586                       function is not a friend, the qualifying type
9587                       must be a class.  */
9588                    || (!friendp && !CLASS_TYPE_P (ctype))
9589                    /* For a declaration, the type need not be
9590                       complete, if either it is dependent (since there
9591                       is no meaningful definition of complete in that
9592                       case) or the qualifying class is currently being
9593                       defined.  */
9594                    || !(dependent_type_p (ctype)
9595                         || currently_open_class (ctype)))
9596                /* Check that the qualifying type is complete.  */
9597                && !complete_type_or_else (ctype, NULL_TREE))
9598         return error_mark_node;
9599       else if (TREE_CODE (type) == FUNCTION_TYPE)
9600         {
9601           if (current_class_type
9602               && (!friendp || funcdef_flag))
9603             {
9604               error (funcdef_flag
9605                      ? G_("cannot define member function %<%T::%s%> "
9606                           "within %<%T%>")
9607                      : G_("cannot declare member function %<%T::%s%> "
9608                           "within %<%T%>"),
9609                      ctype, name, current_class_type);
9610               return error_mark_node;
9611             }
9612         }
9613       else if (decl_spec_seq_has_spec_p (declspecs, ds_typedef)
9614                && current_class_type)
9615         {
9616           error ("cannot declare member %<%T::%s%> within %qT",
9617                  ctype, name, current_class_type);
9618           return error_mark_node;
9619         }
9620     }
9621
9622   if (ctype == NULL_TREE && decl_context == FIELD && friendp == 0)
9623     ctype = current_class_type;
9624
9625   /* Now TYPE has the actual type.  */
9626
9627   if (returned_attrs)
9628     {
9629       if (attrlist)
9630         *attrlist = chainon (returned_attrs, *attrlist);
9631       else
9632         attrlist = &returned_attrs;
9633     }
9634
9635   /* Handle parameter packs. */
9636   if (parameter_pack_p)
9637     {
9638       if (decl_context == PARM)
9639         /* Turn the type into a pack expansion.*/
9640         type = make_pack_expansion (type);
9641       else
9642         error ("non-parameter %qs cannot be a parameter pack", name);
9643     }
9644
9645   /* Did array size calculations overflow or does the array cover more
9646      than half of the address-space?  */
9647   if (TREE_CODE (type) == ARRAY_TYPE
9648       && COMPLETE_TYPE_P (type)
9649       && TREE_CODE (TYPE_SIZE_UNIT (type)) == INTEGER_CST
9650       && ! valid_constant_size_p (TYPE_SIZE_UNIT (type)))
9651     {
9652       error ("size of array %qs is too large", name);
9653       /* If we proceed with the array type as it is, we'll eventually
9654          crash in tree_low_cst().  */
9655       type = error_mark_node;
9656     }
9657
9658   if ((decl_context == FIELD || decl_context == PARM)
9659       && !processing_template_decl
9660       && variably_modified_type_p (type, NULL_TREE))
9661     {
9662       if (decl_context == FIELD)
9663         error ("data member may not have variably modified type %qT", type);
9664       else
9665         error ("parameter may not have variably modified type %qT", type);
9666       type = error_mark_node;
9667     }
9668
9669   if (explicitp == 1 || (explicitp && friendp))
9670     {
9671       /* [dcl.fct.spec] The explicit specifier shall only be used in
9672          declarations of constructors within a class definition.  */
9673       error ("only declarations of constructors can be %<explicit%>");
9674       explicitp = 0;
9675     }
9676
9677   if (storage_class == sc_mutable)
9678     {
9679       if (decl_context != FIELD || friendp)
9680         {
9681           error ("non-member %qs cannot be declared %<mutable%>", name);
9682           storage_class = sc_none;
9683         }
9684       else if (decl_context == TYPENAME
9685                || decl_spec_seq_has_spec_p (declspecs, ds_typedef))
9686         {
9687           error ("non-object member %qs cannot be declared %<mutable%>", name);
9688           storage_class = sc_none;
9689         }
9690       else if (TREE_CODE (type) == FUNCTION_TYPE
9691                || TREE_CODE (type) == METHOD_TYPE)
9692         {
9693           error ("function %qs cannot be declared %<mutable%>", name);
9694           storage_class = sc_none;
9695         }
9696       else if (staticp)
9697         {
9698           error ("static %qs cannot be declared %<mutable%>", name);
9699           storage_class = sc_none;
9700         }
9701       else if (type_quals & TYPE_QUAL_CONST)
9702         {
9703           error ("const %qs cannot be declared %<mutable%>", name);
9704           storage_class = sc_none;
9705         }
9706       else if (TREE_CODE (type) == REFERENCE_TYPE)
9707         {
9708           permerror (input_location, "reference %qs cannot be declared "
9709                      "%<mutable%>", name);
9710           storage_class = sc_none;
9711         }
9712     }
9713
9714   /* If this is declaring a typedef name, return a TYPE_DECL.  */
9715   if (decl_spec_seq_has_spec_p (declspecs, ds_typedef) && decl_context != TYPENAME)
9716     {
9717       tree decl;
9718
9719       /* Note that the grammar rejects storage classes
9720          in typenames, fields or parameters.  */
9721       if (current_lang_name == lang_name_java)
9722         TYPE_FOR_JAVA (type) = 1;
9723
9724       /* This declaration:
9725
9726            typedef void f(int) const;
9727
9728          declares a function type which is not a member of any
9729          particular class, but which is cv-qualified; for
9730          example "f S::*" declares a pointer to a const-qualified
9731          member function of S.  We record the cv-qualification in the
9732          function type.  */
9733       if (memfn_quals && TREE_CODE (type) == FUNCTION_TYPE)
9734         {
9735           type = apply_memfn_quals (type, memfn_quals);
9736           
9737           /* We have now dealt with these qualifiers.  */
9738           memfn_quals = TYPE_UNQUALIFIED;
9739         }
9740
9741       if (type_uses_auto (type))
9742         {
9743           error ("typedef declared %<auto%>");
9744           type = error_mark_node;
9745         }
9746
9747       if (decl_context == FIELD)
9748         decl = build_lang_decl (TYPE_DECL, unqualified_id, type);
9749       else
9750         decl = build_decl (input_location, TYPE_DECL, unqualified_id, type);
9751       if (id_declarator && declarator->u.id.qualifying_scope) {
9752         error_at (DECL_SOURCE_LOCATION (decl), 
9753                   "typedef name may not be a nested-name-specifier");
9754         TREE_TYPE (decl) = error_mark_node;
9755       }
9756
9757       if (decl_context != FIELD)
9758         {
9759           if (!current_function_decl)
9760             DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
9761           else if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (current_function_decl)
9762                    || (DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P
9763                        (current_function_decl)))
9764             /* The TYPE_DECL is "abstract" because there will be
9765                clones of this constructor/destructor, and there will
9766                be copies of this TYPE_DECL generated in those
9767                clones.  */
9768             DECL_ABSTRACT (decl) = 1;
9769         }
9770       else if (current_class_type
9771                && constructor_name_p (unqualified_id, current_class_type))
9772         permerror (input_location, "ISO C++ forbids nested type %qD with same name "
9773                    "as enclosing class",
9774                    unqualified_id);
9775
9776       /* If the user declares "typedef struct {...} foo" then the
9777          struct will have an anonymous name.  Fill that name in now.
9778          Nothing can refer to it, so nothing needs know about the name
9779          change.  */
9780       if (type != error_mark_node
9781           && unqualified_id
9782           && TYPE_NAME (type)
9783           && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL
9784           && TYPE_ANONYMOUS_P (type)
9785           && declspecs->type_definition_p
9786           && cp_type_quals (type) == TYPE_UNQUALIFIED)
9787         {
9788           tree t;
9789
9790           /* Replace the anonymous name with the real name everywhere.  */
9791           for (t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
9792             {
9793               if (ANON_AGGRNAME_P (TYPE_IDENTIFIER (t)))
9794                 /* We do not rename the debug info representing the
9795                    anonymous tagged type because the standard says in
9796                    [dcl.typedef] that the naming applies only for
9797                    linkage purposes.  */
9798                 /*debug_hooks->set_name (t, decl);*/
9799                 TYPE_NAME (t) = decl;
9800             }
9801
9802           if (TYPE_LANG_SPECIFIC (type))
9803             TYPE_WAS_ANONYMOUS (type) = 1;
9804
9805           /* If this is a typedef within a template class, the nested
9806              type is a (non-primary) template.  The name for the
9807              template needs updating as well.  */
9808           if (TYPE_LANG_SPECIFIC (type) && CLASSTYPE_TEMPLATE_INFO (type))
9809             DECL_NAME (CLASSTYPE_TI_TEMPLATE (type))
9810               = TYPE_IDENTIFIER (type);
9811
9812           /* Adjust linkage now that we aren't anonymous anymore.  */
9813           set_linkage_according_to_type (type, TYPE_MAIN_DECL (type));
9814           determine_visibility (TYPE_MAIN_DECL (type));
9815
9816           /* FIXME remangle member functions; member functions of a
9817              type with external linkage have external linkage.  */
9818         }
9819
9820       if (signed_p
9821           || (typedef_decl && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl)))
9822         C_TYPEDEF_EXPLICITLY_SIGNED (decl) = 1;
9823
9824       bad_specifiers (decl, BSP_TYPE, virtualp,
9825                       memfn_quals != TYPE_UNQUALIFIED,
9826                       inlinep, friendp, raises != NULL_TREE);
9827
9828       if (decl_spec_seq_has_spec_p (declspecs, ds_alias))
9829         /* Acknowledge that this was written:
9830              `using analias = atype;'.  */
9831         TYPE_DECL_ALIAS_P (decl) = 1;
9832
9833       return decl;
9834     }
9835
9836   /* Detect the case of an array type of unspecified size
9837      which came, as such, direct from a typedef name.
9838      We must copy the type, so that the array's domain can be
9839      individually set by the object's initializer.  */
9840
9841   if (type && typedef_type
9842       && TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type)
9843       && TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (typedef_type))
9844     type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
9845
9846   /* Detect where we're using a typedef of function type to declare a
9847      function. PARMS will not be set, so we must create it now.  */
9848
9849   if (type == typedef_type && TREE_CODE (type) == FUNCTION_TYPE)
9850     {
9851       tree decls = NULL_TREE;
9852       tree args;
9853
9854       for (args = TYPE_ARG_TYPES (type);
9855            args && args != void_list_node;
9856            args = TREE_CHAIN (args))
9857         {
9858           tree decl = cp_build_parm_decl (NULL_TREE, TREE_VALUE (args));
9859
9860           DECL_CHAIN (decl) = decls;
9861           decls = decl;
9862         }
9863
9864       parms = nreverse (decls);
9865
9866       if (decl_context != TYPENAME)
9867         {
9868           /* A cv-qualifier-seq shall only be part of the function type
9869              for a non-static member function. [8.3.5/4 dcl.fct] */
9870           if (type_memfn_quals (type) != TYPE_UNQUALIFIED
9871               && (current_class_type == NULL_TREE || staticp) )
9872             {
9873               error (staticp
9874                      ? G_("qualified function types cannot be used to "
9875                           "declare static member functions")
9876                      : G_("qualified function types cannot be used to "
9877                           "declare free functions"));
9878               type = TYPE_MAIN_VARIANT (type);
9879             }
9880
9881           /* The qualifiers on the function type become the qualifiers on
9882              the non-static member function. */
9883           memfn_quals |= type_memfn_quals (type);
9884           type_quals = TYPE_UNQUALIFIED;
9885         }
9886     }
9887
9888   /* If this is a type name (such as, in a cast or sizeof),
9889      compute the type and return it now.  */
9890
9891   if (decl_context == TYPENAME)
9892     {
9893       /* Note that the grammar rejects storage classes
9894          in typenames, fields or parameters.  */
9895       if (type_quals != TYPE_UNQUALIFIED)
9896         type_quals = TYPE_UNQUALIFIED;
9897
9898       /* Special case: "friend class foo" looks like a TYPENAME context.  */
9899       if (friendp)
9900         {
9901           if (type_quals != TYPE_UNQUALIFIED)
9902             {
9903               error ("type qualifiers specified for friend class declaration");
9904               type_quals = TYPE_UNQUALIFIED;
9905             }
9906           if (inlinep)
9907             {
9908               error ("%<inline%> specified for friend class declaration");
9909               inlinep = 0;
9910             }
9911
9912           if (!current_aggr)
9913             {
9914               /* Don't allow friend declaration without a class-key.  */
9915               if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
9916                 permerror (input_location, "template parameters cannot be friends");
9917               else if (TREE_CODE (type) == TYPENAME_TYPE)
9918                 permerror (input_location, "friend declaration requires class-key, "
9919                            "i.e. %<friend class %T::%D%>",
9920                            TYPE_CONTEXT (type), TYPENAME_TYPE_FULLNAME (type));
9921               else
9922                 permerror (input_location, "friend declaration requires class-key, "
9923                            "i.e. %<friend %#T%>",
9924                            type);
9925             }
9926
9927           /* Only try to do this stuff if we didn't already give up.  */
9928           if (type != integer_type_node)
9929             {
9930               /* A friendly class?  */
9931               if (current_class_type)
9932                 make_friend_class (current_class_type, TYPE_MAIN_VARIANT (type),
9933                                    /*complain=*/true);
9934               else
9935                 error ("trying to make class %qT a friend of global scope",
9936                        type);
9937
9938               type = void_type_node;
9939             }
9940         }
9941       else if (memfn_quals)
9942         {
9943           if (ctype == NULL_TREE
9944               && TREE_CODE (type) == METHOD_TYPE)
9945             ctype = TYPE_METHOD_BASETYPE (type);
9946
9947           if (ctype)
9948             type = build_memfn_type (type, ctype, memfn_quals);
9949           /* Core issue #547: need to allow this in template type args.  */
9950           else if (template_type_arg && TREE_CODE (type) == FUNCTION_TYPE)
9951             type = apply_memfn_quals (type, memfn_quals);
9952           else
9953             error ("invalid qualifiers on non-member function type");
9954         }
9955
9956       return type;
9957     }
9958   else if (unqualified_id == NULL_TREE && decl_context != PARM
9959            && decl_context != CATCHPARM
9960            && TREE_CODE (type) != UNION_TYPE
9961            && ! bitfield)
9962     {
9963       error ("abstract declarator %qT used as declaration", type);
9964       return error_mark_node;
9965     }
9966
9967   /* Only functions may be declared using an operator-function-id.  */
9968   if (unqualified_id
9969       && IDENTIFIER_OPNAME_P (unqualified_id)
9970       && TREE_CODE (type) != FUNCTION_TYPE
9971       && TREE_CODE (type) != METHOD_TYPE)
9972     {
9973       error ("declaration of %qD as non-function", unqualified_id);
9974       return error_mark_node;
9975     }
9976
9977   /* We don't check parameter types here because we can emit a better
9978      error message later.  */
9979   if (decl_context != PARM)
9980     {
9981       type = check_var_type (unqualified_id, type);
9982       if (type == error_mark_node)
9983         return error_mark_node;
9984     }
9985
9986   /* Now create the decl, which may be a VAR_DECL, a PARM_DECL
9987      or a FUNCTION_DECL, depending on DECL_CONTEXT and TYPE.  */
9988
9989   if (decl_context == PARM || decl_context == CATCHPARM)
9990     {
9991       if (ctype || in_namespace)
9992         error ("cannot use %<::%> in parameter declaration");
9993
9994       if (type_uses_auto (type))
9995         {
9996           error ("parameter declared %<auto%>");
9997           type = error_mark_node;
9998         }
9999
10000       /* A parameter declared as an array of T is really a pointer to T.
10001          One declared as a function is really a pointer to a function.
10002          One declared as a member is really a pointer to member.  */
10003
10004       if (TREE_CODE (type) == ARRAY_TYPE)
10005         {
10006           /* Transfer const-ness of array into that of type pointed to.  */
10007           type = build_pointer_type (TREE_TYPE (type));
10008           type_quals = TYPE_UNQUALIFIED;
10009         }
10010       else if (TREE_CODE (type) == FUNCTION_TYPE)
10011         type = build_pointer_type (type);
10012     }
10013
10014   if (ctype && TREE_CODE (type) == FUNCTION_TYPE && staticp < 2
10015       && !NEW_DELETE_OPNAME_P (unqualified_id))
10016     {
10017       cp_cv_quals real_quals = memfn_quals;
10018       if (constexpr_p && sfk != sfk_constructor && sfk != sfk_destructor)
10019         real_quals |= TYPE_QUAL_CONST;
10020       type = build_memfn_type (type, ctype, real_quals);
10021     }
10022
10023   {
10024     tree decl;
10025
10026     if (decl_context == PARM)
10027       {
10028         decl = cp_build_parm_decl (unqualified_id, type);
10029
10030         bad_specifiers (decl, BSP_PARM, virtualp,
10031                         memfn_quals != TYPE_UNQUALIFIED,
10032                         inlinep, friendp, raises != NULL_TREE);
10033       }
10034     else if (decl_context == FIELD)
10035       {
10036         if (!staticp && TREE_CODE (type) != METHOD_TYPE
10037             && type_uses_auto (type))
10038           {
10039             error ("non-static data member declared %<auto%>");
10040             type = error_mark_node;
10041           }
10042
10043         /* The C99 flexible array extension.  */
10044         if (!staticp && TREE_CODE (type) == ARRAY_TYPE
10045             && TYPE_DOMAIN (type) == NULL_TREE)
10046           {
10047             tree itype = compute_array_index_type (dname, integer_zero_node,
10048                                                    tf_warning_or_error);
10049             type = build_cplus_array_type (TREE_TYPE (type), itype);
10050           }
10051
10052         if (type == error_mark_node)
10053           {
10054             /* Happens when declaring arrays of sizes which
10055                are error_mark_node, for example.  */
10056             decl = NULL_TREE;
10057           }
10058         else if (in_namespace && !friendp)
10059           {
10060             /* Something like struct S { int N::j; };  */
10061             error ("invalid use of %<::%>");
10062             return error_mark_node;
10063           }
10064         else if (TREE_CODE (type) == FUNCTION_TYPE
10065                  || TREE_CODE (type) == METHOD_TYPE)
10066           {
10067             int publicp = 0;
10068             tree function_context;
10069
10070             if (friendp == 0)
10071               {
10072                 /* This should never happen in pure C++ (the check
10073                    could be an assert).  It could happen in
10074                    Objective-C++ if someone writes invalid code that
10075                    uses a function declaration for an instance
10076                    variable or property (instance variables and
10077                    properties are parsed as FIELD_DECLs, but they are
10078                    part of an Objective-C class, not a C++ class).
10079                    That code is invalid and is caught by this
10080                    check.  */
10081                 if (!ctype)
10082                   {
10083                     error ("declaration of function %qD in invalid context",
10084                            unqualified_id);
10085                     return error_mark_node;
10086                   }
10087
10088                 /* ``A union may [ ... ] not [ have ] virtual functions.''
10089                    ARM 9.5 */
10090                 if (virtualp && TREE_CODE (ctype) == UNION_TYPE)
10091                   {
10092                     error ("function %qD declared virtual inside a union",
10093                            unqualified_id);
10094                     return error_mark_node;
10095                   }
10096
10097                 if (NEW_DELETE_OPNAME_P (unqualified_id))
10098                   {
10099                     if (virtualp)
10100                       {
10101                         error ("%qD cannot be declared virtual, since it "
10102                                "is always static",
10103                                unqualified_id);
10104                         virtualp = 0;
10105                       }
10106                   }
10107               }
10108
10109             /* Check that the name used for a destructor makes sense.  */
10110             if (sfk == sfk_destructor)
10111               {
10112                 tree uqname = id_declarator->u.id.unqualified_name;
10113
10114                 if (!ctype)
10115                   {
10116                     gcc_assert (friendp);
10117                     error ("expected qualified name in friend declaration "
10118                            "for destructor %qD", uqname);
10119                     return error_mark_node;
10120                   }
10121
10122                 if (!check_dtor_name (ctype, TREE_OPERAND (uqname, 0)))
10123                   {
10124                     error ("declaration of %qD as member of %qT",
10125                            uqname, ctype);
10126                     return error_mark_node;
10127                   }
10128                 if (constexpr_p)
10129                   {
10130                     error ("a destructor cannot be %<constexpr%>");
10131                     return error_mark_node;
10132                   }
10133               }
10134             else if (sfk == sfk_constructor && friendp && !ctype)
10135               {
10136                 error ("expected qualified name in friend declaration "
10137                        "for constructor %qD",
10138                        id_declarator->u.id.unqualified_name);
10139                 return error_mark_node;
10140               }
10141
10142             /* Tell grokfndecl if it needs to set TREE_PUBLIC on the node.  */
10143             function_context = (ctype != NULL_TREE) ?
10144               decl_function_context (TYPE_MAIN_DECL (ctype)) : NULL_TREE;
10145             publicp = (! friendp || ! staticp)
10146               && function_context == NULL_TREE;
10147             decl = grokfndecl (ctype, type,
10148                                TREE_CODE (unqualified_id) != TEMPLATE_ID_EXPR
10149                                ? unqualified_id : dname,
10150                                parms,
10151                                unqualified_id,
10152                                virtualp, flags, memfn_quals, raises,
10153                                friendp ? -1 : 0, friendp, publicp,
10154                                inlinep | (2 * constexpr_p),
10155                                sfk,
10156                                funcdef_flag, template_count, in_namespace,
10157                                attrlist, declarator->id_loc);
10158             decl = set_virt_specifiers (decl, virt_specifiers);
10159             if (decl == NULL_TREE)
10160               return error_mark_node;
10161 #if 0
10162             /* This clobbers the attrs stored in `decl' from `attrlist'.  */
10163             /* The decl and setting of decl_attr is also turned off.  */
10164             decl = build_decl_attribute_variant (decl, decl_attr);
10165 #endif
10166
10167             /* [class.conv.ctor]
10168
10169                A constructor declared without the function-specifier
10170                explicit that can be called with a single parameter
10171                specifies a conversion from the type of its first
10172                parameter to the type of its class.  Such a constructor
10173                is called a converting constructor.  */
10174             if (explicitp == 2)
10175               DECL_NONCONVERTING_P (decl) = 1;
10176           }
10177         else if (!staticp && !dependent_type_p (type)
10178                  && !COMPLETE_TYPE_P (complete_type (type))
10179                  && (TREE_CODE (type) != ARRAY_TYPE || initialized == 0))
10180           {
10181             if (unqualified_id)
10182               error ("field %qD has incomplete type", unqualified_id);
10183             else
10184               error ("name %qT has incomplete type", type);
10185
10186             /* If we're instantiating a template, tell them which
10187                instantiation made the field's type be incomplete.  */
10188             if (current_class_type
10189                 && TYPE_NAME (current_class_type)
10190                 && IDENTIFIER_TEMPLATE (current_class_name)
10191                 && declspecs->type
10192                 && declspecs->type == type)
10193               error ("  in instantiation of template %qT",
10194                      current_class_type);
10195
10196             return error_mark_node;
10197           }
10198         else
10199           {
10200             if (friendp)
10201               {
10202                 error ("%qE is neither function nor member function; "
10203                        "cannot be declared friend", unqualified_id);
10204                 friendp = 0;
10205               }
10206             decl = NULL_TREE;
10207           }
10208
10209         if (friendp)
10210           {
10211             /* Friends are treated specially.  */
10212             if (ctype == current_class_type)
10213               ;  /* We already issued a permerror.  */
10214             else if (decl && DECL_NAME (decl))
10215               {
10216                 if (template_class_depth (current_class_type) == 0)
10217                   {
10218                     decl = check_explicit_specialization
10219                       (unqualified_id, decl, template_count,
10220                        2 * funcdef_flag + 4);
10221                     if (decl == error_mark_node)
10222                       return error_mark_node;
10223                   }
10224
10225                 decl = do_friend (ctype, unqualified_id, decl,
10226                                   *attrlist, flags,
10227                                   funcdef_flag);
10228                 return decl;
10229               }
10230             else
10231               return error_mark_node;
10232           }
10233
10234         /* Structure field.  It may not be a function, except for C++.  */
10235
10236         if (decl == NULL_TREE)
10237           {
10238             if (staticp)
10239               {
10240                 /* C++ allows static class members.  All other work
10241                    for this is done by grokfield.  */
10242                 decl = build_lang_decl_loc (declarator->id_loc,
10243                                             VAR_DECL, unqualified_id, type);
10244                 set_linkage_for_static_data_member (decl);
10245                 /* Even if there is an in-class initialization, DECL
10246                    is considered undefined until an out-of-class
10247                    definition is provided.  */
10248                 DECL_EXTERNAL (decl) = 1;
10249
10250                 if (thread_p)
10251                   DECL_TLS_MODEL (decl) = decl_default_tls_model (decl);
10252
10253                 if (constexpr_p && !initialized)
10254                   {
10255                     error ("constexpr static data member %qD must have an "
10256                            "initializer", decl);
10257                     constexpr_p = false;
10258                   }
10259               }
10260             else
10261               {
10262                 if (constexpr_p)
10263                   {
10264                     error ("non-static data member %qE declared %<constexpr%>",
10265                            unqualified_id);
10266                     constexpr_p = false;
10267                   }
10268                 decl = build_decl (input_location,
10269                                    FIELD_DECL, unqualified_id, type);
10270                 DECL_NONADDRESSABLE_P (decl) = bitfield;
10271                 if (bitfield && !unqualified_id)
10272                   TREE_NO_WARNING (decl) = 1;
10273
10274                 if (storage_class == sc_mutable)
10275                   {
10276                     DECL_MUTABLE_P (decl) = 1;
10277                     storage_class = sc_none;
10278                   }
10279
10280                 if (initialized)
10281                   {
10282                     /* An attempt is being made to initialize a non-static
10283                        member.  This is new in C++11.  */
10284                     maybe_warn_cpp0x (CPP0X_NSDMI);
10285
10286                     /* If this has been parsed with static storage class, but
10287                        errors forced staticp to be cleared, ensure NSDMI is
10288                        not present.  */
10289                     if (declspecs->storage_class == sc_static)
10290                       DECL_INITIAL (decl) = error_mark_node;
10291                   }
10292               }
10293
10294             bad_specifiers (decl, BSP_FIELD, virtualp,
10295                             memfn_quals != TYPE_UNQUALIFIED,
10296                             inlinep, friendp, raises != NULL_TREE);
10297           }
10298       }
10299     else if (TREE_CODE (type) == FUNCTION_TYPE
10300              || TREE_CODE (type) == METHOD_TYPE)
10301       {
10302         tree original_name;
10303         int publicp = 0;
10304
10305         if (!unqualified_id)
10306           return error_mark_node;
10307
10308         if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
10309           original_name = dname;
10310         else
10311           original_name = unqualified_id;
10312
10313         if (storage_class == sc_auto)
10314           error ("storage class %<auto%> invalid for function %qs", name);
10315         else if (storage_class == sc_register)
10316           error ("storage class %<register%> invalid for function %qs", name);
10317         else if (thread_p)
10318           error ("storage class %<__thread%> invalid for function %qs", name);
10319
10320         if (virt_specifiers)
10321           error ("virt-specifiers in %qs not allowed outside a class definition", name);
10322         /* Function declaration not at top level.
10323            Storage classes other than `extern' are not allowed
10324            and `extern' makes no difference.  */
10325         if (! toplevel_bindings_p ()
10326             && (storage_class == sc_static
10327                 || decl_spec_seq_has_spec_p (declspecs, ds_inline))
10328             && pedantic)
10329           {
10330             if (storage_class == sc_static)
10331               pedwarn (input_location, OPT_Wpedantic, 
10332                        "%<static%> specified invalid for function %qs "
10333                        "declared out of global scope", name);
10334             else
10335               pedwarn (input_location, OPT_Wpedantic, 
10336                        "%<inline%> specifier invalid for function %qs "
10337                        "declared out of global scope", name);
10338           }
10339
10340         if (ctype == NULL_TREE)
10341           {
10342             if (virtualp)
10343               {
10344                 error ("virtual non-class function %qs", name);
10345                 virtualp = 0;
10346               }
10347             else if (sfk == sfk_constructor
10348                      || sfk == sfk_destructor)
10349               {
10350                 error (funcdef_flag
10351                        ? G_("%qs defined in a non-class scope")
10352                        : G_("%qs declared in a non-class scope"), name);
10353                 sfk = sfk_none;
10354               }
10355           }
10356
10357         /* Record presence of `static'.  */
10358         publicp = (ctype != NULL_TREE
10359                    || storage_class == sc_extern
10360                    || storage_class != sc_static);
10361
10362         decl = grokfndecl (ctype, type, original_name, parms, unqualified_id,
10363                            virtualp, flags, memfn_quals, raises,
10364                            1, friendp,
10365                            publicp, inlinep | (2 * constexpr_p), sfk,
10366                            funcdef_flag,
10367                            template_count, in_namespace, attrlist,
10368                            declarator->id_loc);
10369         if (decl == NULL_TREE)
10370           return error_mark_node;
10371
10372         if (staticp == 1)
10373           {
10374             int invalid_static = 0;
10375
10376             /* Don't allow a static member function in a class, and forbid
10377                declaring main to be static.  */
10378             if (TREE_CODE (type) == METHOD_TYPE)
10379               {
10380                 permerror (input_location, "cannot declare member function %qD to have "
10381                            "static linkage", decl);
10382                 invalid_static = 1;
10383               }
10384             else if (current_function_decl)
10385               {
10386                 /* FIXME need arm citation */
10387                 error ("cannot declare static function inside another function");
10388                 invalid_static = 1;
10389               }
10390
10391             if (invalid_static)
10392               {
10393                 staticp = 0;
10394                 storage_class = sc_none;
10395               }
10396           }
10397       }
10398     else
10399       {
10400         /* It's a variable.  */
10401
10402         /* An uninitialized decl with `extern' is a reference.  */
10403         decl = grokvardecl (type, unqualified_id,
10404                             declspecs,
10405                             initialized,
10406                             (type_quals & TYPE_QUAL_CONST) != 0,
10407                             ctype ? ctype : in_namespace);
10408         bad_specifiers (decl, BSP_VAR, virtualp,
10409                         memfn_quals != TYPE_UNQUALIFIED,
10410                         inlinep, friendp, raises != NULL_TREE);
10411
10412         if (ctype)
10413           {
10414             DECL_CONTEXT (decl) = ctype;
10415             if (staticp == 1)
10416               {
10417                 permerror (input_location, "%<static%> may not be used when defining "
10418                            "(as opposed to declaring) a static data member");
10419                 staticp = 0;
10420                 storage_class = sc_none;
10421               }
10422             if (storage_class == sc_register && TREE_STATIC (decl))
10423               {
10424                 error ("static member %qD declared %<register%>", decl);
10425                 storage_class = sc_none;
10426               }
10427             if (storage_class == sc_extern && pedantic)
10428               {
10429                 pedwarn (input_location, OPT_Wpedantic, 
10430                          "cannot explicitly declare member %q#D to have "
10431                          "extern linkage", decl);
10432                 storage_class = sc_none;
10433               }
10434           }
10435         else if (constexpr_p && DECL_EXTERNAL (decl))
10436           {
10437             error ("declaration of constexpr variable %qD is not a definition",
10438                    decl);
10439             constexpr_p = false;
10440           }
10441       }
10442
10443     if (storage_class == sc_extern && initialized && !funcdef_flag)
10444       {
10445         if (toplevel_bindings_p ())
10446           {
10447             /* It's common practice (and completely valid) to have a const
10448                be initialized and declared extern.  */
10449             if (!(type_quals & TYPE_QUAL_CONST))
10450               warning (0, "%qs initialized and declared %<extern%>", name);
10451           }
10452         else
10453           {
10454             error ("%qs has both %<extern%> and initializer", name);
10455             return error_mark_node;
10456           }
10457       }
10458
10459     /* Record `register' declaration for warnings on &
10460        and in case doing stupid register allocation.  */
10461
10462     if (storage_class == sc_register)
10463       DECL_REGISTER (decl) = 1;
10464     else if (storage_class == sc_extern)
10465       DECL_THIS_EXTERN (decl) = 1;
10466     else if (storage_class == sc_static)
10467       DECL_THIS_STATIC (decl) = 1;
10468
10469     /* Set constexpr flag on vars (functions got it in grokfndecl).  */
10470     if (constexpr_p && TREE_CODE (decl) == VAR_DECL)
10471       DECL_DECLARED_CONSTEXPR_P (decl) = true;
10472
10473     /* Record constancy and volatility on the DECL itself .  There's
10474        no need to do this when processing a template; we'll do this
10475        for the instantiated declaration based on the type of DECL.  */
10476     if (!processing_template_decl)
10477       cp_apply_type_quals_to_decl (type_quals, decl);
10478
10479     return decl;
10480   }
10481 }
10482 \f
10483 /* Subroutine of start_function.  Ensure that each of the parameter
10484    types (as listed in PARMS) is complete, as is required for a
10485    function definition.  */
10486
10487 static void
10488 require_complete_types_for_parms (tree parms)
10489 {
10490   for (; parms; parms = DECL_CHAIN (parms))
10491     {
10492       if (dependent_type_p (TREE_TYPE (parms)))
10493         continue;
10494       if (!VOID_TYPE_P (TREE_TYPE (parms))
10495           && complete_type_or_else (TREE_TYPE (parms), parms))
10496         {
10497           relayout_decl (parms);
10498           DECL_ARG_TYPE (parms) = type_passed_as (TREE_TYPE (parms));
10499         }
10500       else
10501         /* grokparms or complete_type_or_else will have already issued
10502            an error.  */
10503         TREE_TYPE (parms) = error_mark_node;
10504     }
10505 }
10506
10507 /* Returns nonzero if T is a local variable.  */
10508
10509 int
10510 local_variable_p (const_tree t)
10511 {
10512   if ((TREE_CODE (t) == VAR_DECL
10513        /* A VAR_DECL with a context that is a _TYPE is a static data
10514           member.  */
10515        && !TYPE_P (CP_DECL_CONTEXT (t))
10516        /* Any other non-local variable must be at namespace scope.  */
10517        && !DECL_NAMESPACE_SCOPE_P (t))
10518       || (TREE_CODE (t) == PARM_DECL))
10519     return 1;
10520
10521   return 0;
10522 }
10523
10524 /* Like local_variable_p, but suitable for use as a tree-walking
10525    function.  */
10526
10527 static tree
10528 local_variable_p_walkfn (tree *tp, int *walk_subtrees,
10529                          void *data ATTRIBUTE_UNUSED)
10530 {
10531   /* Check DECL_NAME to avoid including temporaries.  We don't check
10532      DECL_ARTIFICIAL because we do want to complain about 'this'.  */
10533   if (local_variable_p (*tp) && DECL_NAME (*tp))
10534     return *tp;
10535   else if (TYPE_P (*tp))
10536     *walk_subtrees = 0;
10537
10538   return NULL_TREE;
10539 }
10540
10541 /* Check that ARG, which is a default-argument expression for a
10542    parameter DECL, is valid.  Returns ARG, or ERROR_MARK_NODE, if
10543    something goes wrong.  DECL may also be a _TYPE node, rather than a
10544    DECL, if there is no DECL available.  */
10545
10546 tree
10547 check_default_argument (tree decl, tree arg)
10548 {
10549   tree var;
10550   tree decl_type;
10551
10552   if (TREE_CODE (arg) == DEFAULT_ARG)
10553     /* We get a DEFAULT_ARG when looking at an in-class declaration
10554        with a default argument.  Ignore the argument for now; we'll
10555        deal with it after the class is complete.  */
10556     return arg;
10557
10558   if (TYPE_P (decl))
10559     {
10560       decl_type = decl;
10561       decl = NULL_TREE;
10562     }
10563   else
10564     decl_type = TREE_TYPE (decl);
10565
10566   if (arg == error_mark_node
10567       || decl == error_mark_node
10568       || TREE_TYPE (arg) == error_mark_node
10569       || decl_type == error_mark_node)
10570     /* Something already went wrong.  There's no need to check
10571        further.  */
10572     return error_mark_node;
10573
10574   /* [dcl.fct.default]
10575
10576      A default argument expression is implicitly converted to the
10577      parameter type.  */
10578   ++cp_unevaluated_operand;
10579   perform_implicit_conversion_flags (decl_type, arg, tf_warning_or_error,
10580                                      LOOKUP_NORMAL);
10581   --cp_unevaluated_operand;
10582
10583   if (warn_zero_as_null_pointer_constant
10584       && c_inhibit_evaluation_warnings == 0
10585       && TYPE_PTR_OR_PTRMEM_P (decl_type)
10586       && null_ptr_cst_p (arg)
10587       && !NULLPTR_TYPE_P (TREE_TYPE (arg)))
10588     {
10589       warning (OPT_Wzero_as_null_pointer_constant,
10590                "zero as null pointer constant");
10591       return nullptr_node;
10592     }
10593
10594   /* [dcl.fct.default]
10595
10596      Local variables shall not be used in default argument
10597      expressions.
10598
10599      The keyword `this' shall not be used in a default argument of a
10600      member function.  */
10601   var = cp_walk_tree_without_duplicates (&arg, local_variable_p_walkfn, NULL);
10602   if (var)
10603     {
10604       if (DECL_NAME (var) == this_identifier)
10605         permerror (input_location, "default argument %qE uses %qD", arg, var);
10606       else
10607         error ("default argument %qE uses local variable %qD", arg, var);
10608       return error_mark_node;
10609     }
10610
10611   /* All is well.  */
10612   return arg;
10613 }
10614
10615 /* Returns a deprecated type used within TYPE, or NULL_TREE if none.  */
10616
10617 static tree
10618 type_is_deprecated (tree type)
10619 {
10620   enum tree_code code;
10621   if (TREE_DEPRECATED (type))
10622     return type;
10623   if (TYPE_NAME (type)
10624       && TREE_DEPRECATED (TYPE_NAME (type)))
10625     return type;
10626
10627   /* Do warn about using typedefs to a deprecated class.  */
10628   if (TAGGED_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
10629     return type_is_deprecated (TYPE_MAIN_VARIANT (type));
10630
10631   code = TREE_CODE (type);
10632
10633   if (code == POINTER_TYPE || code == REFERENCE_TYPE
10634       || code == OFFSET_TYPE || code == FUNCTION_TYPE
10635       || code == METHOD_TYPE || code == ARRAY_TYPE)
10636     return type_is_deprecated (TREE_TYPE (type));
10637
10638   if (TYPE_PTRMEMFUNC_P (type))
10639     return type_is_deprecated
10640       (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
10641
10642   return NULL_TREE;
10643 }
10644
10645 /* Decode the list of parameter types for a function type.
10646    Given the list of things declared inside the parens,
10647    return a list of types.
10648
10649    If this parameter does not end with an ellipsis, we append
10650    void_list_node.
10651
10652    *PARMS is set to the chain of PARM_DECLs created.  */
10653
10654 static tree
10655 grokparms (tree parmlist, tree *parms)
10656 {
10657   tree result = NULL_TREE;
10658   tree decls = NULL_TREE;
10659   tree parm;
10660   int any_error = 0;
10661
10662   for (parm = parmlist; parm != NULL_TREE; parm = TREE_CHAIN (parm))
10663     {
10664       tree type = NULL_TREE;
10665       tree init = TREE_PURPOSE (parm);
10666       tree decl = TREE_VALUE (parm);
10667       const char *errmsg;
10668
10669       if (parm == void_list_node)
10670         break;
10671
10672       if (! decl || TREE_TYPE (decl) == error_mark_node)
10673         continue;
10674
10675       type = TREE_TYPE (decl);
10676       if (VOID_TYPE_P (type))
10677         {
10678           if (same_type_p (type, void_type_node)
10679               && DECL_SELF_REFERENCE_P (type)
10680               && !DECL_NAME (decl) && !result && TREE_CHAIN (parm) == void_list_node)
10681             /* this is a parmlist of `(void)', which is ok.  */
10682             break;
10683           cxx_incomplete_type_error (decl, type);
10684           /* It's not a good idea to actually create parameters of
10685              type `void'; other parts of the compiler assume that a
10686              void type terminates the parameter list.  */
10687           type = error_mark_node;
10688           TREE_TYPE (decl) = error_mark_node;
10689         }
10690
10691       if (type != error_mark_node
10692           && TYPE_FOR_JAVA (type)
10693           && MAYBE_CLASS_TYPE_P (type))
10694         {
10695           error ("parameter %qD has Java class type", decl);
10696           type = error_mark_node;
10697           TREE_TYPE (decl) = error_mark_node;
10698           init = NULL_TREE;
10699         }
10700
10701       if (type != error_mark_node
10702           && (errmsg = targetm.invalid_parameter_type (type)))
10703         {
10704           error (errmsg);
10705           type = error_mark_node;
10706           TREE_TYPE (decl) = error_mark_node;
10707         }
10708
10709       if (type != error_mark_node)
10710         {
10711           if (deprecated_state != DEPRECATED_SUPPRESS)
10712             {
10713               tree deptype = type_is_deprecated (type);
10714               if (deptype)
10715                 warn_deprecated_use (deptype, NULL_TREE);
10716             }
10717
10718           /* Top-level qualifiers on the parameters are
10719              ignored for function types.  */
10720           type = cp_build_qualified_type (type, 0);
10721           if (TREE_CODE (type) == METHOD_TYPE)
10722             {
10723               error ("parameter %qD invalidly declared method type", decl);
10724               type = build_pointer_type (type);
10725               TREE_TYPE (decl) = type;
10726             }
10727           else if (abstract_virtuals_error (decl, type))
10728             any_error = 1;  /* Seems like a good idea.  */
10729           else if (POINTER_TYPE_P (type))
10730             {
10731               /* [dcl.fct]/6, parameter types cannot contain pointers
10732                  (references) to arrays of unknown bound.  */
10733               tree t = TREE_TYPE (type);
10734               int ptr = TYPE_PTR_P (type);
10735
10736               while (1)
10737                 {
10738                   if (TYPE_PTR_P (t))
10739                     ptr = 1;
10740                   else if (TREE_CODE (t) != ARRAY_TYPE)
10741                     break;
10742                   else if (!TYPE_DOMAIN (t))
10743                     break;
10744                   t = TREE_TYPE (t);
10745                 }
10746               if (TREE_CODE (t) == ARRAY_TYPE)
10747                 error (ptr
10748                        ? G_("parameter %qD includes pointer to array of "
10749                             "unknown bound %qT")
10750                        : G_("parameter %qD includes reference to array of "
10751                             "unknown bound %qT"),
10752                        decl, t);
10753             }
10754
10755           if (any_error)
10756             init = NULL_TREE;
10757           else if (init && !processing_template_decl)
10758             init = check_default_argument (decl, init);
10759         }
10760
10761       DECL_CHAIN (decl) = decls;
10762       decls = decl;
10763       result = tree_cons (init, type, result);
10764     }
10765   decls = nreverse (decls);
10766   result = nreverse (result);
10767   if (parm)
10768     result = chainon (result, void_list_node);
10769   *parms = decls;
10770
10771   return result;
10772 }
10773
10774 \f
10775 /* D is a constructor or overloaded `operator='.
10776
10777    Let T be the class in which D is declared. Then, this function
10778    returns:
10779
10780    -1 if D's is an ill-formed constructor or copy assignment operator
10781       whose first parameter is of type `T'.
10782    0  if D is not a copy constructor or copy assignment
10783       operator.
10784    1  if D is a copy constructor or copy assignment operator whose
10785       first parameter is a reference to non-const qualified T.
10786    2  if D is a copy constructor or copy assignment operator whose
10787       first parameter is a reference to const qualified T.
10788
10789    This function can be used as a predicate. Positive values indicate
10790    a copy constructor and nonzero values indicate a copy assignment
10791    operator.  */
10792
10793 int
10794 copy_fn_p (const_tree d)
10795 {
10796   tree args;
10797   tree arg_type;
10798   int result = 1;
10799
10800   gcc_assert (DECL_FUNCTION_MEMBER_P (d));
10801
10802   if (TREE_CODE (d) == TEMPLATE_DECL
10803       || (DECL_TEMPLATE_INFO (d)
10804           && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
10805     /* Instantiations of template member functions are never copy
10806        functions.  Note that member functions of templated classes are
10807        represented as template functions internally, and we must
10808        accept those as copy functions.  */
10809     return 0;
10810
10811   args = FUNCTION_FIRST_USER_PARMTYPE (d);
10812   if (!args)
10813     return 0;
10814
10815   arg_type = TREE_VALUE (args);
10816   if (arg_type == error_mark_node)
10817     return 0;
10818
10819   if (TYPE_MAIN_VARIANT (arg_type) == DECL_CONTEXT (d))
10820     {
10821       /* Pass by value copy assignment operator.  */
10822       result = -1;
10823     }
10824   else if (TREE_CODE (arg_type) == REFERENCE_TYPE
10825            && !TYPE_REF_IS_RVALUE (arg_type)
10826            && TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)) == DECL_CONTEXT (d))
10827     {
10828       if (CP_TYPE_CONST_P (TREE_TYPE (arg_type)))
10829         result = 2;
10830     }
10831   else
10832     return 0;
10833
10834   args = TREE_CHAIN (args);
10835
10836   if (args && args != void_list_node && !TREE_PURPOSE (args))
10837     /* There are more non-optional args.  */
10838     return 0;
10839
10840   return result;
10841 }
10842
10843 /* D is a constructor or overloaded `operator='.
10844
10845    Let T be the class in which D is declared. Then, this function
10846    returns true when D is a move constructor or move assignment
10847    operator, false otherwise.  */
10848
10849 bool
10850 move_fn_p (const_tree d)
10851 {
10852   tree args;
10853   tree arg_type;
10854   bool result = false;
10855
10856   gcc_assert (DECL_FUNCTION_MEMBER_P (d));
10857
10858   if (cxx_dialect == cxx98)
10859     /* There are no move constructors if we are in C++98 mode.  */
10860     return false;
10861
10862   if (TREE_CODE (d) == TEMPLATE_DECL
10863       || (DECL_TEMPLATE_INFO (d)
10864          && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
10865     /* Instantiations of template member functions are never copy
10866        functions.  Note that member functions of templated classes are
10867        represented as template functions internally, and we must
10868        accept those as copy functions.  */
10869     return 0;
10870
10871   args = FUNCTION_FIRST_USER_PARMTYPE (d);
10872   if (!args)
10873     return 0;
10874
10875   arg_type = TREE_VALUE (args);
10876   if (arg_type == error_mark_node)
10877     return 0;
10878
10879   if (TREE_CODE (arg_type) == REFERENCE_TYPE
10880       && TYPE_REF_IS_RVALUE (arg_type)
10881       && same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)),
10882                       DECL_CONTEXT (d)))
10883     result = true;
10884
10885   args = TREE_CHAIN (args);
10886
10887   if (args && args != void_list_node && !TREE_PURPOSE (args))
10888     /* There are more non-optional args.  */
10889     return false;
10890
10891   return result;
10892 }
10893
10894 /* Remember any special properties of member function DECL.  */
10895
10896 void
10897 grok_special_member_properties (tree decl)
10898 {
10899   tree class_type;
10900
10901   if (!DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
10902     return;
10903
10904   class_type = DECL_CONTEXT (decl);
10905   if (DECL_CONSTRUCTOR_P (decl))
10906     {
10907       int ctor = copy_fn_p (decl);
10908
10909       if (!DECL_ARTIFICIAL (decl))
10910         TYPE_HAS_USER_CONSTRUCTOR (class_type) = 1;
10911
10912       if (ctor > 0)
10913         {
10914           /* [class.copy]
10915
10916              A non-template constructor for class X is a copy
10917              constructor if its first parameter is of type X&, const
10918              X&, volatile X& or const volatile X&, and either there
10919              are no other parameters or else all other parameters have
10920              default arguments.  */
10921           TYPE_HAS_COPY_CTOR (class_type) = 1;
10922           if (user_provided_p (decl))
10923             TYPE_HAS_COMPLEX_COPY_CTOR (class_type) = 1;
10924           if (ctor > 1)
10925             TYPE_HAS_CONST_COPY_CTOR (class_type) = 1;
10926         }
10927       else if (sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (decl)))
10928         {
10929           TYPE_HAS_DEFAULT_CONSTRUCTOR (class_type) = 1;
10930           if (user_provided_p (decl))
10931             TYPE_HAS_COMPLEX_DFLT (class_type) = 1;
10932         }
10933       else if (move_fn_p (decl) && user_provided_p (decl))
10934         TYPE_HAS_COMPLEX_MOVE_CTOR (class_type) = 1;
10935       else if (is_list_ctor (decl))
10936         TYPE_HAS_LIST_CTOR (class_type) = 1;
10937
10938       if (DECL_DECLARED_CONSTEXPR_P (decl)
10939           && !copy_fn_p (decl) && !move_fn_p (decl))
10940         TYPE_HAS_CONSTEXPR_CTOR (class_type) = 1;
10941     }
10942   else if (DECL_OVERLOADED_OPERATOR_P (decl) == NOP_EXPR)
10943     {
10944       /* [class.copy]
10945
10946          A non-template assignment operator for class X is a copy
10947          assignment operator if its parameter is of type X, X&, const
10948          X&, volatile X& or const volatile X&.  */
10949
10950       int assop = copy_fn_p (decl);
10951
10952       if (assop)
10953         {
10954           TYPE_HAS_COPY_ASSIGN (class_type) = 1;
10955           if (user_provided_p (decl))
10956             TYPE_HAS_COMPLEX_COPY_ASSIGN (class_type) = 1;
10957           if (assop != 1)
10958             TYPE_HAS_CONST_COPY_ASSIGN (class_type) = 1;
10959         }
10960       else if (move_fn_p (decl) && user_provided_p (decl))
10961         TYPE_HAS_COMPLEX_MOVE_ASSIGN (class_type) = 1;
10962     }
10963   /* Destructors are handled in check_methods.  */
10964 }
10965
10966 /* Check a constructor DECL has the correct form.  Complains
10967    if the class has a constructor of the form X(X).  */
10968
10969 int
10970 grok_ctor_properties (const_tree ctype, const_tree decl)
10971 {
10972   int ctor_parm = copy_fn_p (decl);
10973
10974   if (ctor_parm < 0)
10975     {
10976       /* [class.copy]
10977
10978          A declaration of a constructor for a class X is ill-formed if
10979          its first parameter is of type (optionally cv-qualified) X
10980          and either there are no other parameters or else all other
10981          parameters have default arguments.
10982
10983          We *don't* complain about member template instantiations that
10984          have this form, though; they can occur as we try to decide
10985          what constructor to use during overload resolution.  Since
10986          overload resolution will never prefer such a constructor to
10987          the non-template copy constructor (which is either explicitly
10988          or implicitly defined), there's no need to worry about their
10989          existence.  Theoretically, they should never even be
10990          instantiated, but that's hard to forestall.  */
10991       error ("invalid constructor; you probably meant %<%T (const %T&)%>",
10992                 ctype, ctype);
10993       return 0;
10994     }
10995
10996   return 1;
10997 }
10998
10999 /* An operator with this code is unary, but can also be binary.  */
11000
11001 static int
11002 ambi_op_p (enum tree_code code)
11003 {
11004   return (code == INDIRECT_REF
11005           || code == ADDR_EXPR
11006           || code == UNARY_PLUS_EXPR
11007           || code == NEGATE_EXPR
11008           || code == PREINCREMENT_EXPR
11009           || code == PREDECREMENT_EXPR);
11010 }
11011
11012 /* An operator with this name can only be unary.  */
11013
11014 static int
11015 unary_op_p (enum tree_code code)
11016 {
11017   return (code == TRUTH_NOT_EXPR
11018           || code == BIT_NOT_EXPR
11019           || code == COMPONENT_REF
11020           || code == TYPE_EXPR);
11021 }
11022
11023 /* DECL is a declaration for an overloaded operator.  If COMPLAIN is true,
11024    errors are issued for invalid declarations.  */
11025
11026 bool
11027 grok_op_properties (tree decl, bool complain)
11028 {
11029   tree argtypes = TYPE_ARG_TYPES (TREE_TYPE (decl));
11030   tree argtype;
11031   int methodp = (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE);
11032   tree name = DECL_NAME (decl);
11033   enum tree_code operator_code;
11034   int arity;
11035   bool ellipsis_p;
11036   tree class_type;
11037
11038   /* Count the number of arguments and check for ellipsis.  */
11039   for (argtype = argtypes, arity = 0;
11040        argtype && argtype != void_list_node;
11041        argtype = TREE_CHAIN (argtype))
11042     ++arity;
11043   ellipsis_p = !argtype;
11044
11045   class_type = DECL_CONTEXT (decl);
11046   if (class_type && !CLASS_TYPE_P (class_type))
11047     class_type = NULL_TREE;
11048
11049   if (DECL_CONV_FN_P (decl))
11050     operator_code = TYPE_EXPR;
11051   else
11052     do
11053       {
11054 #define DEF_OPERATOR(NAME, CODE, MANGLING, ARITY, ASSN_P)       \
11055         if (ansi_opname (CODE) == name)                         \
11056           {                                                     \
11057             operator_code = (CODE);                             \
11058             break;                                              \
11059           }                                                     \
11060         else if (ansi_assopname (CODE) == name)                 \
11061           {                                                     \
11062             operator_code = (CODE);                             \
11063             DECL_ASSIGNMENT_OPERATOR_P (decl) = 1;              \
11064             break;                                              \
11065           }
11066
11067 #include "operators.def"
11068 #undef DEF_OPERATOR
11069
11070         gcc_unreachable ();
11071       }
11072     while (0);
11073   gcc_assert (operator_code != MAX_TREE_CODES);
11074   SET_OVERLOADED_OPERATOR_CODE (decl, operator_code);
11075
11076   if (class_type)
11077     switch (operator_code)
11078       {
11079       case NEW_EXPR:
11080         TYPE_HAS_NEW_OPERATOR (class_type) = 1;
11081         break;
11082
11083       case DELETE_EXPR:
11084         TYPE_GETS_DELETE (class_type) |= 1;
11085         break;
11086
11087       case VEC_NEW_EXPR:
11088         TYPE_HAS_ARRAY_NEW_OPERATOR (class_type) = 1;
11089         break;
11090
11091       case VEC_DELETE_EXPR:
11092         TYPE_GETS_DELETE (class_type) |= 2;
11093         break;
11094
11095       default:
11096         break;
11097       }
11098
11099     /* [basic.std.dynamic.allocation]/1:
11100
11101        A program is ill-formed if an allocation function is declared
11102        in a namespace scope other than global scope or declared static
11103        in global scope.
11104
11105        The same also holds true for deallocation functions.  */
11106   if (operator_code == NEW_EXPR || operator_code == VEC_NEW_EXPR
11107       || operator_code == DELETE_EXPR || operator_code == VEC_DELETE_EXPR)
11108     {
11109       if (DECL_NAMESPACE_SCOPE_P (decl))
11110         {
11111           if (CP_DECL_CONTEXT (decl) != global_namespace)
11112             {
11113               error ("%qD may not be declared within a namespace", decl);
11114               return false;
11115             }
11116           else if (!TREE_PUBLIC (decl))
11117             {
11118               error ("%qD may not be declared as static", decl);
11119               return false;
11120             }
11121         }
11122     }
11123
11124   if (operator_code == NEW_EXPR || operator_code == VEC_NEW_EXPR)
11125     {
11126       TREE_TYPE (decl) = coerce_new_type (TREE_TYPE (decl));
11127       DECL_IS_OPERATOR_NEW (decl) = 1;
11128     }
11129   else if (operator_code == DELETE_EXPR || operator_code == VEC_DELETE_EXPR)
11130     TREE_TYPE (decl) = coerce_delete_type (TREE_TYPE (decl));
11131   else
11132     {
11133       /* An operator function must either be a non-static member function
11134          or have at least one parameter of a class, a reference to a class,
11135          an enumeration, or a reference to an enumeration.  13.4.0.6 */
11136       if (! methodp || DECL_STATIC_FUNCTION_P (decl))
11137         {
11138           if (operator_code == TYPE_EXPR
11139               || operator_code == CALL_EXPR
11140               || operator_code == COMPONENT_REF
11141               || operator_code == ARRAY_REF
11142               || operator_code == NOP_EXPR)
11143             {
11144               error ("%qD must be a nonstatic member function", decl);
11145               return false;
11146             }
11147           else
11148             {
11149               tree p;
11150
11151               if (DECL_STATIC_FUNCTION_P (decl))
11152                 {
11153                   error ("%qD must be either a non-static member "
11154                          "function or a non-member function", decl);
11155                   return false;
11156                 }
11157
11158               for (p = argtypes; p && p != void_list_node; p = TREE_CHAIN (p))
11159                 {
11160                   tree arg = non_reference (TREE_VALUE (p));
11161                   if (arg == error_mark_node)
11162                     return false;
11163
11164                   /* MAYBE_CLASS_TYPE_P, rather than CLASS_TYPE_P, is used
11165                      because these checks are performed even on
11166                      template functions.  */
11167                   if (MAYBE_CLASS_TYPE_P (arg)
11168                       || TREE_CODE (arg) == ENUMERAL_TYPE)
11169                     break;
11170                 }
11171
11172               if (!p || p == void_list_node)
11173                 {
11174                   if (complain)
11175                     error ("%qD must have an argument of class or "
11176                            "enumerated type", decl);
11177                   return false;
11178                 }
11179             }
11180         }
11181
11182       /* There are no restrictions on the arguments to an overloaded
11183          "operator ()".  */
11184       if (operator_code == CALL_EXPR)
11185         return true;
11186
11187       /* Warn about conversion operators that will never be used.  */
11188       if (IDENTIFIER_TYPENAME_P (name)
11189           && ! DECL_TEMPLATE_INFO (decl)
11190           && warn_conversion
11191           /* Warn only declaring the function; there is no need to
11192              warn again about out-of-class definitions.  */
11193           && class_type == current_class_type)
11194         {
11195           tree t = TREE_TYPE (name);
11196           int ref = (TREE_CODE (t) == REFERENCE_TYPE);
11197
11198           if (ref)
11199             t = TYPE_MAIN_VARIANT (TREE_TYPE (t));
11200
11201           if (TREE_CODE (t) == VOID_TYPE)
11202             warning (OPT_Wconversion,
11203                      ref
11204                      ? G_("conversion to a reference to void "
11205                           "will never use a type conversion operator")
11206                      : G_("conversion to void "
11207                           "will never use a type conversion operator"));
11208           else if (class_type)
11209             {
11210               if (t == class_type)
11211                 warning (OPT_Wconversion,
11212                      ref
11213                      ? G_("conversion to a reference to the same type "
11214                           "will never use a type conversion operator")
11215                      : G_("conversion to the same type "
11216                           "will never use a type conversion operator"));                
11217               /* Don't force t to be complete here.  */
11218               else if (MAYBE_CLASS_TYPE_P (t)
11219                        && COMPLETE_TYPE_P (t)
11220                        && DERIVED_FROM_P (t, class_type))
11221                  warning (OPT_Wconversion,
11222                           ref
11223                           ? G_("conversion to a reference to a base class "
11224                                "will never use a type conversion operator")
11225                           : G_("conversion to a base class "
11226                                "will never use a type conversion operator"));           
11227             }
11228
11229         }
11230
11231       if (operator_code == COND_EXPR)
11232         {
11233           /* 13.4.0.3 */
11234           error ("ISO C++ prohibits overloading operator ?:");
11235           return false;
11236         }
11237       else if (ellipsis_p)
11238         {
11239           error ("%qD must not have variable number of arguments", decl);
11240           return false;
11241         }
11242       else if (ambi_op_p (operator_code))
11243         {
11244           if (arity == 1)
11245             /* We pick the one-argument operator codes by default, so
11246                we don't have to change anything.  */
11247             ;
11248           else if (arity == 2)
11249             {
11250               /* If we thought this was a unary operator, we now know
11251                  it to be a binary operator.  */
11252               switch (operator_code)
11253                 {
11254                 case INDIRECT_REF:
11255                   operator_code = MULT_EXPR;
11256                   break;
11257
11258                 case ADDR_EXPR:
11259                   operator_code = BIT_AND_EXPR;
11260                   break;
11261
11262                 case UNARY_PLUS_EXPR:
11263                   operator_code = PLUS_EXPR;
11264                   break;
11265
11266                 case NEGATE_EXPR:
11267                   operator_code = MINUS_EXPR;
11268                   break;
11269
11270                 case PREINCREMENT_EXPR:
11271                   operator_code = POSTINCREMENT_EXPR;
11272                   break;
11273
11274                 case PREDECREMENT_EXPR:
11275                   operator_code = POSTDECREMENT_EXPR;
11276                   break;
11277
11278                 default:
11279                   gcc_unreachable ();
11280                 }
11281
11282               SET_OVERLOADED_OPERATOR_CODE (decl, operator_code);
11283
11284               if ((operator_code == POSTINCREMENT_EXPR
11285                    || operator_code == POSTDECREMENT_EXPR)
11286                   && ! processing_template_decl
11287                   && ! same_type_p (TREE_VALUE (TREE_CHAIN (argtypes)), integer_type_node))
11288                 {
11289                   if (methodp)
11290                     error ("postfix %qD must take %<int%> as its argument",
11291                            decl);
11292                   else
11293                     error ("postfix %qD must take %<int%> as its second "
11294                            "argument", decl);
11295                   return false;
11296                 }
11297             }
11298           else
11299             {
11300               if (methodp)
11301                 error ("%qD must take either zero or one argument", decl);
11302               else
11303                 error ("%qD must take either one or two arguments", decl);
11304               return false;
11305             }
11306
11307           /* More Effective C++ rule 6.  */
11308           if (warn_ecpp
11309               && (operator_code == POSTINCREMENT_EXPR
11310                   || operator_code == POSTDECREMENT_EXPR
11311                   || operator_code == PREINCREMENT_EXPR
11312                   || operator_code == PREDECREMENT_EXPR))
11313             {
11314               tree arg = TREE_VALUE (argtypes);
11315               tree ret = TREE_TYPE (TREE_TYPE (decl));
11316               if (methodp || TREE_CODE (arg) == REFERENCE_TYPE)
11317                 arg = TREE_TYPE (arg);
11318               arg = TYPE_MAIN_VARIANT (arg);
11319               if (operator_code == PREINCREMENT_EXPR
11320                   || operator_code == PREDECREMENT_EXPR)
11321                 {
11322                   if (TREE_CODE (ret) != REFERENCE_TYPE
11323                       || !same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (ret)),
11324                                        arg))
11325                     warning (OPT_Weffc__, "prefix %qD should return %qT", decl,
11326                              build_reference_type (arg));
11327                 }
11328               else
11329                 {
11330                   if (!same_type_p (TYPE_MAIN_VARIANT (ret), arg))
11331                     warning (OPT_Weffc__, "postfix %qD should return %qT", decl, arg);
11332                 }
11333             }
11334         }
11335       else if (unary_op_p (operator_code))
11336         {
11337           if (arity != 1)
11338             {
11339               if (methodp)
11340                 error ("%qD must take %<void%>", decl);
11341               else
11342                 error ("%qD must take exactly one argument", decl);
11343               return false;
11344             }
11345         }
11346       else /* if (binary_op_p (operator_code)) */
11347         {
11348           if (arity != 2)
11349             {
11350               if (methodp)
11351                 error ("%qD must take exactly one argument", decl);
11352               else
11353                 error ("%qD must take exactly two arguments", decl);
11354               return false;
11355             }
11356
11357           /* More Effective C++ rule 7.  */
11358           if (warn_ecpp
11359               && (operator_code == TRUTH_ANDIF_EXPR
11360                   || operator_code == TRUTH_ORIF_EXPR
11361                   || operator_code == COMPOUND_EXPR))
11362             warning (OPT_Weffc__, "user-defined %qD always evaluates both arguments",
11363                      decl);
11364         }
11365
11366       /* Effective C++ rule 23.  */
11367       if (warn_ecpp
11368           && arity == 2
11369           && !DECL_ASSIGNMENT_OPERATOR_P (decl)
11370           && (operator_code == PLUS_EXPR
11371               || operator_code == MINUS_EXPR
11372               || operator_code == TRUNC_DIV_EXPR
11373               || operator_code == MULT_EXPR
11374               || operator_code == TRUNC_MOD_EXPR)
11375           && TREE_CODE (TREE_TYPE (TREE_TYPE (decl))) == REFERENCE_TYPE)
11376         warning (OPT_Weffc__, "%qD should return by value", decl);
11377
11378       /* [over.oper]/8 */
11379       for (; argtypes && argtypes != void_list_node;
11380           argtypes = TREE_CHAIN (argtypes))
11381         if (TREE_PURPOSE (argtypes))
11382           {
11383             TREE_PURPOSE (argtypes) = NULL_TREE;
11384             if (operator_code == POSTINCREMENT_EXPR
11385                 || operator_code == POSTDECREMENT_EXPR)
11386               {
11387                 pedwarn (input_location, OPT_Wpedantic, "%qD cannot have default arguments", 
11388                          decl);
11389               }
11390             else
11391               {
11392                 error ("%qD cannot have default arguments", decl);
11393                 return false;
11394               }
11395           }
11396     }
11397   return true;
11398 }
11399 \f
11400 /* Return a string giving the keyword associate with CODE.  */
11401
11402 static const char *
11403 tag_name (enum tag_types code)
11404 {
11405   switch (code)
11406     {
11407     case record_type:
11408       return "struct";
11409     case class_type:
11410       return "class";
11411     case union_type:
11412       return "union";
11413     case enum_type:
11414       return "enum";
11415     case typename_type:
11416       return "typename";
11417     default:
11418       gcc_unreachable ();
11419     }
11420 }
11421
11422 /* Name lookup in an elaborated-type-specifier (after the keyword
11423    indicated by TAG_CODE) has found the TYPE_DECL DECL.  If the
11424    elaborated-type-specifier is invalid, issue a diagnostic and return
11425    error_mark_node; otherwise, return the *_TYPE to which it referred.
11426    If ALLOW_TEMPLATE_P is true, TYPE may be a class template.  */
11427
11428 tree
11429 check_elaborated_type_specifier (enum tag_types tag_code,
11430                                  tree decl,
11431                                  bool allow_template_p)
11432 {
11433   tree type;
11434
11435   if (decl == error_mark_node)
11436     return error_mark_node;
11437
11438   /* In the case of:
11439
11440        struct S { struct S *p; };
11441
11442      name lookup will find the TYPE_DECL for the implicit "S::S"
11443      typedef.  Adjust for that here.  */
11444   if (DECL_SELF_REFERENCE_P (decl))
11445     decl = TYPE_NAME (TREE_TYPE (decl));
11446
11447   type = TREE_TYPE (decl);
11448
11449   /* Check TEMPLATE_TYPE_PARM first because DECL_IMPLICIT_TYPEDEF_P
11450      is false for this case as well.  */
11451   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
11452     {
11453       error ("using template type parameter %qT after %qs",
11454              type, tag_name (tag_code));
11455       return error_mark_node;
11456     }
11457   /* Accept template template parameters.  */
11458   else if (allow_template_p
11459            && (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
11460                || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM))
11461     ;
11462   /*   [dcl.type.elab]
11463
11464        If the identifier resolves to a typedef-name or the
11465        simple-template-id resolves to an alias template
11466        specialization, the elaborated-type-specifier is ill-formed.
11467
11468      In other words, the only legitimate declaration to use in the
11469      elaborated type specifier is the implicit typedef created when
11470      the type is declared.  */
11471   else if (!DECL_IMPLICIT_TYPEDEF_P (decl)
11472            && !DECL_SELF_REFERENCE_P (decl)
11473            && tag_code != typename_type)
11474     {
11475       if (alias_template_specialization_p (type))
11476         error ("using alias template specialization %qT after %qs",
11477                type, tag_name (tag_code));
11478       else
11479         error ("using typedef-name %qD after %qs", decl, tag_name (tag_code));
11480       inform (DECL_SOURCE_LOCATION (decl),
11481               "%qD has a previous declaration here", decl);
11482       return error_mark_node;
11483     }
11484   else if (TREE_CODE (type) != RECORD_TYPE
11485            && TREE_CODE (type) != UNION_TYPE
11486            && tag_code != enum_type
11487            && tag_code != typename_type)
11488     {
11489       error ("%qT referred to as %qs", type, tag_name (tag_code));
11490       error ("%q+T has a previous declaration here", type);
11491       return error_mark_node;
11492     }
11493   else if (TREE_CODE (type) != ENUMERAL_TYPE
11494            && tag_code == enum_type)
11495     {
11496       error ("%qT referred to as enum", type);
11497       error ("%q+T has a previous declaration here", type);
11498       return error_mark_node;
11499     }
11500   else if (!allow_template_p
11501            && TREE_CODE (type) == RECORD_TYPE
11502            && CLASSTYPE_IS_TEMPLATE (type))
11503     {
11504       /* If a class template appears as elaborated type specifier
11505          without a template header such as:
11506
11507            template <class T> class C {};
11508            void f(class C);             // No template header here
11509
11510          then the required template argument is missing.  */
11511       error ("template argument required for %<%s %T%>",
11512              tag_name (tag_code),
11513              DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)));
11514       return error_mark_node;
11515     }
11516
11517   return type;
11518 }
11519
11520 /* Lookup NAME in elaborate type specifier in scope according to
11521    SCOPE and issue diagnostics if necessary.
11522    Return *_TYPE node upon success, NULL_TREE when the NAME is not
11523    found, and ERROR_MARK_NODE for type error.  */
11524
11525 static tree
11526 lookup_and_check_tag (enum tag_types tag_code, tree name,
11527                       tag_scope scope, bool template_header_p)
11528 {
11529   tree t;
11530   tree decl;
11531   if (scope == ts_global)
11532     {
11533       /* First try ordinary name lookup, ignoring hidden class name
11534          injected via friend declaration.  */
11535       decl = lookup_name_prefer_type (name, 2);
11536       /* If that fails, the name will be placed in the smallest
11537          non-class, non-function-prototype scope according to 3.3.1/5.
11538          We may already have a hidden name declared as friend in this
11539          scope.  So lookup again but not ignoring hidden names.
11540          If we find one, that name will be made visible rather than
11541          creating a new tag.  */
11542       if (!decl)
11543         decl = lookup_type_scope (name, ts_within_enclosing_non_class);
11544     }
11545   else
11546     decl = lookup_type_scope (name, scope);
11547
11548   if (decl
11549       && (DECL_CLASS_TEMPLATE_P (decl)
11550           || DECL_TEMPLATE_TEMPLATE_PARM_P (decl)))
11551     decl = DECL_TEMPLATE_RESULT (decl);
11552
11553   if (decl && TREE_CODE (decl) == TYPE_DECL)
11554     {
11555       /* Look for invalid nested type:
11556            class C {
11557              class C {};
11558            };  */
11559       if (scope == ts_current && DECL_SELF_REFERENCE_P (decl))
11560         {
11561           error ("%qD has the same name as the class in which it is "
11562                  "declared",
11563                  decl);
11564           return error_mark_node;
11565         }
11566
11567       /* Two cases we need to consider when deciding if a class
11568          template is allowed as an elaborated type specifier:
11569          1. It is a self reference to its own class.
11570          2. It comes with a template header.
11571
11572          For example:
11573
11574            template <class T> class C {
11575              class C *c1;               // DECL_SELF_REFERENCE_P is true
11576              class D;
11577            };
11578            template <class U> class C; // template_header_p is true
11579            template <class T> class C<T>::D {
11580              class C *c2;               // DECL_SELF_REFERENCE_P is true
11581            };  */
11582
11583       t = check_elaborated_type_specifier (tag_code,
11584                                            decl,
11585                                            template_header_p
11586                                            | DECL_SELF_REFERENCE_P (decl));
11587       return t;
11588     }
11589   else if (decl && TREE_CODE (decl) == TREE_LIST)
11590     {
11591       error ("reference to %qD is ambiguous", name);
11592       print_candidates (decl);
11593       return error_mark_node;
11594     }
11595   else
11596     return NULL_TREE;
11597 }
11598
11599 /* Get the struct, enum or union (TAG_CODE says which) with tag NAME.
11600    Define the tag as a forward-reference if it is not defined.
11601
11602    If a declaration is given, process it here, and report an error if
11603    multiple declarations are not identical.
11604
11605    SCOPE is TS_CURRENT when this is also a definition.  Only look in
11606    the current frame for the name (since C++ allows new names in any
11607    scope.)  It is TS_WITHIN_ENCLOSING_NON_CLASS if this is a friend
11608    declaration.  Only look beginning from the current scope outward up
11609    till the nearest non-class scope.  Otherwise it is TS_GLOBAL.
11610
11611    TEMPLATE_HEADER_P is true when this declaration is preceded by
11612    a set of template parameters.  */
11613
11614 static tree
11615 xref_tag_1 (enum tag_types tag_code, tree name,
11616             tag_scope scope, bool template_header_p)
11617 {
11618   enum tree_code code;
11619   tree t;
11620   tree context = NULL_TREE;
11621
11622   gcc_assert (TREE_CODE (name) == IDENTIFIER_NODE);
11623
11624   switch (tag_code)
11625     {
11626     case record_type:
11627     case class_type:
11628       code = RECORD_TYPE;
11629       break;
11630     case union_type:
11631       code = UNION_TYPE;
11632       break;
11633     case enum_type:
11634       code = ENUMERAL_TYPE;
11635       break;
11636     default:
11637       gcc_unreachable ();
11638     }
11639
11640   /* In case of anonymous name, xref_tag is only called to
11641      make type node and push name.  Name lookup is not required.  */
11642   if (ANON_AGGRNAME_P (name))
11643     t = NULL_TREE;
11644   else
11645     t = lookup_and_check_tag  (tag_code, name,
11646                                scope, template_header_p);
11647
11648   if (t == error_mark_node)
11649     return error_mark_node;
11650
11651   if (scope != ts_current && t && current_class_type
11652       && template_class_depth (current_class_type)
11653       && template_header_p)
11654     {
11655       if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
11656         return t;
11657
11658       /* Since SCOPE is not TS_CURRENT, we are not looking at a
11659          definition of this tag.  Since, in addition, we are currently
11660          processing a (member) template declaration of a template
11661          class, we must be very careful; consider:
11662
11663            template <class X>
11664            struct S1
11665
11666            template <class U>
11667            struct S2
11668            { template <class V>
11669            friend struct S1; };
11670
11671          Here, the S2::S1 declaration should not be confused with the
11672          outer declaration.  In particular, the inner version should
11673          have a template parameter of level 2, not level 1.  This
11674          would be particularly important if the member declaration
11675          were instead:
11676
11677            template <class V = U> friend struct S1;
11678
11679          say, when we should tsubst into `U' when instantiating
11680          S2.  On the other hand, when presented with:
11681
11682            template <class T>
11683            struct S1 {
11684              template <class U>
11685              struct S2 {};
11686              template <class U>
11687              friend struct S2;
11688            };
11689
11690          we must find the inner binding eventually.  We
11691          accomplish this by making sure that the new type we
11692          create to represent this declaration has the right
11693          TYPE_CONTEXT.  */
11694       context = TYPE_CONTEXT (t);
11695       t = NULL_TREE;
11696     }
11697
11698   if (! t)
11699     {
11700       /* If no such tag is yet defined, create a forward-reference node
11701          and record it as the "definition".
11702          When a real declaration of this type is found,
11703          the forward-reference will be altered into a real type.  */
11704       if (code == ENUMERAL_TYPE)
11705         {
11706           error ("use of enum %q#D without previous declaration", name);
11707           return error_mark_node;
11708         }
11709       else
11710         {
11711           t = make_class_type (code);
11712           TYPE_CONTEXT (t) = context;
11713           t = pushtag (name, t, scope);
11714         }
11715     }
11716   else
11717     {
11718       if (template_header_p && MAYBE_CLASS_TYPE_P (t))
11719         {
11720           if (!redeclare_class_template (t, current_template_parms))
11721             return error_mark_node;
11722         }
11723       else if (!processing_template_decl
11724                && CLASS_TYPE_P (t)
11725                && CLASSTYPE_IS_TEMPLATE (t))
11726         {
11727           error ("redeclaration of %qT as a non-template", t);
11728           error ("previous declaration %q+D", t);
11729           return error_mark_node;
11730         }
11731
11732       /* Make injected friend class visible.  */
11733       if (scope != ts_within_enclosing_non_class
11734           && hidden_name_p (TYPE_NAME (t)))
11735         {
11736           DECL_ANTICIPATED (TYPE_NAME (t)) = 0;
11737           DECL_FRIEND_P (TYPE_NAME (t)) = 0;
11738
11739           if (TYPE_TEMPLATE_INFO (t))
11740             {
11741               DECL_ANTICIPATED (TYPE_TI_TEMPLATE (t)) = 0;
11742               DECL_FRIEND_P (TYPE_TI_TEMPLATE (t)) = 0;
11743             }
11744         }
11745     }
11746
11747   return t;
11748 }
11749
11750 /* Wrapper for xref_tag_1.  */
11751
11752 tree
11753 xref_tag (enum tag_types tag_code, tree name,
11754           tag_scope scope, bool template_header_p)
11755 {
11756   tree ret;
11757   bool subtime;
11758   subtime = timevar_cond_start (TV_NAME_LOOKUP);
11759   ret = xref_tag_1 (tag_code, name, scope, template_header_p);
11760   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
11761   return ret;
11762 }
11763
11764
11765 tree
11766 xref_tag_from_type (tree old, tree id, tag_scope scope)
11767 {
11768   enum tag_types tag_kind;
11769
11770   if (TREE_CODE (old) == RECORD_TYPE)
11771     tag_kind = (CLASSTYPE_DECLARED_CLASS (old) ? class_type : record_type);
11772   else
11773     tag_kind  = union_type;
11774
11775   if (id == NULL_TREE)
11776     id = TYPE_IDENTIFIER (old);
11777
11778   return xref_tag (tag_kind, id, scope, false);
11779 }
11780
11781 /* Create the binfo hierarchy for REF with (possibly NULL) base list
11782    BASE_LIST.  For each element on BASE_LIST the TREE_PURPOSE is an
11783    access_* node, and the TREE_VALUE is the type of the base-class.
11784    Non-NULL TREE_TYPE indicates virtual inheritance.  
11785  
11786    Returns true if the binfo hierarchy was successfully created,
11787    false if an error was detected. */
11788
11789 bool
11790 xref_basetypes (tree ref, tree base_list)
11791 {
11792   tree *basep;
11793   tree binfo, base_binfo;
11794   unsigned max_vbases = 0; /* Maximum direct & indirect virtual bases.  */
11795   unsigned max_bases = 0;  /* Maximum direct bases.  */
11796   int i;
11797   tree default_access;
11798   tree igo_prev; /* Track Inheritance Graph Order.  */
11799
11800   if (ref == error_mark_node)
11801     return false;
11802
11803   /* The base of a derived class is private by default, all others are
11804      public.  */
11805   default_access = (TREE_CODE (ref) == RECORD_TYPE
11806                     && CLASSTYPE_DECLARED_CLASS (ref)
11807                     ? access_private_node : access_public_node);
11808
11809   /* First, make sure that any templates in base-classes are
11810      instantiated.  This ensures that if we call ourselves recursively
11811      we do not get confused about which classes are marked and which
11812      are not.  */
11813   basep = &base_list;
11814   while (*basep)
11815     {
11816       tree basetype = TREE_VALUE (*basep);
11817
11818       /* The dependent_type_p call below should really be dependent_scope_p
11819          so that we give a hard error about using an incomplete type as a
11820          base, but we allow it with a pedwarn for backward
11821          compatibility.  */
11822       if (processing_template_decl
11823           && CLASS_TYPE_P (basetype) && TYPE_BEING_DEFINED (basetype))
11824         cxx_incomplete_type_diagnostic (NULL_TREE, basetype, DK_PEDWARN);
11825       if (!dependent_type_p (basetype)
11826           && !complete_type_or_else (basetype, NULL))
11827         /* An incomplete type.  Remove it from the list.  */
11828         *basep = TREE_CHAIN (*basep);
11829       else
11830         {
11831           max_bases++;
11832           if (TREE_TYPE (*basep))
11833             max_vbases++;
11834           if (CLASS_TYPE_P (basetype))
11835             max_vbases += VEC_length (tree, CLASSTYPE_VBASECLASSES (basetype));
11836           basep = &TREE_CHAIN (*basep);
11837         }
11838     }
11839
11840   TYPE_MARKED_P (ref) = 1;
11841
11842   /* The binfo slot should be empty, unless this is an (ill-formed)
11843      redefinition.  */
11844   if (TYPE_BINFO (ref) && !TYPE_SIZE (ref))
11845     {
11846       error ("redefinition of %q#T", ref);
11847       return false;
11848     }
11849
11850   gcc_assert (TYPE_MAIN_VARIANT (ref) == ref);
11851
11852   binfo = make_tree_binfo (max_bases);
11853
11854   TYPE_BINFO (ref) = binfo;
11855   BINFO_OFFSET (binfo) = size_zero_node;
11856   BINFO_TYPE (binfo) = ref;
11857
11858   /* Apply base-class info set up to the variants of this type.  */
11859   fixup_type_variants (ref);
11860
11861   if (max_bases)
11862     {
11863       BINFO_BASE_ACCESSES (binfo) = VEC_alloc (tree, gc, max_bases);
11864       /* An aggregate cannot have baseclasses.  */
11865       CLASSTYPE_NON_AGGREGATE (ref) = 1;
11866
11867       if (TREE_CODE (ref) == UNION_TYPE)
11868         {
11869           error ("derived union %qT invalid", ref);
11870           return false;
11871         }
11872     }
11873
11874   if (max_bases > 1)
11875     {
11876       if (TYPE_FOR_JAVA (ref))
11877         {
11878           error ("Java class %qT cannot have multiple bases", ref);
11879           return false;
11880         }
11881     }
11882
11883   if (max_vbases)
11884     {
11885       CLASSTYPE_VBASECLASSES (ref) = VEC_alloc (tree, gc, max_vbases);
11886
11887       if (TYPE_FOR_JAVA (ref))
11888         {
11889           error ("Java class %qT cannot have virtual bases", ref);
11890           return false;
11891         }
11892     }
11893
11894   for (igo_prev = binfo; base_list; base_list = TREE_CHAIN (base_list))
11895     {
11896       tree access = TREE_PURPOSE (base_list);
11897       int via_virtual = TREE_TYPE (base_list) != NULL_TREE;
11898       tree basetype = TREE_VALUE (base_list);
11899
11900       if (access == access_default_node)
11901         access = default_access;
11902
11903       if (PACK_EXPANSION_P (basetype))
11904         basetype = PACK_EXPANSION_PATTERN (basetype);
11905       if (TREE_CODE (basetype) == TYPE_DECL)
11906         basetype = TREE_TYPE (basetype);
11907       if (!MAYBE_CLASS_TYPE_P (basetype) || TREE_CODE (basetype) == UNION_TYPE)
11908         {
11909           error ("base type %qT fails to be a struct or class type",
11910                  basetype);
11911           return false;
11912         }
11913
11914       if (TYPE_FOR_JAVA (basetype) && (current_lang_depth () == 0))
11915         TYPE_FOR_JAVA (ref) = 1;
11916
11917       base_binfo = NULL_TREE;
11918       if (CLASS_TYPE_P (basetype) && !dependent_scope_p (basetype))
11919         {
11920           base_binfo = TYPE_BINFO (basetype);
11921           /* The original basetype could have been a typedef'd type.  */
11922           basetype = BINFO_TYPE (base_binfo);
11923
11924           /* Inherit flags from the base.  */
11925           TYPE_HAS_NEW_OPERATOR (ref)
11926             |= TYPE_HAS_NEW_OPERATOR (basetype);
11927           TYPE_HAS_ARRAY_NEW_OPERATOR (ref)
11928             |= TYPE_HAS_ARRAY_NEW_OPERATOR (basetype);
11929           TYPE_GETS_DELETE (ref) |= TYPE_GETS_DELETE (basetype);
11930           TYPE_HAS_CONVERSION (ref) |= TYPE_HAS_CONVERSION (basetype);
11931           CLASSTYPE_DIAMOND_SHAPED_P (ref)
11932             |= CLASSTYPE_DIAMOND_SHAPED_P (basetype);
11933           CLASSTYPE_REPEATED_BASE_P (ref)
11934             |= CLASSTYPE_REPEATED_BASE_P (basetype);
11935         }
11936
11937       /* We must do this test after we've seen through a typedef
11938          type.  */
11939       if (TYPE_MARKED_P (basetype))
11940         {
11941           if (basetype == ref)
11942             error ("recursive type %qT undefined", basetype);
11943           else
11944             error ("duplicate base type %qT invalid", basetype);
11945           return false;
11946         }
11947
11948       if (PACK_EXPANSION_P (TREE_VALUE (base_list)))
11949         /* Regenerate the pack expansion for the bases. */
11950         basetype = make_pack_expansion (basetype);
11951
11952       TYPE_MARKED_P (basetype) = 1;
11953
11954       base_binfo = copy_binfo (base_binfo, basetype, ref,
11955                                &igo_prev, via_virtual);
11956       if (!BINFO_INHERITANCE_CHAIN (base_binfo))
11957         BINFO_INHERITANCE_CHAIN (base_binfo) = binfo;
11958
11959       BINFO_BASE_APPEND (binfo, base_binfo);
11960       BINFO_BASE_ACCESS_APPEND (binfo, access);
11961     }
11962
11963   if (VEC_length (tree, CLASSTYPE_VBASECLASSES (ref)) < max_vbases)
11964     /* If we didn't get max_vbases vbases, we must have shared at
11965        least one of them, and are therefore diamond shaped.  */
11966     CLASSTYPE_DIAMOND_SHAPED_P (ref) = 1;
11967
11968   /* Unmark all the types.  */
11969   for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
11970     TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
11971   TYPE_MARKED_P (ref) = 0;
11972
11973   /* Now see if we have a repeated base type.  */
11974   if (!CLASSTYPE_REPEATED_BASE_P (ref))
11975     {
11976       for (base_binfo = binfo; base_binfo;
11977            base_binfo = TREE_CHAIN (base_binfo))
11978         {
11979           if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
11980             {
11981               CLASSTYPE_REPEATED_BASE_P (ref) = 1;
11982               break;
11983             }
11984           TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 1;
11985         }
11986       for (base_binfo = binfo; base_binfo;
11987            base_binfo = TREE_CHAIN (base_binfo))
11988         if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
11989           TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
11990         else
11991           break;
11992     }
11993
11994   return true;
11995 }
11996
11997 \f
11998 /* Copies the enum-related properties from type SRC to type DST.
11999    Used with the underlying type of an enum and the enum itself.  */
12000 static void
12001 copy_type_enum (tree dst, tree src)
12002 {
12003   tree t;
12004   for (t = dst; t; t = TYPE_NEXT_VARIANT (t))
12005     {
12006       TYPE_MIN_VALUE (t) = TYPE_MIN_VALUE (src);
12007       TYPE_MAX_VALUE (t) = TYPE_MAX_VALUE (src);
12008       TYPE_SIZE (t) = TYPE_SIZE (src);
12009       TYPE_SIZE_UNIT (t) = TYPE_SIZE_UNIT (src);
12010       SET_TYPE_MODE (dst, TYPE_MODE (src));
12011       TYPE_PRECISION (t) = TYPE_PRECISION (src);
12012       TYPE_ALIGN (t) = TYPE_ALIGN (src);
12013       TYPE_USER_ALIGN (t) = TYPE_USER_ALIGN (src);
12014       TYPE_UNSIGNED (t) = TYPE_UNSIGNED (src);
12015     }
12016 }
12017
12018 /* Begin compiling the definition of an enumeration type.
12019    NAME is its name, 
12020
12021    if ENUMTYPE is not NULL_TREE then the type has alredy been found.
12022
12023    UNDERLYING_TYPE is the type that will be used as the storage for
12024    the enumeration type. This should be NULL_TREE if no storage type
12025    was specified.
12026
12027    SCOPED_ENUM_P is true if this is a scoped enumeration type.
12028
12029    if IS_NEW is not NULL, gets TRUE iff a new type is created.
12030
12031    Returns the type object, as yet incomplete.
12032    Also records info about it so that build_enumerator
12033    may be used to declare the individual values as they are read.  */
12034
12035 tree
12036 start_enum (tree name, tree enumtype, tree underlying_type,
12037             bool scoped_enum_p, bool *is_new)
12038 {
12039   tree prevtype = NULL_TREE;
12040   gcc_assert (TREE_CODE (name) == IDENTIFIER_NODE);
12041
12042   if (is_new)
12043     *is_new = false;
12044   /* [C++0x dcl.enum]p5:
12045
12046     If not explicitly specified, the underlying type of a scoped
12047     enumeration type is int.  */
12048   if (!underlying_type && scoped_enum_p)
12049     underlying_type = integer_type_node;
12050
12051   if (underlying_type)
12052     underlying_type = cv_unqualified (underlying_type);
12053
12054   /* If this is the real definition for a previous forward reference,
12055      fill in the contents in the same object that used to be the
12056      forward reference.  */
12057   if (!enumtype)
12058     enumtype = lookup_and_check_tag (enum_type, name,
12059                                      /*tag_scope=*/ts_current,
12060                                      /*template_header_p=*/false);
12061
12062   /* In case of a template_decl, the only check that should be deferred
12063      to instantiation time is the comparison of underlying types.  */
12064   if (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE)
12065     {
12066       if (scoped_enum_p != SCOPED_ENUM_P (enumtype))
12067         {
12068           error_at (input_location, "scoped/unscoped mismatch "
12069                     "in enum %q#T", enumtype);
12070           error_at (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
12071                     "previous definition here");
12072           enumtype = error_mark_node;
12073         }
12074       else if (ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) != !! underlying_type)
12075         {
12076           error_at (input_location, "underlying type mismatch "
12077                     "in enum %q#T", enumtype);
12078           error_at (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
12079                     "previous definition here");
12080           enumtype = error_mark_node;
12081         }
12082       else if (underlying_type && ENUM_UNDERLYING_TYPE (enumtype)
12083                && !dependent_type_p (underlying_type)
12084                && !dependent_type_p (ENUM_UNDERLYING_TYPE (enumtype))
12085                && !same_type_p (underlying_type,
12086                                 ENUM_UNDERLYING_TYPE (enumtype)))
12087         {
12088           error_at (input_location, "different underlying type "
12089                     "in enum %q#T", enumtype);
12090           error_at (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
12091                     "previous definition here");
12092           underlying_type = NULL_TREE;
12093         }
12094     }
12095
12096   if (!enumtype || TREE_CODE (enumtype) != ENUMERAL_TYPE
12097       || processing_template_decl)
12098     {
12099       /* In case of error, make a dummy enum to allow parsing to
12100          continue.  */
12101       if (enumtype == error_mark_node)
12102         {
12103           name = make_anon_name ();
12104           enumtype = NULL_TREE;
12105         }
12106
12107       /* enumtype may be an ENUMERAL_TYPE if this is a redefinition
12108          of an opaque enum, or an opaque enum of an already defined
12109          enumeration (C++0x only).
12110          In any other case, it'll be NULL_TREE. */
12111       if (!enumtype)
12112         {
12113           if (is_new)
12114             *is_new = true;
12115         }
12116       prevtype = enumtype;
12117
12118       /* Do not push the decl more than once, unless we need to
12119          compare underlying types at instantiation time */
12120       if (!enumtype
12121           || TREE_CODE (enumtype) != ENUMERAL_TYPE
12122           || (underlying_type
12123               && dependent_type_p (underlying_type))
12124           || (ENUM_UNDERLYING_TYPE (enumtype)
12125               && dependent_type_p (ENUM_UNDERLYING_TYPE (enumtype))))
12126         {
12127           enumtype = cxx_make_type (ENUMERAL_TYPE);
12128           enumtype = pushtag (name, enumtype, /*tag_scope=*/ts_current);
12129         }
12130       else
12131           enumtype = xref_tag (enum_type, name, /*tag_scope=*/ts_current,
12132                                false);
12133
12134       if (enumtype == error_mark_node)
12135         return error_mark_node;
12136
12137       /* The enum is considered opaque until the opening '{' of the
12138          enumerator list.  */
12139       SET_OPAQUE_ENUM_P (enumtype, true);
12140       ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) = !! underlying_type;
12141     }
12142
12143   SET_SCOPED_ENUM_P (enumtype, scoped_enum_p);
12144
12145   if (underlying_type)
12146     {
12147       if (CP_INTEGRAL_TYPE_P (underlying_type))
12148         {
12149           copy_type_enum (enumtype, underlying_type);
12150           ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
12151         }
12152       else if (dependent_type_p (underlying_type))
12153         ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
12154       else
12155         error ("underlying type %<%T%> of %<%T%> must be an integral type", 
12156                underlying_type, enumtype);
12157     }
12158
12159   /* If into a template class, the returned enum is always the first
12160      declaration (opaque or not) seen. This way all the references to
12161      this type will be to the same declaration. The following ones are used
12162      only to check for definition errors.  */
12163   if (prevtype && processing_template_decl)
12164     return prevtype;
12165   else
12166     return enumtype;
12167 }
12168
12169 /* After processing and defining all the values of an enumeration type,
12170    install their decls in the enumeration type.
12171    ENUMTYPE is the type object.  */
12172
12173 void
12174 finish_enum_value_list (tree enumtype)
12175 {
12176   tree values;
12177   tree underlying_type;
12178   tree decl;
12179   tree value;
12180   tree minnode, maxnode;
12181   tree t;
12182
12183   bool fixed_underlying_type_p 
12184     = ENUM_UNDERLYING_TYPE (enumtype) != NULL_TREE;
12185
12186   /* We built up the VALUES in reverse order.  */
12187   TYPE_VALUES (enumtype) = nreverse (TYPE_VALUES (enumtype));
12188
12189   /* For an enum defined in a template, just set the type of the values;
12190      all further processing is postponed until the template is
12191      instantiated.  We need to set the type so that tsubst of a CONST_DECL
12192      works.  */
12193   if (processing_template_decl)
12194     {
12195       for (values = TYPE_VALUES (enumtype);
12196            values;
12197            values = TREE_CHAIN (values))
12198         TREE_TYPE (TREE_VALUE (values)) = enumtype;
12199       return;
12200     }
12201
12202   /* Determine the minimum and maximum values of the enumerators.  */
12203   if (TYPE_VALUES (enumtype))
12204     {
12205       minnode = maxnode = NULL_TREE;
12206
12207       for (values = TYPE_VALUES (enumtype);
12208            values;
12209            values = TREE_CHAIN (values))
12210         {
12211           decl = TREE_VALUE (values);
12212
12213           /* [dcl.enum]: Following the closing brace of an enum-specifier,
12214              each enumerator has the type of its enumeration.  Prior to the
12215              closing brace, the type of each enumerator is the type of its
12216              initializing value.  */
12217           TREE_TYPE (decl) = enumtype;
12218
12219           /* Update the minimum and maximum values, if appropriate.  */
12220           value = DECL_INITIAL (decl);
12221           if (value == error_mark_node)
12222             value = integer_zero_node;
12223           /* Figure out what the minimum and maximum values of the
12224              enumerators are.  */
12225           if (!minnode)
12226             minnode = maxnode = value;
12227           else if (tree_int_cst_lt (maxnode, value))
12228             maxnode = value;
12229           else if (tree_int_cst_lt (value, minnode))
12230             minnode = value;
12231         }
12232     }
12233   else
12234     /* [dcl.enum]
12235
12236        If the enumerator-list is empty, the underlying type is as if
12237        the enumeration had a single enumerator with value 0.  */
12238     minnode = maxnode = integer_zero_node;
12239
12240   if (!fixed_underlying_type_p)
12241     {
12242       /* Compute the number of bits require to represent all values of the
12243          enumeration.  We must do this before the type of MINNODE and
12244          MAXNODE are transformed, since tree_int_cst_min_precision relies
12245          on the TREE_TYPE of the value it is passed.  */
12246       bool unsignedp = tree_int_cst_sgn (minnode) >= 0;
12247       int lowprec = tree_int_cst_min_precision (minnode, unsignedp);
12248       int highprec = tree_int_cst_min_precision (maxnode, unsignedp);
12249       int precision = MAX (lowprec, highprec);
12250       unsigned int itk;
12251       bool use_short_enum;
12252
12253       /* Determine the underlying type of the enumeration.
12254
12255          [dcl.enum]
12256
12257          The underlying type of an enumeration is an integral type that
12258          can represent all the enumerator values defined in the
12259          enumeration.  It is implementation-defined which integral type is
12260          used as the underlying type for an enumeration except that the
12261          underlying type shall not be larger than int unless the value of
12262          an enumerator cannot fit in an int or unsigned int.
12263
12264          We use "int" or an "unsigned int" as the underlying type, even if
12265          a smaller integral type would work, unless the user has
12266          explicitly requested that we use the smallest possible type.  The
12267          user can request that for all enumerations with a command line
12268          flag, or for just one enumeration with an attribute.  */
12269
12270       use_short_enum = flag_short_enums
12271         || lookup_attribute ("packed", TYPE_ATTRIBUTES (enumtype));
12272
12273       for (itk = (use_short_enum ? itk_char : itk_int);
12274            itk != itk_none;
12275            itk++)
12276         {
12277           underlying_type = integer_types[itk];
12278           if (underlying_type != NULL_TREE
12279               && TYPE_PRECISION (underlying_type) >= precision
12280               && TYPE_UNSIGNED (underlying_type) == unsignedp)
12281             break;
12282         }
12283       if (itk == itk_none)
12284         {
12285           /* DR 377
12286
12287              IF no integral type can represent all the enumerator values, the
12288              enumeration is ill-formed.  */
12289           error ("no integral type can represent all of the enumerator values "
12290                  "for %qT", enumtype);
12291           precision = TYPE_PRECISION (long_long_integer_type_node);
12292           underlying_type = integer_types[itk_unsigned_long_long];
12293         }
12294
12295       /* [dcl.enum]
12296
12297          The value of sizeof() applied to an enumeration type, an object
12298          of an enumeration type, or an enumerator, is the value of sizeof()
12299          applied to the underlying type.  */
12300       copy_type_enum (enumtype, underlying_type);
12301
12302       /* Compute the minimum and maximum values for the type.
12303
12304          [dcl.enum]
12305
12306          For an enumeration where emin is the smallest enumerator and emax
12307          is the largest, the values of the enumeration are the values of the
12308          underlying type in the range bmin to bmax, where bmin and bmax are,
12309          respectively, the smallest and largest values of the smallest bit-
12310          field that can store emin and emax.  */
12311
12312       /* The middle-end currently assumes that types with TYPE_PRECISION
12313          narrower than their underlying type are suitably zero or sign
12314          extended to fill their mode.  Similarly, it assumes that the front
12315          end assures that a value of a particular type must be within
12316          TYPE_MIN_VALUE and TYPE_MAX_VALUE.
12317
12318          We used to set these fields based on bmin and bmax, but that led
12319          to invalid assumptions like optimizing away bounds checking.  So
12320          now we just set the TYPE_PRECISION, TYPE_MIN_VALUE, and
12321          TYPE_MAX_VALUE to the values for the mode above and only restrict
12322          the ENUM_UNDERLYING_TYPE for the benefit of diagnostics.  */
12323       ENUM_UNDERLYING_TYPE (enumtype)
12324         = build_distinct_type_copy (underlying_type);
12325       TYPE_PRECISION (ENUM_UNDERLYING_TYPE (enumtype)) = precision;
12326       set_min_and_max_values_for_integral_type
12327         (ENUM_UNDERLYING_TYPE (enumtype), precision, unsignedp);
12328
12329       /* If -fstrict-enums, still constrain TYPE_MIN/MAX_VALUE.  */
12330       if (flag_strict_enums)
12331         set_min_and_max_values_for_integral_type (enumtype, precision,
12332                                                   unsignedp);
12333     }
12334   else
12335     underlying_type = ENUM_UNDERLYING_TYPE (enumtype);
12336
12337   /* Convert each of the enumerators to the type of the underlying
12338      type of the enumeration.  */
12339   for (values = TYPE_VALUES (enumtype); values; values = TREE_CHAIN (values))
12340     {
12341       location_t saved_location;
12342
12343       decl = TREE_VALUE (values);
12344       saved_location = input_location;
12345       input_location = DECL_SOURCE_LOCATION (decl);
12346       if (fixed_underlying_type_p)
12347         /* If the enumeration type has a fixed underlying type, we
12348            already checked all of the enumerator values.  */
12349         value = DECL_INITIAL (decl);
12350       else
12351         value = perform_implicit_conversion (underlying_type,
12352                                              DECL_INITIAL (decl),
12353                                              tf_warning_or_error);
12354       input_location = saved_location;
12355
12356       /* Do not clobber shared ints.  */
12357       value = copy_node (value);
12358
12359       TREE_TYPE (value) = enumtype;
12360       DECL_INITIAL (decl) = value;
12361     }
12362
12363   /* Fix up all variant types of this enum type.  */
12364   for (t = TYPE_MAIN_VARIANT (enumtype); t; t = TYPE_NEXT_VARIANT (t))
12365     TYPE_VALUES (t) = TYPE_VALUES (enumtype);
12366
12367   if (at_class_scope_p ()
12368       && COMPLETE_TYPE_P (current_class_type)
12369       && UNSCOPED_ENUM_P (enumtype))
12370     insert_late_enum_def_into_classtype_sorted_fields (enumtype,
12371                                                        current_class_type);
12372
12373   /* Finish debugging output for this type.  */
12374   rest_of_type_compilation (enumtype, namespace_bindings_p ());
12375 }
12376
12377 /* Finishes the enum type. This is called only the first time an
12378    enumeration is seen, be it opaque or odinary.
12379    ENUMTYPE is the type object.  */
12380
12381 void
12382 finish_enum (tree enumtype)
12383 {
12384   if (processing_template_decl)
12385     {
12386       if (at_function_scope_p ())
12387         add_stmt (build_min (TAG_DEFN, enumtype));
12388       return;
12389     }
12390
12391   /* If this is a forward declaration, there should not be any variants,
12392      though we can get a variant in the middle of an enum-specifier with
12393      wacky code like 'enum E { e = sizeof(const E*) };'  */
12394   gcc_assert (enumtype == TYPE_MAIN_VARIANT (enumtype)
12395               && (TYPE_VALUES (enumtype)
12396                   || !TYPE_NEXT_VARIANT (enumtype)));
12397 }
12398
12399 /* Build and install a CONST_DECL for an enumeration constant of the
12400    enumeration type ENUMTYPE whose NAME and VALUE (if any) are provided.
12401    LOC is the location of NAME.
12402    Assignment of sequential values by default is handled here.  */
12403
12404 void
12405 build_enumerator (tree name, tree value, tree enumtype, location_t loc)
12406 {
12407   tree decl;
12408   tree context;
12409   tree type;
12410
12411   /* If the VALUE was erroneous, pretend it wasn't there; that will
12412      result in the enum being assigned the next value in sequence.  */
12413   if (value == error_mark_node)
12414     value = NULL_TREE;
12415
12416   /* Remove no-op casts from the value.  */
12417   if (value)
12418     STRIP_TYPE_NOPS (value);
12419
12420   if (! processing_template_decl)
12421     {
12422       /* Validate and default VALUE.  */
12423       if (value != NULL_TREE)
12424         {
12425           value = cxx_constant_value (value);
12426
12427           if (TREE_CODE (value) != INTEGER_CST
12428               || ! INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (value)))
12429             {
12430               error ("enumerator value for %qD is not an integer constant",
12431                      name);
12432               value = NULL_TREE;
12433             }
12434         }
12435
12436       /* Default based on previous value.  */
12437       if (value == NULL_TREE)
12438         {
12439           if (TYPE_VALUES (enumtype))
12440             {
12441               HOST_WIDE_INT hi;
12442               unsigned HOST_WIDE_INT lo;
12443               tree prev_value;
12444               bool overflowed;
12445
12446               /* C++03 7.2/4: If no initializer is specified for the first
12447                  enumerator, the type is an unspecified integral
12448                  type. Otherwise the type is the same as the type of the
12449                  initializing value of the preceding enumerator unless the
12450                  incremented value is not representable in that type, in
12451                  which case the type is an unspecified integral type
12452                  sufficient to contain the incremented value.  */
12453               prev_value = DECL_INITIAL (TREE_VALUE (TYPE_VALUES (enumtype)));
12454               if (error_operand_p (prev_value))
12455                 value = error_mark_node;
12456               else
12457                 {
12458                   overflowed = add_double (TREE_INT_CST_LOW (prev_value),
12459                                            TREE_INT_CST_HIGH (prev_value),
12460                                            1, 0, &lo, &hi);
12461                   if (!overflowed)
12462                     {
12463                       double_int di;
12464                       tree type = TREE_TYPE (prev_value);
12465                       bool pos = (TYPE_UNSIGNED (type) || hi >= 0);
12466                       di.low = lo; di.high = hi;
12467                       if (!double_int_fits_to_tree_p (type, di))
12468                         {
12469                           unsigned int itk;
12470                           for (itk = itk_int; itk != itk_none; itk++)
12471                             {
12472                               type = integer_types[itk];
12473                               if (type != NULL_TREE
12474                                   && (pos || !TYPE_UNSIGNED (type))
12475                                   && double_int_fits_to_tree_p (type, di))
12476                                 break;
12477                             }
12478                           if (type && cxx_dialect < cxx0x
12479                               && itk > itk_unsigned_long)
12480                             pedwarn (input_location, OPT_Wlong_long, pos ? "\
12481 incremented enumerator value is too large for %<unsigned long%>" :  "\
12482 incremented enumerator value is too large for %<long%>");
12483                         }
12484                       if (type == NULL_TREE)
12485                         overflowed = true;
12486                       else
12487                         value = double_int_to_tree (type, di);
12488                     }
12489
12490                   if (overflowed)
12491                     {
12492                       error ("overflow in enumeration values at %qD", name);
12493                       value = error_mark_node;
12494                     }
12495                 }
12496             }
12497           else
12498             value = integer_zero_node;
12499         }
12500
12501       /* Remove no-op casts from the value.  */
12502       STRIP_TYPE_NOPS (value);
12503
12504       /* If the underlying type of the enum is fixed, check whether
12505          the enumerator values fits in the underlying type.  If it
12506          does not fit, the program is ill-formed [C++0x dcl.enum].  */
12507       if (ENUM_UNDERLYING_TYPE (enumtype)
12508           && value
12509           && TREE_CODE (value) == INTEGER_CST
12510           && !int_fits_type_p (value, ENUM_UNDERLYING_TYPE (enumtype)))
12511         {
12512           error ("enumerator value %E is too large for underlying type %<%T%>",
12513                  value, ENUM_UNDERLYING_TYPE (enumtype));
12514
12515           /* Silently convert the value so that we can continue.  */
12516           value = perform_implicit_conversion (ENUM_UNDERLYING_TYPE (enumtype),
12517                                                value, tf_none);
12518         }
12519     }
12520
12521   /* C++ associates enums with global, function, or class declarations.  */
12522   context = current_scope ();
12523
12524   /* Build the actual enumeration constant.  Note that the enumeration
12525      constants have the underlying type of the enum (if it is fixed)
12526      or the type of their initializer (if the underlying type of the
12527      enum is not fixed):
12528
12529       [ C++0x dcl.enum ]
12530
12531         If the underlying type is fixed, the type of each enumerator
12532         prior to the closing brace is the underlying type; if the
12533         initializing value of an enumerator cannot be represented by
12534         the underlying type, the program is ill-formed. If the
12535         underlying type is not fixed, the type of each enumerator is
12536         the type of its initializing value.
12537
12538     If the underlying type is not fixed, it will be computed by
12539     finish_enum and we will reset the type of this enumerator.  Of
12540     course, if we're processing a template, there may be no value.  */
12541   type = value ? TREE_TYPE (value) : NULL_TREE;
12542
12543   decl = build_decl (loc, CONST_DECL, name, type);
12544   
12545   DECL_CONTEXT (decl) = enumtype;
12546   TREE_CONSTANT (decl) = 1;
12547   TREE_READONLY (decl) = 1;
12548   DECL_INITIAL (decl) = value;
12549
12550   if (context && context == current_class_type && !SCOPED_ENUM_P (enumtype))
12551     /* In something like `struct S { enum E { i = 7 }; };' we put `i'
12552        on the TYPE_FIELDS list for `S'.  (That's so that you can say
12553        things like `S::i' later.)  */
12554     finish_member_declaration (decl);
12555   else
12556     pushdecl (decl);
12557
12558   /* Add this enumeration constant to the list for this type.  */
12559   TYPE_VALUES (enumtype) = tree_cons (name, decl, TYPE_VALUES (enumtype));
12560 }
12561
12562 /* Look for an enumerator with the given NAME within the enumeration
12563    type ENUMTYPE.  This routine is used primarily for qualified name
12564    lookup into an enumerator in C++0x, e.g.,
12565
12566      enum class Color { Red, Green, Blue };
12567
12568      Color color = Color::Red;
12569
12570    Returns the value corresponding to the enumerator, or
12571    NULL_TREE if no such enumerator was found.  */
12572 tree
12573 lookup_enumerator (tree enumtype, tree name)
12574 {
12575   tree e;
12576   gcc_assert (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE);
12577
12578   e = purpose_member (name, TYPE_VALUES (enumtype));
12579   return e? TREE_VALUE (e) : NULL_TREE;
12580 }
12581
12582 \f
12583 /* We're defining DECL.  Make sure that its type is OK.  */
12584
12585 static void
12586 check_function_type (tree decl, tree current_function_parms)
12587 {
12588   tree fntype = TREE_TYPE (decl);
12589   tree return_type = complete_type (TREE_TYPE (fntype));
12590
12591   /* In a function definition, arg types must be complete.  */
12592   require_complete_types_for_parms (current_function_parms);
12593
12594   if (dependent_type_p (return_type)
12595       || type_uses_auto (return_type))
12596     return;
12597   if (!COMPLETE_OR_VOID_TYPE_P (return_type)
12598       || (TYPE_FOR_JAVA (return_type) && MAYBE_CLASS_TYPE_P (return_type)))
12599     {
12600       tree args = TYPE_ARG_TYPES (fntype);
12601
12602       if (!COMPLETE_OR_VOID_TYPE_P (return_type))
12603         error ("return type %q#T is incomplete", return_type);
12604       else
12605         error ("return type has Java class type %q#T", return_type);
12606
12607       /* Make it return void instead.  */
12608       if (TREE_CODE (fntype) == METHOD_TYPE)
12609         fntype = build_method_type_directly (TREE_TYPE (TREE_VALUE (args)),
12610                                              void_type_node,
12611                                              TREE_CHAIN (args));
12612       else
12613         fntype = build_function_type (void_type_node, args);
12614       fntype
12615         = build_exception_variant (fntype,
12616                                    TYPE_RAISES_EXCEPTIONS (TREE_TYPE (decl)));
12617       fntype = (cp_build_type_attribute_variant
12618                 (fntype, TYPE_ATTRIBUTES (TREE_TYPE (decl))));
12619       TREE_TYPE (decl) = fntype;
12620     }
12621   else
12622     abstract_virtuals_error (decl, TREE_TYPE (fntype));
12623 }
12624
12625 /* Create the FUNCTION_DECL for a function definition.
12626    DECLSPECS and DECLARATOR are the parts of the declaration;
12627    they describe the function's name and the type it returns,
12628    but twisted together in a fashion that parallels the syntax of C.
12629
12630    FLAGS is a bitwise or of SF_PRE_PARSED (indicating that the
12631    DECLARATOR is really the DECL for the function we are about to
12632    process and that DECLSPECS should be ignored), SF_INCLASS_INLINE
12633    indicating that the function is an inline defined in-class.
12634
12635    This function creates a binding context for the function body
12636    as well as setting up the FUNCTION_DECL in current_function_decl.
12637
12638    For C++, we must first check whether that datum makes any sense.
12639    For example, "class A local_a(1,2);" means that variable local_a
12640    is an aggregate of type A, which should have a constructor
12641    applied to it with the argument list [1, 2].
12642
12643    On entry, DECL_INITIAL (decl1) should be NULL_TREE or error_mark_node,
12644    or may be a BLOCK if the function has been defined previously
12645    in this translation unit.  On exit, DECL_INITIAL (decl1) will be
12646    error_mark_node if the function has never been defined, or
12647    a BLOCK if the function has been defined somewhere.  */
12648
12649 void
12650 start_preparsed_function (tree decl1, tree attrs, int flags)
12651 {
12652   tree ctype = NULL_TREE;
12653   tree fntype;
12654   tree restype;
12655   int doing_friend = 0;
12656   cp_binding_level *bl;
12657   tree current_function_parms;
12658   struct c_fileinfo *finfo
12659     = get_fileinfo (LOCATION_FILE (DECL_SOURCE_LOCATION (decl1)));
12660   bool honor_interface;
12661
12662   /* Sanity check.  */
12663   gcc_assert (TREE_CODE (TREE_VALUE (void_list_node)) == VOID_TYPE);
12664   gcc_assert (TREE_CHAIN (void_list_node) == NULL_TREE);
12665
12666   fntype = TREE_TYPE (decl1);
12667   if (TREE_CODE (fntype) == METHOD_TYPE)
12668     ctype = TYPE_METHOD_BASETYPE (fntype);
12669
12670   /* ISO C++ 11.4/5.  A friend function defined in a class is in
12671      the (lexical) scope of the class in which it is defined.  */
12672   if (!ctype && DECL_FRIEND_P (decl1))
12673     {
12674       ctype = DECL_FRIEND_CONTEXT (decl1);
12675
12676       /* CTYPE could be null here if we're dealing with a template;
12677          for example, `inline friend float foo()' inside a template
12678          will have no CTYPE set.  */
12679       if (ctype && TREE_CODE (ctype) != RECORD_TYPE)
12680         ctype = NULL_TREE;
12681       else
12682         doing_friend = 1;
12683     }
12684
12685   if (DECL_DECLARED_INLINE_P (decl1)
12686       && lookup_attribute ("noinline", attrs))
12687     warning (0, "inline function %q+D given attribute noinline", decl1);
12688
12689   /* Handle gnu_inline attribute.  */
12690   if (GNU_INLINE_P (decl1))
12691     {
12692       DECL_EXTERNAL (decl1) = 1;
12693       DECL_NOT_REALLY_EXTERN (decl1) = 0;
12694       DECL_INTERFACE_KNOWN (decl1) = 1;
12695       DECL_DISREGARD_INLINE_LIMITS (decl1) = 1;
12696     }
12697
12698   if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl1))
12699     /* This is a constructor, we must ensure that any default args
12700        introduced by this definition are propagated to the clones
12701        now. The clones are used directly in overload resolution.  */
12702     adjust_clone_args (decl1);
12703
12704   /* Sometimes we don't notice that a function is a static member, and
12705      build a METHOD_TYPE for it.  Fix that up now.  */
12706   gcc_assert (!(ctype != NULL_TREE && DECL_STATIC_FUNCTION_P (decl1)
12707                 && TREE_CODE (TREE_TYPE (decl1)) == METHOD_TYPE));
12708
12709   /* Set up current_class_type, and enter the scope of the class, if
12710      appropriate.  */
12711   if (ctype)
12712     push_nested_class (ctype);
12713   else if (DECL_STATIC_FUNCTION_P (decl1))
12714     push_nested_class (DECL_CONTEXT (decl1));
12715
12716   /* Now that we have entered the scope of the class, we must restore
12717      the bindings for any template parameters surrounding DECL1, if it
12718      is an inline member template.  (Order is important; consider the
12719      case where a template parameter has the same name as a field of
12720      the class.)  It is not until after this point that
12721      PROCESSING_TEMPLATE_DECL is guaranteed to be set up correctly.  */
12722   if (flags & SF_INCLASS_INLINE)
12723     maybe_begin_member_template_processing (decl1);
12724
12725   /* Effective C++ rule 15.  */
12726   if (warn_ecpp
12727       && DECL_OVERLOADED_OPERATOR_P (decl1) == NOP_EXPR
12728       && TREE_CODE (TREE_TYPE (fntype)) == VOID_TYPE)
12729     warning (OPT_Weffc__, "%<operator=%> should return a reference to %<*this%>");
12730
12731   /* Make the init_value nonzero so pushdecl knows this is not tentative.
12732      error_mark_node is replaced below (in poplevel) with the BLOCK.  */
12733   if (!DECL_INITIAL (decl1))
12734     DECL_INITIAL (decl1) = error_mark_node;
12735
12736   /* This function exists in static storage.
12737      (This does not mean `static' in the C sense!)  */
12738   TREE_STATIC (decl1) = 1;
12739
12740   /* We must call push_template_decl after current_class_type is set
12741      up.  (If we are processing inline definitions after exiting a
12742      class scope, current_class_type will be NULL_TREE until set above
12743      by push_nested_class.)  */
12744   if (processing_template_decl)
12745     {
12746       /* FIXME: Handle error_mark_node more gracefully.  */
12747       tree newdecl1 = push_template_decl (decl1);
12748       if (newdecl1 != error_mark_node)
12749         decl1 = newdecl1;
12750     }
12751
12752   /* We are now in the scope of the function being defined.  */
12753   current_function_decl = decl1;
12754
12755   /* Save the parm names or decls from this function's declarator
12756      where store_parm_decls will find them.  */
12757   current_function_parms = DECL_ARGUMENTS (decl1);
12758
12759   /* Make sure the parameter and return types are reasonable.  When
12760      you declare a function, these types can be incomplete, but they
12761      must be complete when you define the function.  */
12762   check_function_type (decl1, current_function_parms);
12763
12764   /* Build the return declaration for the function.  */
12765   restype = TREE_TYPE (fntype);
12766
12767   if (DECL_RESULT (decl1) == NULL_TREE)
12768     {
12769       tree resdecl;
12770
12771       resdecl = build_decl (input_location, RESULT_DECL, 0, restype);
12772       DECL_ARTIFICIAL (resdecl) = 1;
12773       DECL_IGNORED_P (resdecl) = 1;
12774       DECL_RESULT (decl1) = resdecl;
12775
12776       cp_apply_type_quals_to_decl (cp_type_quals (restype), resdecl);
12777     }
12778
12779   /* Let the user know we're compiling this function.  */
12780   announce_function (decl1);
12781
12782   /* Record the decl so that the function name is defined.
12783      If we already have a decl for this name, and it is a FUNCTION_DECL,
12784      use the old decl.  */
12785   if (!processing_template_decl && !(flags & SF_PRE_PARSED))
12786     {
12787       /* A specialization is not used to guide overload resolution.  */
12788       if (!DECL_FUNCTION_MEMBER_P (decl1)
12789           && !(DECL_USE_TEMPLATE (decl1) &&
12790                PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl1))))
12791         {
12792           tree olddecl = pushdecl (decl1);
12793
12794           if (olddecl == error_mark_node)
12795             /* If something went wrong when registering the declaration,
12796                use DECL1; we have to have a FUNCTION_DECL to use when
12797                parsing the body of the function.  */
12798             ;
12799           else
12800             {
12801               /* Otherwise, OLDDECL is either a previous declaration
12802                  of the same function or DECL1 itself.  */
12803
12804               if (warn_missing_declarations
12805                   && olddecl == decl1
12806                   && !DECL_MAIN_P (decl1)
12807                   && TREE_PUBLIC (decl1)
12808                   && !DECL_DECLARED_INLINE_P (decl1))
12809                 {
12810                   tree context;
12811
12812                   /* Check whether DECL1 is in an anonymous
12813                      namespace.  */
12814                   for (context = DECL_CONTEXT (decl1);
12815                        context;
12816                        context = DECL_CONTEXT (context))
12817                     {
12818                       if (TREE_CODE (context) == NAMESPACE_DECL
12819                           && DECL_NAME (context) == NULL_TREE)
12820                         break;
12821                     }
12822
12823                   if (context == NULL)
12824                     warning (OPT_Wmissing_declarations,
12825                              "no previous declaration for %q+D", decl1);
12826                 }
12827
12828               decl1 = olddecl;
12829             }
12830         }
12831       else
12832         {
12833           /* We need to set the DECL_CONTEXT.  */
12834           if (!DECL_CONTEXT (decl1) && DECL_TEMPLATE_INFO (decl1))
12835             DECL_CONTEXT (decl1) = DECL_CONTEXT (DECL_TI_TEMPLATE (decl1));
12836         }
12837       fntype = TREE_TYPE (decl1);
12838
12839       /* If #pragma weak applies, mark the decl appropriately now.
12840          The pragma only applies to global functions.  Because
12841          determining whether or not the #pragma applies involves
12842          computing the mangled name for the declaration, we cannot
12843          apply the pragma until after we have merged this declaration
12844          with any previous declarations; if the original declaration
12845          has a linkage specification, that specification applies to
12846          the definition as well, and may affect the mangled name.  */
12847       if (DECL_FILE_SCOPE_P (decl1))
12848         maybe_apply_pragma_weak (decl1);
12849     }
12850
12851   /* Reset this in case the call to pushdecl changed it.  */
12852   current_function_decl = decl1;
12853
12854   gcc_assert (DECL_INITIAL (decl1));
12855
12856   /* This function may already have been parsed, in which case just
12857      return; our caller will skip over the body without parsing.  */
12858   if (DECL_INITIAL (decl1) != error_mark_node)
12859     return;
12860
12861   /* Initialize RTL machinery.  We cannot do this until
12862      CURRENT_FUNCTION_DECL and DECL_RESULT are set up.  We do this
12863      even when processing a template; this is how we get
12864      CFUN set up, and our per-function variables initialized.
12865      FIXME factor out the non-RTL stuff.  */
12866   bl = current_binding_level;
12867   allocate_struct_function (decl1, processing_template_decl);
12868
12869   /* Initialize the language data structures.  Whenever we start
12870      a new function, we destroy temporaries in the usual way.  */
12871   cfun->language = ggc_alloc_cleared_language_function ();
12872   current_stmt_tree ()->stmts_are_full_exprs_p = 1;
12873   current_binding_level = bl;
12874
12875   if (!processing_template_decl && type_uses_auto (restype))
12876     {
12877       FNDECL_USED_AUTO (decl1) = true;
12878       current_function_auto_return_pattern = restype;
12879     }
12880
12881   /* Start the statement-tree, start the tree now.  */
12882   DECL_SAVED_TREE (decl1) = push_stmt_list ();
12883
12884   /* If we are (erroneously) defining a function that we have already
12885      defined before, wipe out what we knew before.  */
12886   if (!DECL_PENDING_INLINE_P (decl1))
12887     DECL_SAVED_FUNCTION_DATA (decl1) = NULL;
12888
12889   if (ctype && !doing_friend && !DECL_STATIC_FUNCTION_P (decl1))
12890     {
12891       /* We know that this was set up by `grokclassfn'.  We do not
12892          wait until `store_parm_decls', since evil parse errors may
12893          never get us to that point.  Here we keep the consistency
12894          between `current_class_type' and `current_class_ptr'.  */
12895       tree t = DECL_ARGUMENTS (decl1);
12896
12897       gcc_assert (t != NULL_TREE && TREE_CODE (t) == PARM_DECL);
12898       gcc_assert (TREE_CODE (TREE_TYPE (t)) == POINTER_TYPE);
12899
12900       cp_function_chain->x_current_class_ref
12901         = cp_build_indirect_ref (t, RO_NULL, tf_warning_or_error);
12902       /* Set this second to avoid shortcut in cp_build_indirect_ref.  */
12903       cp_function_chain->x_current_class_ptr = t;
12904
12905       /* Constructors and destructors need to know whether they're "in
12906          charge" of initializing virtual base classes.  */
12907       t = DECL_CHAIN (t);
12908       if (DECL_HAS_IN_CHARGE_PARM_P (decl1))
12909         {
12910           current_in_charge_parm = t;
12911           t = DECL_CHAIN (t);
12912         }
12913       if (DECL_HAS_VTT_PARM_P (decl1))
12914         {
12915           gcc_assert (DECL_NAME (t) == vtt_parm_identifier);
12916           current_vtt_parm = t;
12917         }
12918     }
12919
12920   honor_interface = (!DECL_TEMPLATE_INSTANTIATION (decl1)
12921                      /* Implicitly-defined methods (like the
12922                         destructor for a class in which no destructor
12923                         is explicitly declared) must not be defined
12924                         until their definition is needed.  So, we
12925                         ignore interface specifications for
12926                         compiler-generated functions.  */
12927                      && !DECL_ARTIFICIAL (decl1));
12928
12929   if (processing_template_decl)
12930     /* Don't mess with interface flags.  */;
12931   else if (DECL_INTERFACE_KNOWN (decl1))
12932     {
12933       tree ctx = decl_function_context (decl1);
12934
12935       if (DECL_NOT_REALLY_EXTERN (decl1))
12936         DECL_EXTERNAL (decl1) = 0;
12937
12938       if (ctx != NULL_TREE && DECL_DECLARED_INLINE_P (ctx)
12939           && TREE_PUBLIC (ctx))
12940         /* This is a function in a local class in an extern inline
12941            function.  */
12942         comdat_linkage (decl1);
12943     }
12944   /* If this function belongs to an interface, it is public.
12945      If it belongs to someone else's interface, it is also external.
12946      This only affects inlines and template instantiations.  */
12947   else if (!finfo->interface_unknown && honor_interface)
12948     {
12949       if (DECL_DECLARED_INLINE_P (decl1)
12950           || DECL_TEMPLATE_INSTANTIATION (decl1))
12951         {
12952           DECL_EXTERNAL (decl1)
12953             = (finfo->interface_only
12954                || (DECL_DECLARED_INLINE_P (decl1)
12955                    && ! flag_implement_inlines
12956                    && !DECL_VINDEX (decl1)));
12957
12958           /* For WIN32 we also want to put these in linkonce sections.  */
12959           maybe_make_one_only (decl1);
12960         }
12961       else
12962         DECL_EXTERNAL (decl1) = 0;
12963       DECL_INTERFACE_KNOWN (decl1) = 1;
12964       /* If this function is in an interface implemented in this file,
12965          make sure that the back end knows to emit this function
12966          here.  */
12967       if (!DECL_EXTERNAL (decl1))
12968         mark_needed (decl1);
12969     }
12970   else if (finfo->interface_unknown && finfo->interface_only
12971            && honor_interface)
12972     {
12973       /* If MULTIPLE_SYMBOL_SPACES is defined and we saw a #pragma
12974          interface, we will have both finfo->interface_unknown and
12975          finfo->interface_only set.  In that case, we don't want to
12976          use the normal heuristics because someone will supply a
12977          #pragma implementation elsewhere, and deducing it here would
12978          produce a conflict.  */
12979       comdat_linkage (decl1);
12980       DECL_EXTERNAL (decl1) = 0;
12981       DECL_INTERFACE_KNOWN (decl1) = 1;
12982       DECL_DEFER_OUTPUT (decl1) = 1;
12983     }
12984   else
12985     {
12986       /* This is a definition, not a reference.
12987          So clear DECL_EXTERNAL, unless this is a GNU extern inline.  */
12988       if (!GNU_INLINE_P (decl1))
12989         DECL_EXTERNAL (decl1) = 0;
12990
12991       if ((DECL_DECLARED_INLINE_P (decl1)
12992            || DECL_TEMPLATE_INSTANTIATION (decl1))
12993           && ! DECL_INTERFACE_KNOWN (decl1))
12994         DECL_DEFER_OUTPUT (decl1) = 1;
12995       else
12996         DECL_INTERFACE_KNOWN (decl1) = 1;
12997     }
12998
12999   /* Determine the ELF visibility attribute for the function.  We must not
13000      do this before calling "pushdecl", as we must allow "duplicate_decls"
13001      to merge any attributes appropriately.  We also need to wait until
13002      linkage is set.  */
13003   if (!DECL_CLONED_FUNCTION_P (decl1))
13004     determine_visibility (decl1);
13005
13006   begin_scope (sk_function_parms, decl1);
13007
13008   ++function_depth;
13009
13010   if (DECL_DESTRUCTOR_P (decl1)
13011       || (DECL_CONSTRUCTOR_P (decl1)
13012           && targetm.cxx.cdtor_returns_this ()))
13013     {
13014       cdtor_label = build_decl (input_location, 
13015                                 LABEL_DECL, NULL_TREE, NULL_TREE);
13016       DECL_CONTEXT (cdtor_label) = current_function_decl;
13017     }
13018
13019   start_fname_decls ();
13020
13021   store_parm_decls (current_function_parms);
13022 }
13023
13024
13025 /* Like start_preparsed_function, except that instead of a
13026    FUNCTION_DECL, this function takes DECLSPECS and DECLARATOR.
13027
13028    Returns 1 on success.  If the DECLARATOR is not suitable for a function
13029    (it defines a datum instead), we return 0, which tells
13030    yyparse to report a parse error.  */
13031
13032 int
13033 start_function (cp_decl_specifier_seq *declspecs,
13034                 const cp_declarator *declarator,
13035                 tree attrs)
13036 {
13037   tree decl1;
13038
13039   decl1 = grokdeclarator (declarator, declspecs, FUNCDEF, 1, &attrs);
13040   if (decl1 == error_mark_node)
13041     return 0;
13042   /* If the declarator is not suitable for a function definition,
13043      cause a syntax error.  */
13044   if (decl1 == NULL_TREE || TREE_CODE (decl1) != FUNCTION_DECL)
13045     {
13046       error ("invalid function declaration");
13047       return 0;
13048     }
13049
13050   if (DECL_MAIN_P (decl1))
13051     /* main must return int.  grokfndecl should have corrected it
13052        (and issued a diagnostic) if the user got it wrong.  */
13053     gcc_assert (same_type_p (TREE_TYPE (TREE_TYPE (decl1)),
13054                              integer_type_node));
13055
13056   start_preparsed_function (decl1, attrs, /*flags=*/SF_DEFAULT);
13057
13058   return 1;
13059 }
13060 \f
13061 /* Returns true iff an EH_SPEC_BLOCK should be created in the body of
13062    FN.  */
13063
13064 static bool
13065 use_eh_spec_block (tree fn)
13066 {
13067   return (flag_exceptions && flag_enforce_eh_specs
13068           && !processing_template_decl
13069           && !type_throw_all_p (TREE_TYPE (fn))
13070           /* We insert the EH_SPEC_BLOCK only in the original
13071              function; then, it is copied automatically to the
13072              clones.  */
13073           && !DECL_CLONED_FUNCTION_P (fn)
13074           /* Implicitly-generated constructors and destructors have
13075              exception specifications.  However, those specifications
13076              are the union of the possible exceptions specified by the
13077              constructors/destructors for bases and members, so no
13078              unallowed exception will ever reach this function.  By
13079              not creating the EH_SPEC_BLOCK we save a little memory,
13080              and we avoid spurious warnings about unreachable
13081              code.  */
13082           && !DECL_DEFAULTED_FN (fn));
13083 }
13084
13085 /* Store the parameter declarations into the current function declaration.
13086    This is called after parsing the parameter declarations, before
13087    digesting the body of the function.
13088
13089    Also install to binding contour return value identifier, if any.  */
13090
13091 static void
13092 store_parm_decls (tree current_function_parms)
13093 {
13094   tree fndecl = current_function_decl;
13095   tree parm;
13096
13097   /* This is a chain of any other decls that came in among the parm
13098      declarations.  If a parm is declared with  enum {foo, bar} x;
13099      then CONST_DECLs for foo and bar are put here.  */
13100   tree nonparms = NULL_TREE;
13101
13102   if (current_function_parms)
13103     {
13104       /* This case is when the function was defined with an ANSI prototype.
13105          The parms already have decls, so we need not do anything here
13106          except record them as in effect
13107          and complain if any redundant old-style parm decls were written.  */
13108
13109       tree specparms = current_function_parms;
13110       tree next;
13111
13112       /* Must clear this because it might contain TYPE_DECLs declared
13113              at class level.  */
13114       current_binding_level->names = NULL;
13115
13116       /* If we're doing semantic analysis, then we'll call pushdecl
13117              for each of these.  We must do them in reverse order so that
13118              they end in the correct forward order.  */
13119       specparms = nreverse (specparms);
13120
13121       for (parm = specparms; parm; parm = next)
13122         {
13123           next = DECL_CHAIN (parm);
13124           if (TREE_CODE (parm) == PARM_DECL)
13125             {
13126               if (DECL_NAME (parm) == NULL_TREE
13127                   || TREE_CODE (parm) != VOID_TYPE)
13128                 pushdecl (parm);
13129               else
13130                 error ("parameter %qD declared void", parm);
13131             }
13132           else
13133             {
13134               /* If we find an enum constant or a type tag,
13135                  put it aside for the moment.  */
13136               TREE_CHAIN (parm) = NULL_TREE;
13137               nonparms = chainon (nonparms, parm);
13138             }
13139         }
13140
13141       /* Get the decls in their original chain order and record in the
13142          function.  This is all and only the PARM_DECLs that were
13143          pushed into scope by the loop above.  */
13144       DECL_ARGUMENTS (fndecl) = getdecls ();
13145     }
13146   else
13147     DECL_ARGUMENTS (fndecl) = NULL_TREE;
13148
13149   /* Now store the final chain of decls for the arguments
13150      as the decl-chain of the current lexical scope.
13151      Put the enumerators in as well, at the front so that
13152      DECL_ARGUMENTS is not modified.  */
13153   current_binding_level->names = chainon (nonparms, DECL_ARGUMENTS (fndecl));
13154
13155   if (use_eh_spec_block (current_function_decl))
13156     current_eh_spec_block = begin_eh_spec_block ();
13157 }
13158
13159 \f
13160 /* We have finished doing semantic analysis on DECL, but have not yet
13161    generated RTL for its body.  Save away our current state, so that
13162    when we want to generate RTL later we know what to do.  */
13163
13164 static void
13165 save_function_data (tree decl)
13166 {
13167   struct language_function *f;
13168
13169   /* Save the language-specific per-function data so that we can
13170      get it back when we really expand this function.  */
13171   gcc_assert (!DECL_PENDING_INLINE_P (decl));
13172
13173   /* Make a copy.  */
13174   f = ggc_alloc_language_function ();
13175   memcpy (f, cp_function_chain, sizeof (struct language_function));
13176   DECL_SAVED_FUNCTION_DATA (decl) = f;
13177
13178   /* Clear out the bits we don't need.  */
13179   f->base.x_stmt_tree.x_cur_stmt_list = NULL;
13180   f->bindings = NULL;
13181   f->x_local_names = NULL;
13182   f->base.local_typedefs = NULL;
13183 }
13184
13185
13186 /* Set the return value of the constructor (if present).  */
13187
13188 static void
13189 finish_constructor_body (void)
13190 {
13191   tree val;
13192   tree exprstmt;
13193
13194   if (targetm.cxx.cdtor_returns_this ()
13195       && (! TYPE_FOR_JAVA (current_class_type)))
13196     {
13197       /* Any return from a constructor will end up here.  */
13198       add_stmt (build_stmt (input_location, LABEL_EXPR, cdtor_label));
13199
13200       val = DECL_ARGUMENTS (current_function_decl);
13201       val = build2 (MODIFY_EXPR, TREE_TYPE (val),
13202                     DECL_RESULT (current_function_decl), val);
13203       /* Return the address of the object.  */
13204       exprstmt = build_stmt (input_location, RETURN_EXPR, val);
13205       add_stmt (exprstmt);
13206     }
13207 }
13208
13209 /* Do all the processing for the beginning of a destructor; set up the
13210    vtable pointers and cleanups for bases and members.  */
13211
13212 static void
13213 begin_destructor_body (void)
13214 {
13215   tree compound_stmt;
13216
13217   /* If the CURRENT_CLASS_TYPE is incomplete, we will have already
13218      issued an error message.  We still want to try to process the
13219      body of the function, but initialize_vtbl_ptrs will crash if
13220      TYPE_BINFO is NULL.  */
13221   if (COMPLETE_TYPE_P (current_class_type))
13222     {
13223       compound_stmt = begin_compound_stmt (0);
13224       /* Make all virtual function table pointers in non-virtual base
13225          classes point to CURRENT_CLASS_TYPE's virtual function
13226          tables.  */
13227       initialize_vtbl_ptrs (current_class_ptr);
13228       finish_compound_stmt (compound_stmt);
13229
13230       /* And insert cleanups for our bases and members so that they
13231          will be properly destroyed if we throw.  */
13232       push_base_cleanups ();
13233     }
13234 }
13235
13236 /* At the end of every destructor we generate code to delete the object if
13237    necessary.  Do that now.  */
13238
13239 static void
13240 finish_destructor_body (void)
13241 {
13242   tree exprstmt;
13243
13244   /* Any return from a destructor will end up here; that way all base
13245      and member cleanups will be run when the function returns.  */
13246   add_stmt (build_stmt (input_location, LABEL_EXPR, cdtor_label));
13247
13248   /* In a virtual destructor, we must call delete.  */
13249   if (DECL_VIRTUAL_P (current_function_decl))
13250     {
13251       tree if_stmt;
13252       tree virtual_size = cxx_sizeof (current_class_type);
13253
13254       /* [class.dtor]
13255
13256       At the point of definition of a virtual destructor (including
13257       an implicit definition), non-placement operator delete shall
13258       be looked up in the scope of the destructor's class and if
13259       found shall be accessible and unambiguous.  */
13260       exprstmt = build_op_delete_call (DELETE_EXPR, current_class_ptr,
13261                                        virtual_size,
13262                                        /*global_p=*/false,
13263                                        /*placement=*/NULL_TREE,
13264                                        /*alloc_fn=*/NULL_TREE,
13265                                        tf_warning_or_error);
13266
13267       if_stmt = begin_if_stmt ();
13268       finish_if_stmt_cond (build2 (BIT_AND_EXPR, integer_type_node,
13269                                    current_in_charge_parm,
13270                                    integer_one_node),
13271                            if_stmt);
13272       finish_expr_stmt (exprstmt);
13273       finish_then_clause (if_stmt);
13274       finish_if_stmt (if_stmt);
13275     }
13276
13277   if (targetm.cxx.cdtor_returns_this ())
13278     {
13279       tree val;
13280
13281       val = DECL_ARGUMENTS (current_function_decl);
13282       val = build2 (MODIFY_EXPR, TREE_TYPE (val),
13283                     DECL_RESULT (current_function_decl), val);
13284       /* Return the address of the object.  */
13285       exprstmt = build_stmt (input_location, RETURN_EXPR, val);
13286       add_stmt (exprstmt);
13287     }
13288 }
13289
13290 /* Do the necessary processing for the beginning of a function body, which
13291    in this case includes member-initializers, but not the catch clauses of
13292    a function-try-block.  Currently, this means opening a binding level
13293    for the member-initializers (in a ctor), member cleanups (in a dtor),
13294    and capture proxies (in a lambda operator()).  */
13295
13296 tree
13297 begin_function_body (void)
13298 {
13299   tree stmt;
13300
13301   if (! FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
13302     return NULL_TREE;
13303
13304   if (processing_template_decl)
13305     /* Do nothing now.  */;
13306   else
13307     /* Always keep the BLOCK node associated with the outermost pair of
13308        curly braces of a function.  These are needed for correct
13309        operation of dwarfout.c.  */
13310     keep_next_level (true);
13311
13312   stmt = begin_compound_stmt (BCS_FN_BODY);
13313
13314   if (processing_template_decl)
13315     /* Do nothing now.  */;
13316   else if (DECL_DESTRUCTOR_P (current_function_decl))
13317     begin_destructor_body ();
13318
13319   return stmt;
13320 }
13321
13322 /* Do the processing for the end of a function body.  Currently, this means
13323    closing out the cleanups for fully-constructed bases and members, and in
13324    the case of the destructor, deleting the object if desired.  Again, this
13325    is only meaningful for [cd]tors, since they are the only functions where
13326    there is a significant distinction between the main body and any
13327    function catch clauses.  Handling, say, main() return semantics here
13328    would be wrong, as flowing off the end of a function catch clause for
13329    main() would also need to return 0.  */
13330
13331 void
13332 finish_function_body (tree compstmt)
13333 {
13334   if (compstmt == NULL_TREE)
13335     return;
13336
13337   /* Close the block.  */
13338   finish_compound_stmt (compstmt);
13339
13340   if (processing_template_decl)
13341     /* Do nothing now.  */;
13342   else if (DECL_CONSTRUCTOR_P (current_function_decl))
13343     finish_constructor_body ();
13344   else if (DECL_DESTRUCTOR_P (current_function_decl))
13345     finish_destructor_body ();
13346 }
13347
13348 /* Given a function, returns the BLOCK corresponding to the outermost level
13349    of curly braces, skipping the artificial block created for constructor
13350    initializers.  */
13351
13352 tree
13353 outer_curly_brace_block (tree fndecl)
13354 {
13355   tree block = BLOCK_SUBBLOCKS (DECL_INITIAL (fndecl));
13356   if (FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
13357     /* Skip the artificial function body block.  */
13358     block = BLOCK_SUBBLOCKS (block);
13359   return block;
13360 }
13361
13362 /* If FNDECL is a class's key method, add the class to the list of
13363    keyed classes that should be emitted.  */
13364
13365 static void
13366 record_key_method_defined (tree fndecl)
13367 {
13368   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
13369       && DECL_VIRTUAL_P (fndecl)
13370       && !processing_template_decl)
13371     {
13372       tree fnclass = DECL_CONTEXT (fndecl);
13373       if (fndecl == CLASSTYPE_KEY_METHOD (fnclass))
13374         keyed_classes = tree_cons (NULL_TREE, fnclass, keyed_classes);
13375     }
13376 }
13377
13378 /* Subroutine of finish_function.
13379    Save the body of constexpr functions for possible
13380    future compile time evaluation.  */
13381
13382 static void
13383 maybe_save_function_definition (tree fun)
13384 {
13385   if (!processing_template_decl
13386       && DECL_DECLARED_CONSTEXPR_P (fun)
13387       && !DECL_CLONED_FUNCTION_P (fun))
13388     register_constexpr_fundef (fun, DECL_SAVED_TREE (fun));
13389 }
13390
13391 /* Finish up a function declaration and compile that function
13392    all the way to assembler language output.  The free the storage
13393    for the function definition.
13394
13395    FLAGS is a bitwise or of the following values:
13396      2 - INCLASS_INLINE
13397        We just finished processing the body of an in-class inline
13398        function definition.  (This processing will have taken place
13399        after the class definition is complete.)  */
13400
13401 tree
13402 finish_function (int flags)
13403 {
13404   tree fndecl = current_function_decl;
13405   tree fntype, ctype = NULL_TREE;
13406   int inclass_inline = (flags & 2) != 0;
13407
13408   /* When we get some parse errors, we can end up without a
13409      current_function_decl, so cope.  */
13410   if (fndecl == NULL_TREE)
13411     return error_mark_node;
13412
13413   if (c_dialect_objc ())
13414     objc_finish_function ();
13415
13416   gcc_assert (!defer_mark_used_calls);
13417   defer_mark_used_calls = true;
13418
13419   record_key_method_defined (fndecl);
13420
13421   fntype = TREE_TYPE (fndecl);
13422
13423   /*  TREE_READONLY (fndecl) = 1;
13424       This caused &foo to be of type ptr-to-const-function
13425       which then got a warning when stored in a ptr-to-function variable.  */
13426
13427   gcc_assert (building_stmt_list_p ());
13428   /* The current function is being defined, so its DECL_INITIAL should
13429      be set, and unless there's a multiple definition, it should be
13430      error_mark_node.  */
13431   gcc_assert (DECL_INITIAL (fndecl) == error_mark_node);
13432
13433   /* For a cloned function, we've already got all the code we need;
13434      there's no need to add any extra bits.  */
13435   if (!DECL_CLONED_FUNCTION_P (fndecl))
13436     {
13437       /* Make it so that `main' always returns 0 by default.  */
13438       if (DECL_MAIN_P (current_function_decl))
13439         finish_return_stmt (integer_zero_node);
13440
13441       if (use_eh_spec_block (current_function_decl))
13442         finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
13443                               (TREE_TYPE (current_function_decl)),
13444                               current_eh_spec_block);
13445     }
13446
13447   /* If we're saving up tree structure, tie off the function now.  */
13448   DECL_SAVED_TREE (fndecl) = pop_stmt_list (DECL_SAVED_TREE (fndecl));
13449
13450   finish_fname_decls ();
13451
13452   /* If this function can't throw any exceptions, remember that.  */
13453   if (!processing_template_decl
13454       && !cp_function_chain->can_throw
13455       && !flag_non_call_exceptions
13456       && !decl_replaceable_p (fndecl))
13457     TREE_NOTHROW (fndecl) = 1;
13458
13459   /* This must come after expand_function_end because cleanups might
13460      have declarations (from inline functions) that need to go into
13461      this function's blocks.  */
13462
13463   /* If the current binding level isn't the outermost binding level
13464      for this function, either there is a bug, or we have experienced
13465      syntax errors and the statement tree is malformed.  */
13466   if (current_binding_level->kind != sk_function_parms)
13467     {
13468       /* Make sure we have already experienced errors.  */
13469       gcc_assert (errorcount);
13470
13471       /* Throw away the broken statement tree and extra binding
13472          levels.  */
13473       DECL_SAVED_TREE (fndecl) = alloc_stmt_list ();
13474
13475       while (current_binding_level->kind != sk_function_parms)
13476         {
13477           if (current_binding_level->kind == sk_class)
13478             pop_nested_class ();
13479           else
13480             poplevel (0, 0, 0);
13481         }
13482     }
13483   poplevel (1, 0, 1);
13484
13485   /* Statements should always be full-expressions at the outermost set
13486      of curly braces for a function.  */
13487   gcc_assert (stmts_are_full_exprs_p ());
13488
13489   /* If there are no return statements in a function with auto return type,
13490      the return type is void.  But if the declared type is something like
13491      auto*, this is an error.  */
13492   if (!processing_template_decl && FNDECL_USED_AUTO (fndecl)
13493       && TREE_TYPE (fntype) == current_function_auto_return_pattern)
13494     {
13495       if (!is_auto (current_function_auto_return_pattern)
13496           && !current_function_returns_value && !current_function_returns_null)
13497         {
13498           error ("no return statements in function returning %qT",
13499                  current_function_auto_return_pattern);
13500           inform (input_location, "only plain %<auto%> return type can be "
13501                   "deduced to %<void%>");
13502         }
13503       apply_deduced_return_type (fndecl, void_type_node);
13504       fntype = TREE_TYPE (fndecl);
13505     }
13506
13507   /* Save constexpr function body before it gets munged by
13508      the NRV transformation.   */
13509   maybe_save_function_definition (fndecl);
13510
13511   /* Set up the named return value optimization, if we can.  Candidate
13512      variables are selected in check_return_expr.  */
13513   if (current_function_return_value)
13514     {
13515       tree r = current_function_return_value;
13516       tree outer;
13517
13518       if (r != error_mark_node
13519           /* This is only worth doing for fns that return in memory--and
13520              simpler, since we don't have to worry about promoted modes.  */
13521           && aggregate_value_p (TREE_TYPE (TREE_TYPE (fndecl)), fndecl)
13522           /* Only allow this for variables declared in the outer scope of
13523              the function so we know that their lifetime always ends with a
13524              return; see g++.dg/opt/nrv6.C.  We could be more flexible if
13525              we were to do this optimization in tree-ssa.  */
13526           && (outer = outer_curly_brace_block (fndecl))
13527           && chain_member (r, BLOCK_VARS (outer)))
13528         finalize_nrv (&DECL_SAVED_TREE (fndecl), r, DECL_RESULT (fndecl));
13529
13530       current_function_return_value = NULL_TREE;
13531     }
13532
13533   /* Remember that we were in class scope.  */
13534   if (current_class_name)
13535     ctype = current_class_type;
13536
13537   /* Must mark the RESULT_DECL as being in this function.  */
13538   DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
13539
13540   /* Set the BLOCK_SUPERCONTEXT of the outermost function scope to point
13541      to the FUNCTION_DECL node itself.  */
13542   BLOCK_SUPERCONTEXT (DECL_INITIAL (fndecl)) = fndecl;
13543
13544   /* Save away current state, if appropriate.  */
13545   if (!processing_template_decl)
13546     save_function_data (fndecl);
13547
13548   /* Complain if there's just no return statement.  */
13549   if (warn_return_type
13550       && TREE_CODE (TREE_TYPE (fntype)) != VOID_TYPE
13551       && !dependent_type_p (TREE_TYPE (fntype))
13552       && !current_function_returns_value && !current_function_returns_null
13553       /* Don't complain if we abort or throw.  */
13554       && !current_function_returns_abnormally
13555       /* Don't complain if we are declared noreturn.  */
13556       && !TREE_THIS_VOLATILE (fndecl)
13557       && !DECL_NAME (DECL_RESULT (fndecl))
13558       && !TREE_NO_WARNING (fndecl)
13559       /* Structor return values (if any) are set by the compiler.  */
13560       && !DECL_CONSTRUCTOR_P (fndecl)
13561       && !DECL_DESTRUCTOR_P (fndecl)
13562       && targetm.warn_func_return (fndecl))
13563     {
13564       warning (OPT_Wreturn_type,
13565                "no return statement in function returning non-void");
13566       TREE_NO_WARNING (fndecl) = 1;
13567     }
13568
13569   /* Store the end of the function, so that we get good line number
13570      info for the epilogue.  */
13571   cfun->function_end_locus = input_location;
13572
13573   /* Complain about parameters that are only set, but never otherwise used.  */
13574   if (warn_unused_but_set_parameter
13575       && !processing_template_decl
13576       && errorcount == unused_but_set_errorcount
13577       && !DECL_CLONED_FUNCTION_P (fndecl))
13578     {
13579       tree decl;
13580
13581       for (decl = DECL_ARGUMENTS (fndecl);
13582            decl;
13583            decl = DECL_CHAIN (decl))
13584         if (TREE_USED (decl)
13585             && TREE_CODE (decl) == PARM_DECL
13586             && !DECL_READ_P (decl)
13587             && DECL_NAME (decl)
13588             && !DECL_ARTIFICIAL (decl)
13589             && !TREE_NO_WARNING (decl)
13590             && !DECL_IN_SYSTEM_HEADER (decl)
13591             && TREE_TYPE (decl) != error_mark_node
13592             && TREE_CODE (TREE_TYPE (decl)) != REFERENCE_TYPE
13593             && (!CLASS_TYPE_P (TREE_TYPE (decl))
13594                 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl))))
13595           warning (OPT_Wunused_but_set_parameter,
13596                    "parameter %q+D set but not used", decl);
13597       unused_but_set_errorcount = errorcount;
13598     }
13599
13600   /* Complain about locally defined typedefs that are not used in this
13601      function.  */
13602   maybe_warn_unused_local_typedefs ();
13603
13604   /* Genericize before inlining.  */
13605   if (!processing_template_decl)
13606     {
13607       struct language_function *f = DECL_SAVED_FUNCTION_DATA (fndecl);
13608       invoke_plugin_callbacks (PLUGIN_PRE_GENERICIZE, fndecl);
13609       cp_genericize (fndecl);
13610       /* Clear out the bits we don't need.  */
13611       f->x_current_class_ptr = NULL;
13612       f->x_current_class_ref = NULL;
13613       f->x_eh_spec_block = NULL;
13614       f->x_in_charge_parm = NULL;
13615       f->x_vtt_parm = NULL;
13616       f->x_return_value = NULL;
13617       f->bindings = NULL;
13618       f->extern_decl_map = NULL;
13619     }
13620   /* Clear out the bits we don't need.  */
13621   local_names = NULL;
13622
13623   /* We're leaving the context of this function, so zap cfun.  It's still in
13624      DECL_STRUCT_FUNCTION, and we'll restore it in tree_rest_of_compilation.  */
13625   set_cfun (NULL);
13626   current_function_decl = NULL;
13627
13628   /* If this is an in-class inline definition, we may have to pop the
13629      bindings for the template parameters that we added in
13630      maybe_begin_member_template_processing when start_function was
13631      called.  */
13632   if (inclass_inline)
13633     maybe_end_member_template_processing ();
13634
13635   /* Leave the scope of the class.  */
13636   if (ctype)
13637     pop_nested_class ();
13638
13639   --function_depth;
13640
13641   /* Clean up.  */
13642   current_function_decl = NULL_TREE;
13643
13644   defer_mark_used_calls = false;
13645   if (deferred_mark_used_calls)
13646     {
13647       unsigned int i;
13648       tree decl;
13649
13650       FOR_EACH_VEC_ELT (tree, deferred_mark_used_calls, i, decl)
13651         mark_used (decl);
13652       VEC_free (tree, gc, deferred_mark_used_calls);
13653     }
13654
13655   return fndecl;
13656 }
13657 \f
13658 /* Create the FUNCTION_DECL for a function definition.
13659    DECLSPECS and DECLARATOR are the parts of the declaration;
13660    they describe the return type and the name of the function,
13661    but twisted together in a fashion that parallels the syntax of C.
13662
13663    This function creates a binding context for the function body
13664    as well as setting up the FUNCTION_DECL in current_function_decl.
13665
13666    Returns a FUNCTION_DECL on success.
13667
13668    If the DECLARATOR is not suitable for a function (it defines a datum
13669    instead), we return 0, which tells yyparse to report a parse error.
13670
13671    May return void_type_node indicating that this method is actually
13672    a friend.  See grokfield for more details.
13673
13674    Came here with a `.pushlevel' .
13675
13676    DO NOT MAKE ANY CHANGES TO THIS CODE WITHOUT MAKING CORRESPONDING
13677    CHANGES TO CODE IN `grokfield'.  */
13678
13679 tree
13680 grokmethod (cp_decl_specifier_seq *declspecs,
13681             const cp_declarator *declarator, tree attrlist)
13682 {
13683   tree fndecl = grokdeclarator (declarator, declspecs, MEMFUNCDEF, 0,
13684                                 &attrlist);
13685
13686   if (fndecl == error_mark_node)
13687     return error_mark_node;
13688
13689   if (fndecl == NULL || TREE_CODE (fndecl) != FUNCTION_DECL)
13690     {
13691       error ("invalid member function declaration");
13692       return error_mark_node;
13693     }
13694
13695   if (attrlist)
13696     cplus_decl_attributes (&fndecl, attrlist, 0);
13697
13698   /* Pass friends other than inline friend functions back.  */
13699   if (fndecl == void_type_node)
13700     return fndecl;
13701
13702   if (DECL_IN_AGGR_P (fndecl))
13703     {
13704       if (DECL_CLASS_SCOPE_P (fndecl))
13705         error ("%qD is already defined in class %qT", fndecl,
13706                DECL_CONTEXT (fndecl));
13707       return error_mark_node;
13708     }
13709
13710   check_template_shadow (fndecl);
13711
13712   DECL_DECLARED_INLINE_P (fndecl) = 1;
13713   DECL_NO_INLINE_WARNING_P (fndecl) = 1;
13714
13715   /* We process method specializations in finish_struct_1.  */
13716   if (processing_template_decl && !DECL_TEMPLATE_SPECIALIZATION (fndecl))
13717     {
13718       fndecl = push_template_decl (fndecl);
13719       if (fndecl == error_mark_node)
13720         return fndecl;
13721     }
13722
13723   if (! DECL_FRIEND_P (fndecl))
13724     {
13725       if (DECL_CHAIN (fndecl))
13726         {
13727           fndecl = copy_node (fndecl);
13728           TREE_CHAIN (fndecl) = NULL_TREE;
13729         }
13730     }
13731
13732   cp_finish_decl (fndecl, NULL_TREE, false, NULL_TREE, 0);
13733
13734   DECL_IN_AGGR_P (fndecl) = 1;
13735   return fndecl;
13736 }
13737 \f
13738
13739 /* VAR is a VAR_DECL.  If its type is incomplete, remember VAR so that
13740    we can lay it out later, when and if its type becomes complete.  */
13741
13742 void
13743 maybe_register_incomplete_var (tree var)
13744 {
13745   gcc_assert (TREE_CODE (var) == VAR_DECL);
13746
13747   /* Keep track of variables with incomplete types.  */
13748   if (!processing_template_decl && TREE_TYPE (var) != error_mark_node
13749       && DECL_EXTERNAL (var))
13750     {
13751       tree inner_type = TREE_TYPE (var);
13752
13753       while (TREE_CODE (inner_type) == ARRAY_TYPE)
13754         inner_type = TREE_TYPE (inner_type);
13755       inner_type = TYPE_MAIN_VARIANT (inner_type);
13756
13757       if ((!COMPLETE_TYPE_P (inner_type) && CLASS_TYPE_P (inner_type))
13758           /* RTTI TD entries are created while defining the type_info.  */
13759           || (TYPE_LANG_SPECIFIC (inner_type)
13760               && TYPE_BEING_DEFINED (inner_type)))
13761         {
13762           incomplete_var *iv
13763             = VEC_safe_push (incomplete_var, gc, incomplete_vars, NULL);
13764           iv->decl = var;
13765           iv->incomplete_type = inner_type;
13766         }
13767     }
13768 }
13769
13770 /* Called when a class type (given by TYPE) is defined.  If there are
13771    any existing VAR_DECLs whose type has been completed by this
13772    declaration, update them now.  */
13773
13774 void
13775 complete_vars (tree type)
13776 {
13777   unsigned ix;
13778   incomplete_var *iv;
13779
13780   for (ix = 0; VEC_iterate (incomplete_var, incomplete_vars, ix, iv); )
13781     {
13782       if (same_type_p (type, iv->incomplete_type))
13783         {
13784           tree var = iv->decl;
13785           tree type = TREE_TYPE (var);
13786           /* Complete the type of the variable.  The VAR_DECL itself
13787              will be laid out in expand_expr.  */
13788           complete_type (type);
13789           cp_apply_type_quals_to_decl (cp_type_quals (type), var);
13790           /* Remove this entry from the list.  */
13791           VEC_unordered_remove (incomplete_var, incomplete_vars, ix);
13792         }
13793       else
13794         ix++;
13795     }
13796
13797   /* Check for pending declarations which may have abstract type.  */
13798   complete_type_check_abstract (type);
13799 }
13800
13801 /* If DECL is of a type which needs a cleanup, build and return an
13802    expression to perform that cleanup here.  Return NULL_TREE if no
13803    cleanup need be done.  */
13804
13805 tree
13806 cxx_maybe_build_cleanup (tree decl, tsubst_flags_t complain)
13807 {
13808   tree type;
13809   tree attr;
13810   tree cleanup;
13811
13812   /* Assume no cleanup is required.  */
13813   cleanup = NULL_TREE;
13814
13815   if (error_operand_p (decl))
13816     return cleanup;
13817
13818   /* Handle "__attribute__((cleanup))".  We run the cleanup function
13819      before the destructor since the destructor is what actually
13820      terminates the lifetime of the object.  */
13821   attr = lookup_attribute ("cleanup", DECL_ATTRIBUTES (decl));
13822   if (attr)
13823     {
13824       tree id;
13825       tree fn;
13826       tree arg;
13827
13828       /* Get the name specified by the user for the cleanup function.  */
13829       id = TREE_VALUE (TREE_VALUE (attr));
13830       /* Look up the name to find the cleanup function to call.  It is
13831          important to use lookup_name here because that is what is
13832          used in c-common.c:handle_cleanup_attribute when performing
13833          initial checks on the attribute.  Note that those checks
13834          include ensuring that the function found is not an overloaded
13835          function, or an object with an overloaded call operator,
13836          etc.; we can rely on the fact that the function found is an
13837          ordinary FUNCTION_DECL.  */
13838       fn = lookup_name (id);
13839       arg = build_address (decl);
13840       mark_used (decl);
13841       cleanup = cp_build_function_call_nary (fn, complain, arg, NULL_TREE);
13842       if (cleanup == error_mark_node)
13843         return error_mark_node;
13844     }
13845   /* Handle ordinary C++ destructors.  */
13846   type = TREE_TYPE (decl);
13847   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
13848     {
13849       int flags = LOOKUP_NORMAL|LOOKUP_DESTRUCTOR;
13850       bool has_vbases = (TREE_CODE (type) == RECORD_TYPE
13851                          && CLASSTYPE_VBASECLASSES (type));
13852       tree addr;
13853       tree call;
13854
13855       if (TREE_CODE (type) == ARRAY_TYPE)
13856         addr = decl;
13857       else
13858         addr = build_address (decl);
13859
13860       /* Optimize for space over speed here.  */
13861       if (!has_vbases || flag_expensive_optimizations)
13862         flags |= LOOKUP_NONVIRTUAL;
13863
13864       call = build_delete (TREE_TYPE (addr), addr,
13865                            sfk_complete_destructor, flags, 0, complain);
13866       if (call == error_mark_node)
13867         cleanup = error_mark_node;
13868       else if (cleanup)
13869         cleanup = cp_build_compound_expr (cleanup, call, complain);
13870       else
13871         cleanup = call;
13872     }
13873
13874   /* build_delete sets the location of the destructor call to the
13875      current location, even though the destructor is going to be
13876      called later, at the end of the current scope.  This can lead to
13877      a "jumpy" behaviour for users of debuggers when they step around
13878      the end of the block.  So let's unset the location of the
13879      destructor call instead.  */
13880   if (cleanup != NULL && EXPR_P (cleanup))
13881     SET_EXPR_LOCATION (cleanup, UNKNOWN_LOCATION);
13882   return cleanup;
13883 }
13884
13885 \f
13886 /* When a stmt has been parsed, this function is called.  */
13887
13888 void
13889 finish_stmt (void)
13890 {
13891 }
13892
13893 /* Return the FUNCTION_TYPE that corresponds to MEMFNTYPE, which can be a
13894    FUNCTION_DECL, METHOD_TYPE, FUNCTION_TYPE, pointer or reference to
13895    METHOD_TYPE or FUNCTION_TYPE, or pointer to member function.  */
13896
13897 tree
13898 static_fn_type (tree memfntype)
13899 {
13900   tree fntype;
13901   tree args;
13902
13903   if (TYPE_PTRMEMFUNC_P (memfntype))
13904     memfntype = TYPE_PTRMEMFUNC_FN_TYPE (memfntype);
13905   if (POINTER_TYPE_P (memfntype)
13906       || TREE_CODE (memfntype) == FUNCTION_DECL)
13907     memfntype = TREE_TYPE (memfntype);
13908   if (TREE_CODE (memfntype) == FUNCTION_TYPE)
13909     return memfntype;
13910   gcc_assert (TREE_CODE (memfntype) == METHOD_TYPE);
13911   args = TYPE_ARG_TYPES (memfntype);
13912   fntype = build_function_type (TREE_TYPE (memfntype), TREE_CHAIN (args));
13913   fntype = apply_memfn_quals (fntype, type_memfn_quals (memfntype));
13914   fntype = (cp_build_type_attribute_variant
13915             (fntype, TYPE_ATTRIBUTES (memfntype)));
13916   fntype = (build_exception_variant
13917             (fntype, TYPE_RAISES_EXCEPTIONS (memfntype)));
13918   return fntype;
13919 }
13920
13921 /* DECL was originally constructed as a non-static member function,
13922    but turned out to be static.  Update it accordingly.  */
13923
13924 void
13925 revert_static_member_fn (tree decl)
13926 {
13927   tree stype = static_fn_type (decl);
13928   cp_cv_quals quals = type_memfn_quals (stype);
13929
13930   if (quals != TYPE_UNQUALIFIED)
13931     stype = apply_memfn_quals (stype, TYPE_UNQUALIFIED);
13932
13933   TREE_TYPE (decl) = stype;
13934
13935   if (DECL_ARGUMENTS (decl))
13936     DECL_ARGUMENTS (decl) = DECL_CHAIN (DECL_ARGUMENTS (decl));
13937   DECL_STATIC_FUNCTION_P (decl) = 1;
13938 }
13939
13940 /* Return which tree structure is used by T, or TS_CP_GENERIC if T is
13941    one of the language-independent trees.  */
13942
13943 enum cp_tree_node_structure_enum
13944 cp_tree_node_structure (union lang_tree_node * t)
13945 {
13946   switch (TREE_CODE (&t->generic))
13947     {
13948     case DEFAULT_ARG:           return TS_CP_DEFAULT_ARG;
13949     case DEFERRED_NOEXCEPT:     return TS_CP_DEFERRED_NOEXCEPT;
13950     case IDENTIFIER_NODE:       return TS_CP_IDENTIFIER;
13951     case OVERLOAD:              return TS_CP_OVERLOAD;
13952     case TEMPLATE_PARM_INDEX:   return TS_CP_TPI;
13953     case PTRMEM_CST:            return TS_CP_PTRMEM;
13954     case BASELINK:              return TS_CP_BASELINK;
13955     case STATIC_ASSERT:         return TS_CP_STATIC_ASSERT;
13956     case ARGUMENT_PACK_SELECT:  return TS_CP_ARGUMENT_PACK_SELECT;
13957     case TRAIT_EXPR:            return TS_CP_TRAIT_EXPR;
13958     case LAMBDA_EXPR:           return TS_CP_LAMBDA_EXPR;
13959     case TEMPLATE_INFO:         return TS_CP_TEMPLATE_INFO;
13960     case USERDEF_LITERAL:       return TS_CP_USERDEF_LITERAL;
13961     default:                    return TS_CP_GENERIC;
13962     }
13963 }
13964
13965 /* Build the void_list_node (void_type_node having been created).  */
13966 tree
13967 build_void_list_node (void)
13968 {
13969   tree t = build_tree_list (NULL_TREE, void_type_node);
13970   return t;
13971 }
13972
13973 bool
13974 cp_missing_noreturn_ok_p (tree decl)
13975 {
13976   /* A missing noreturn is ok for the `main' function.  */
13977   return DECL_MAIN_P (decl);
13978 }
13979
13980 /* Return the COMDAT group into which DECL should be placed.  */
13981
13982 tree
13983 cxx_comdat_group (tree decl)
13984 {
13985   tree name;
13986
13987   /* Virtual tables, construction virtual tables, and virtual table
13988      tables all go in a single COMDAT group, named after the primary
13989      virtual table.  */
13990   if (TREE_CODE (decl) == VAR_DECL && DECL_VTABLE_OR_VTT_P (decl))
13991     name = DECL_ASSEMBLER_NAME (CLASSTYPE_VTABLES (DECL_CONTEXT (decl)));
13992   /* For all other DECLs, the COMDAT group is the mangled name of the
13993      declaration itself.  */
13994   else
13995     {
13996       while (DECL_THUNK_P (decl))
13997         {
13998           /* If TARGET_USE_LOCAL_THUNK_ALIAS_P, use_thunk puts the thunk
13999              into the same section as the target function.  In that case
14000              we must return target's name.  */
14001           tree target = THUNK_TARGET (decl);
14002           if (TARGET_USE_LOCAL_THUNK_ALIAS_P (target)
14003               && DECL_SECTION_NAME (target) != NULL
14004               && DECL_ONE_ONLY (target))
14005             decl = target;
14006           else
14007             break;
14008         }
14009       name = DECL_ASSEMBLER_NAME (decl);
14010     }
14011
14012   return name;
14013 }
14014
14015 #include "gt-cp-decl.h"