cf917731f0ca65dadb6fd68aa187bf0d109452f0
[platform/upstream/gcc.git] / gcc / cp / decl.c
1 /* Process declarations and variables for C++ compiler.
2    Copyright (C) 1988-2018 Free Software Foundation, Inc.
3    Contributed by Michael Tiemann (tiemann@cygnus.com)
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21
22 /* Process declarations and symbol lookup for C++ front end.
23    Also constructs types; the standard scalar types at initialization,
24    and structure, union, array and enum types when they are declared.  */
25
26 /* ??? not all decl nodes are given the most useful possible
27    line numbers.  For example, the CONST_DECLs for enum values.  */
28
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "target.h"
33 #include "c-family/c-target.h"
34 #include "cp-tree.h"
35 #include "timevar.h"
36 #include "stringpool.h"
37 #include "cgraph.h"
38 #include "stor-layout.h"
39 #include "varasm.h"
40 #include "attribs.h"
41 #include "flags.h"
42 #include "tree-iterator.h"
43 #include "decl.h"
44 #include "intl.h"
45 #include "toplev.h"
46 #include "c-family/c-objc.h"
47 #include "c-family/c-pragma.h"
48 #include "c-family/c-ubsan.h"
49 #include "debug.h"
50 #include "plugin.h"
51 #include "builtins.h"
52 #include "gimplify.h"
53 #include "asan.h"
54
55 /* Possible cases of bad specifiers type used by bad_specifiers. */
56 enum bad_spec_place {
57   BSP_VAR,    /* variable */
58   BSP_PARM,   /* parameter */
59   BSP_TYPE,   /* type */
60   BSP_FIELD   /* field */
61 };
62
63 static const char *redeclaration_error_message (tree, tree);
64
65 static int decl_jump_unsafe (tree);
66 static void require_complete_types_for_parms (tree);
67 static void push_local_name (tree);
68 static tree grok_reference_init (tree, tree, tree, int);
69 static tree grokvardecl (tree, tree, tree, const cp_decl_specifier_seq *,
70                          int, int, int, bool, int, tree);
71 static int check_static_variable_definition (tree, tree);
72 static void record_unknown_type (tree, const char *);
73 static tree builtin_function_1 (tree, tree, bool);
74 static int member_function_or_else (tree, tree, enum overload_flags);
75 static tree local_variable_p_walkfn (tree *, int *, void *);
76 static const char *tag_name (enum tag_types);
77 static tree lookup_and_check_tag (enum tag_types, tree, tag_scope, bool);
78 static void maybe_deduce_size_from_array_init (tree, tree);
79 static void layout_var_decl (tree);
80 static tree check_initializer (tree, tree, int, vec<tree, va_gc> **);
81 static void make_rtl_for_nonlocal_decl (tree, tree, const char *);
82 static void save_function_data (tree);
83 static void copy_type_enum (tree , tree);
84 static void check_function_type (tree, tree);
85 static void finish_constructor_body (void);
86 static void begin_destructor_body (void);
87 static void finish_destructor_body (void);
88 static void record_key_method_defined (tree);
89 static tree create_array_type_for_decl (tree, tree, tree);
90 static tree get_atexit_node (void);
91 static tree get_dso_handle_node (void);
92 static tree start_cleanup_fn (void);
93 static void end_cleanup_fn (void);
94 static tree cp_make_fname_decl (location_t, tree, int);
95 static void initialize_predefined_identifiers (void);
96 static tree check_special_function_return_type
97        (special_function_kind, tree, tree, int, const location_t*);
98 static tree push_cp_library_fn (enum tree_code, tree, int);
99 static tree build_cp_library_fn (tree, enum tree_code, tree, int);
100 static void store_parm_decls (tree);
101 static void initialize_local_var (tree, tree);
102 static void expand_static_init (tree, tree);
103
104 /* The following symbols are subsumed in the cp_global_trees array, and
105    listed here individually for documentation purposes.
106
107    C++ extensions
108         tree wchar_decl_node;
109
110         tree vtable_entry_type;
111         tree delta_type_node;
112         tree __t_desc_type_node;
113
114         tree class_type_node;
115         tree unknown_type_node;
116
117    Array type `vtable_entry_type[]'
118
119         tree vtbl_type_node;
120         tree vtbl_ptr_type_node;
121
122    Namespaces,
123
124         tree std_node;
125         tree abi_node;
126
127    A FUNCTION_DECL which can call `abort'.  Not necessarily the
128    one that the user will declare, but sufficient to be called
129    by routines that want to abort the program.
130
131         tree abort_fndecl;
132
133    Used by RTTI
134         tree type_info_type_node, tinfo_decl_id, tinfo_decl_type;
135         tree tinfo_var_id;  */
136
137 tree cp_global_trees[CPTI_MAX];
138
139 #define local_names cp_function_chain->x_local_names
140
141 /* A list of objects which have constructors or destructors
142    which reside in the global scope.  The decl is stored in
143    the TREE_VALUE slot and the initializer is stored
144    in the TREE_PURPOSE slot.  */
145 tree static_aggregates;
146
147 /* Like static_aggregates, but for thread_local variables.  */
148 tree tls_aggregates;
149
150 /* -- end of C++ */
151
152 /* A node for the integer constant 2.  */
153
154 tree integer_two_node;
155
156 /* vector of static decls.  */
157 vec<tree, va_gc> *static_decls;
158
159 /* vector of keyed classes.  */
160 vec<tree, va_gc> *keyed_classes;
161
162 /* Used only for jumps to as-yet undefined labels, since jumps to
163    defined labels can have their validity checked immediately.  */
164
165 struct GTY((chain_next ("%h.next"))) named_label_use_entry {
166   struct named_label_use_entry *next;
167   /* The binding level to which this entry is *currently* attached.
168      This is initially the binding level in which the goto appeared,
169      but is modified as scopes are closed.  */
170   cp_binding_level *binding_level;
171   /* The head of the names list that was current when the goto appeared,
172      or the inner scope popped.  These are the decls that will *not* be
173      skipped when jumping to the label.  */
174   tree names_in_scope;
175   /* The location of the goto, for error reporting.  */
176   location_t o_goto_locus;
177   /* True if an OpenMP structured block scope has been closed since
178      the goto appeared.  This means that the branch from the label will
179      illegally exit an OpenMP scope.  */
180   bool in_omp_scope;
181 };
182
183 /* A list of all LABEL_DECLs in the function that have names.  Here so
184    we can clear out their names' definitions at the end of the
185    function, and so we can check the validity of jumps to these labels.  */
186
187 struct GTY((for_user)) named_label_entry {
188
189   tree name;  /* Name of decl. */
190
191   tree label_decl; /* LABEL_DECL, unless deleted local label. */
192
193   named_label_entry *outer; /* Outer shadowed chain.  */
194
195   /* The binding level to which the label is *currently* attached.
196      This is initially set to the binding level in which the label
197      is defined, but is modified as scopes are closed.  */
198   cp_binding_level *binding_level;
199
200   /* The head of the names list that was current when the label was
201      defined, or the inner scope popped.  These are the decls that will
202      be skipped when jumping to the label.  */
203   tree names_in_scope;
204
205   /* A vector of all decls from all binding levels that would be
206      crossed by a backward branch to the label.  */
207   vec<tree, va_gc> *bad_decls;
208
209   /* A list of uses of the label, before the label is defined.  */
210   named_label_use_entry *uses;
211
212   /* The following bits are set after the label is defined, and are
213      updated as scopes are popped.  They indicate that a jump to the
214      label will illegally enter a scope of the given flavor.  */
215   bool in_try_scope;
216   bool in_catch_scope;
217   bool in_omp_scope;
218   bool in_transaction_scope;
219   bool in_constexpr_if;
220 };
221
222 #define named_labels cp_function_chain->x_named_labels
223 \f
224 /* The number of function bodies which we are currently processing.
225    (Zero if we are at namespace scope, one inside the body of a
226    function, two inside the body of a function in a local class, etc.)  */
227 int function_depth;
228
229 /* Whether the exception-specifier is part of a function type (i.e. C++17).  */
230 bool flag_noexcept_type;
231
232 /* States indicating how grokdeclarator() should handle declspecs marked
233    with __attribute__((deprecated)).  An object declared as
234    __attribute__((deprecated)) suppresses warnings of uses of other
235    deprecated items.  */
236 enum deprecated_states deprecated_state = DEPRECATED_NORMAL;
237
238 \f
239 /* A list of VAR_DECLs whose type was incomplete at the time the
240    variable was declared.  */
241
242 struct GTY(()) incomplete_var {
243   tree decl;
244   tree incomplete_type;
245 };
246
247
248 static GTY(()) vec<incomplete_var, va_gc> *incomplete_vars;
249 \f
250 /* Returns the kind of template specialization we are currently
251    processing, given that it's declaration contained N_CLASS_SCOPES
252    explicit scope qualifications.  */
253
254 tmpl_spec_kind
255 current_tmpl_spec_kind (int n_class_scopes)
256 {
257   int n_template_parm_scopes = 0;
258   int seen_specialization_p = 0;
259   int innermost_specialization_p = 0;
260   cp_binding_level *b;
261
262   /* Scan through the template parameter scopes.  */
263   for (b = current_binding_level;
264        b->kind == sk_template_parms;
265        b = b->level_chain)
266     {
267       /* If we see a specialization scope inside a parameter scope,
268          then something is wrong.  That corresponds to a declaration
269          like:
270
271             template <class T> template <> ...
272
273          which is always invalid since [temp.expl.spec] forbids the
274          specialization of a class member template if the enclosing
275          class templates are not explicitly specialized as well.  */
276       if (b->explicit_spec_p)
277         {
278           if (n_template_parm_scopes == 0)
279             innermost_specialization_p = 1;
280           else
281             seen_specialization_p = 1;
282         }
283       else if (seen_specialization_p == 1)
284         return tsk_invalid_member_spec;
285
286       ++n_template_parm_scopes;
287     }
288
289   /* Handle explicit instantiations.  */
290   if (processing_explicit_instantiation)
291     {
292       if (n_template_parm_scopes != 0)
293         /* We've seen a template parameter list during an explicit
294            instantiation.  For example:
295
296              template <class T> template void f(int);
297
298            This is erroneous.  */
299         return tsk_invalid_expl_inst;
300       else
301         return tsk_expl_inst;
302     }
303
304   if (n_template_parm_scopes < n_class_scopes)
305     /* We've not seen enough template headers to match all the
306        specialized classes present.  For example:
307
308          template <class T> void R<T>::S<T>::f(int);
309
310        This is invalid; there needs to be one set of template
311        parameters for each class.  */
312     return tsk_insufficient_parms;
313   else if (n_template_parm_scopes == n_class_scopes)
314     /* We're processing a non-template declaration (even though it may
315        be a member of a template class.)  For example:
316
317          template <class T> void S<T>::f(int);
318
319        The `class T' matches the `S<T>', leaving no template headers
320        corresponding to the `f'.  */
321     return tsk_none;
322   else if (n_template_parm_scopes > n_class_scopes + 1)
323     /* We've got too many template headers.  For example:
324
325          template <> template <class T> void f (T);
326
327        There need to be more enclosing classes.  */
328     return tsk_excessive_parms;
329   else
330     /* This must be a template.  It's of the form:
331
332          template <class T> template <class U> void S<T>::f(U);
333
334        This is a specialization if the innermost level was a
335        specialization; otherwise it's just a definition of the
336        template.  */
337     return innermost_specialization_p ? tsk_expl_spec : tsk_template;
338 }
339
340 /* Exit the current scope.  */
341
342 void
343 finish_scope (void)
344 {
345   poplevel (0, 0, 0);
346 }
347
348 /* When a label goes out of scope, check to see if that label was used
349    in a valid manner, and issue any appropriate warnings or errors.  */
350
351 static void
352 check_label_used (tree label)
353 {
354   if (!processing_template_decl)
355     {
356       if (DECL_INITIAL (label) == NULL_TREE)
357         {
358           location_t location;
359
360           error ("label %q+D used but not defined", label);
361           location = input_location;
362             /* FIXME want (LOCATION_FILE (input_location), (line)0) */
363           /* Avoid crashing later.  */
364           define_label (location, DECL_NAME (label));
365         }
366       else 
367         warn_for_unused_label (label);
368     }
369 }
370
371 /* Helper function to sort named label entries in a vector by DECL_UID.  */
372
373 static int
374 sort_labels (const void *a, const void *b)
375 {
376   tree label1 = *(tree const *) a;
377   tree label2 = *(tree const *) b;
378
379   /* DECL_UIDs can never be equal.  */
380   return DECL_UID (label1) > DECL_UID (label2) ? -1 : +1;
381 }
382
383 /* At the end of a function, all labels declared within the function
384    go out of scope.  BLOCK is the top-level block for the
385    function.  */
386
387 static void
388 pop_labels (tree block)
389 {
390   if (!named_labels)
391     return;
392
393   /* We need to add the labels to the block chain, so debug
394      information is emitted.  But, we want the order to be stable so
395      need to sort them first.  Otherwise the debug output could be
396      randomly ordered.  I guess it's mostly stable, unless the hash
397      table implementation changes.  */
398   auto_vec<tree, 32> labels (named_labels->elements ());
399   hash_table<named_label_hash>::iterator end (named_labels->end ());
400   for (hash_table<named_label_hash>::iterator iter
401          (named_labels->begin ()); iter != end; ++iter)
402     {
403       named_label_entry *ent = *iter;
404
405       gcc_checking_assert (!ent->outer);
406       if (ent->label_decl)
407         labels.quick_push (ent->label_decl);
408       ggc_free (ent);
409     }
410   named_labels = NULL;
411   labels.qsort (sort_labels);
412
413   while (labels.length ())
414     {
415       tree label = labels.pop ();
416
417       DECL_CHAIN (label) = BLOCK_VARS (block);
418       BLOCK_VARS (block) = label;
419
420       check_label_used (label);
421     }
422 }
423
424 /* At the end of a block with local labels, restore the outer definition.  */
425
426 static void
427 pop_local_label (tree id, tree label)
428 {
429   check_label_used (label);
430   named_label_entry **slot = named_labels->find_slot_with_hash
431     (id, IDENTIFIER_HASH_VALUE (id), NO_INSERT);
432   named_label_entry *ent = *slot;
433
434   if (ent->outer)
435     ent = ent->outer;
436   else
437     {
438       ent = ggc_cleared_alloc<named_label_entry> ();
439       ent->name = id;
440     }
441   *slot = ent;
442 }
443
444 /* The following two routines are used to interface to Objective-C++.
445    The binding level is purposely treated as an opaque type.  */
446
447 void *
448 objc_get_current_scope (void)
449 {
450   return current_binding_level;
451 }
452
453 /* The following routine is used by the NeXT-style SJLJ exceptions;
454    variables get marked 'volatile' so as to not be clobbered by
455    _setjmp()/_longjmp() calls.  All variables in the current scope,
456    as well as parent scopes up to (but not including) ENCLOSING_BLK
457    shall be thusly marked.  */
458
459 void
460 objc_mark_locals_volatile (void *enclosing_blk)
461 {
462   cp_binding_level *scope;
463
464   for (scope = current_binding_level;
465        scope && scope != enclosing_blk;
466        scope = scope->level_chain)
467     {
468       tree decl;
469
470       for (decl = scope->names; decl; decl = TREE_CHAIN (decl))
471         objc_volatilize_decl (decl);
472
473       /* Do not climb up past the current function.  */
474       if (scope->kind == sk_function_parms)
475         break;
476     }
477 }
478
479 /* True if B is the level for the condition of a constexpr if.  */
480
481 static bool
482 level_for_constexpr_if (cp_binding_level *b)
483 {
484   return (b->kind == sk_cond && b->this_entity
485           && TREE_CODE (b->this_entity) == IF_STMT
486           && IF_STMT_CONSTEXPR_P (b->this_entity));
487 }
488
489 /* Update data for defined and undefined labels when leaving a scope.  */
490
491 int
492 poplevel_named_label_1 (named_label_entry **slot, cp_binding_level *bl)
493 {
494   named_label_entry *ent = *slot;
495   cp_binding_level *obl = bl->level_chain;
496
497   if (ent->binding_level == bl)
498     {
499       tree decl;
500
501       /* ENT->NAMES_IN_SCOPE may contain a mixture of DECLs and
502          TREE_LISTs representing OVERLOADs, so be careful.  */
503       for (decl = ent->names_in_scope; decl; decl = (DECL_P (decl)
504                                                      ? DECL_CHAIN (decl)
505                                                      : TREE_CHAIN (decl)))
506         if (decl_jump_unsafe (decl))
507           vec_safe_push (ent->bad_decls, decl);
508
509       ent->binding_level = obl;
510       ent->names_in_scope = obl->names;
511       switch (bl->kind)
512         {
513         case sk_try:
514           ent->in_try_scope = true;
515           break;
516         case sk_catch:
517           ent->in_catch_scope = true;
518           break;
519         case sk_omp:
520           ent->in_omp_scope = true;
521           break;
522         case sk_transaction:
523           ent->in_transaction_scope = true;
524           break;
525         case sk_block:
526           if (level_for_constexpr_if (bl->level_chain))
527             ent->in_constexpr_if = true;
528           break;
529         default:
530           break;
531         }
532     }
533   else if (ent->uses)
534     {
535       struct named_label_use_entry *use;
536
537       for (use = ent->uses; use ; use = use->next)
538         if (use->binding_level == bl)
539           {
540             use->binding_level = obl;
541             use->names_in_scope = obl->names;
542             if (bl->kind == sk_omp)
543               use->in_omp_scope = true;
544           }
545     }
546
547   return 1;
548 }
549
550 /* Saved errorcount to avoid -Wunused-but-set-{parameter,variable} warnings
551    when errors were reported, except for -Werror-unused-but-set-*.  */
552 static int unused_but_set_errorcount;
553
554 /* Exit a binding level.
555    Pop the level off, and restore the state of the identifier-decl mappings
556    that were in effect when this level was entered.
557
558    If KEEP == 1, this level had explicit declarations, so
559    and create a "block" (a BLOCK node) for the level
560    to record its declarations and subblocks for symbol table output.
561
562    If FUNCTIONBODY is nonzero, this level is the body of a function,
563    so create a block as if KEEP were set and also clear out all
564    label names.
565
566    If REVERSE is nonzero, reverse the order of decls before putting
567    them into the BLOCK.  */
568
569 tree
570 poplevel (int keep, int reverse, int functionbody)
571 {
572   tree link;
573   /* The chain of decls was accumulated in reverse order.
574      Put it into forward order, just for cleanliness.  */
575   tree decls;
576   tree subblocks;
577   tree block;
578   tree decl;
579   int leaving_for_scope;
580   scope_kind kind;
581   unsigned ix;
582
583   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
584  restart:
585
586   block = NULL_TREE;
587
588   gcc_assert (current_binding_level->kind != sk_class
589               && current_binding_level->kind != sk_namespace);
590
591   if (current_binding_level->kind == sk_cleanup)
592     functionbody = 0;
593   subblocks = functionbody >= 0 ? current_binding_level->blocks : 0;
594
595   gcc_assert (!vec_safe_length (current_binding_level->class_shadowed));
596
597   /* We used to use KEEP == 2 to indicate that the new block should go
598      at the beginning of the list of blocks at this binding level,
599      rather than the end.  This hack is no longer used.  */
600   gcc_assert (keep == 0 || keep == 1);
601
602   if (current_binding_level->keep)
603     keep = 1;
604
605   /* Any uses of undefined labels, and any defined labels, now operate
606      under constraints of next binding contour.  */
607   if (cfun && !functionbody && named_labels)
608     named_labels->traverse<cp_binding_level *, poplevel_named_label_1>
609                    (current_binding_level);
610
611   /* Get the decls in the order they were written.
612      Usually current_binding_level->names is in reverse order.
613      But parameter decls were previously put in forward order.  */
614
615   decls = current_binding_level->names;
616   if (reverse)
617     {
618       decls = nreverse (decls);
619       current_binding_level->names = decls;
620     }
621
622   /* If there were any declarations or structure tags in that level,
623      or if this level is a function body,
624      create a BLOCK to record them for the life of this function.  */
625   block = NULL_TREE;
626   /* Avoid function body block if possible.  */
627   if (functionbody && subblocks && BLOCK_CHAIN (subblocks) == NULL_TREE)
628     keep = 0;
629   else if (keep == 1 || functionbody)
630     block = make_node (BLOCK);
631   if (block != NULL_TREE)
632     {
633       BLOCK_VARS (block) = decls;
634       BLOCK_SUBBLOCKS (block) = subblocks;
635     }
636
637   /* In each subblock, record that this is its superior.  */
638   if (keep >= 0)
639     for (link = subblocks; link; link = BLOCK_CHAIN (link))
640       BLOCK_SUPERCONTEXT (link) = block;
641
642   /* We still support the old for-scope rules, whereby the variables
643      in a init statement were in scope after the for-statement ended.
644      We only use the new rules if flag_new_for_scope is nonzero.  */
645   leaving_for_scope
646     = current_binding_level->kind == sk_for && flag_new_for_scope;
647
648   /* Before we remove the declarations first check for unused variables.  */
649   if ((warn_unused_variable || warn_unused_but_set_variable)
650       && current_binding_level->kind != sk_template_parms
651       && !processing_template_decl)
652     for (tree d = get_local_decls (); d; d = TREE_CHAIN (d))
653       {
654         /* There are cases where D itself is a TREE_LIST.  See in
655            push_local_binding where the list of decls returned by
656            getdecls is built.  */
657         decl = TREE_CODE (d) == TREE_LIST ? TREE_VALUE (d) : d;
658
659         tree type = TREE_TYPE (decl);
660         if (VAR_P (decl)
661             && (! TREE_USED (decl) || !DECL_READ_P (decl))
662             && ! DECL_IN_SYSTEM_HEADER (decl)
663             /* For structured bindings, consider only real variables, not
664                subobjects.  */
665             && (DECL_DECOMPOSITION_P (decl) ? !DECL_DECOMP_BASE (decl)
666                 : (DECL_NAME (decl) && !DECL_ARTIFICIAL (decl)))
667             && type != error_mark_node
668             && (!CLASS_TYPE_P (type)
669                 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
670                 || lookup_attribute ("warn_unused",
671                                      TYPE_ATTRIBUTES (TREE_TYPE (decl)))))
672           {
673             if (! TREE_USED (decl))
674               {
675                 if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
676                   warning_at (DECL_SOURCE_LOCATION (decl),
677                               OPT_Wunused_variable,
678                               "unused structured binding declaration");
679                 else
680                   warning_at (DECL_SOURCE_LOCATION (decl),
681                               OPT_Wunused_variable, "unused variable %qD", decl);
682               }
683             else if (DECL_CONTEXT (decl) == current_function_decl
684                      // For -Wunused-but-set-variable leave references alone.
685                      && TREE_CODE (TREE_TYPE (decl)) != REFERENCE_TYPE
686                      && errorcount == unused_but_set_errorcount)
687               {
688                 if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
689                   warning_at (DECL_SOURCE_LOCATION (decl),
690                               OPT_Wunused_but_set_variable, "structured "
691                               "binding declaration set but not used");
692                 else
693                   warning_at (DECL_SOURCE_LOCATION (decl),
694                               OPT_Wunused_but_set_variable,
695                               "variable %qD set but not used", decl);
696                 unused_but_set_errorcount = errorcount;
697               }
698           }
699       }
700
701   /* Remove declarations for all the DECLs in this level.  */
702   for (link = decls; link; link = TREE_CHAIN (link))
703     {
704       decl = TREE_CODE (link) == TREE_LIST ? TREE_VALUE (link) : link;
705       tree name = OVL_NAME (decl);
706
707       if (leaving_for_scope && VAR_P (decl)
708           /* It's hard to make this ARM compatibility hack play nicely with
709              lambdas, and it really isn't necessary in C++11 mode.  */
710           && cxx_dialect < cxx11
711           && name)
712         {
713           cxx_binding *ob = outer_binding (name,
714                                            IDENTIFIER_BINDING (name),
715                                            /*class_p=*/true);
716           tree ns_binding = NULL_TREE;
717           if (!ob)
718             ns_binding = get_namespace_binding (current_namespace, name);
719
720           if (ob && ob->scope == current_binding_level->level_chain)
721             /* We have something like:
722
723                  int i;
724                  for (int i; ;);
725
726                and we are leaving the `for' scope.  There's no reason to
727                keep the binding of the inner `i' in this case.  */
728             ;
729           else if ((ob && (TREE_CODE (ob->value) == TYPE_DECL))
730                    || (ns_binding && TREE_CODE (ns_binding) == TYPE_DECL))
731             /* Here, we have something like:
732
733                  typedef int I;
734
735                  void f () {
736                    for (int I; ;);
737                  }
738
739                We must pop the for-scope binding so we know what's a
740                type and what isn't.  */
741             ;
742           else
743             {
744               /* Mark this VAR_DECL as dead so that we can tell we left it
745                  there only for backward compatibility.  */
746               DECL_DEAD_FOR_LOCAL (link) = 1;
747
748               /* Keep track of what should have happened when we
749                  popped the binding.  */
750               if (ob && ob->value)
751                 {
752                   SET_DECL_SHADOWED_FOR_VAR (link, ob->value);
753                   DECL_HAS_SHADOWED_FOR_VAR_P (link) = 1;
754                 }
755
756               /* Add it to the list of dead variables in the next
757                  outermost binding to that we can remove these when we
758                  leave that binding.  */
759               vec_safe_push (
760                   current_binding_level->level_chain->dead_vars_from_for,
761                   link);
762
763               /* Although we don't pop the cxx_binding, we do clear
764                  its SCOPE since the scope is going away now.  */
765               IDENTIFIER_BINDING (name)->scope
766                 = current_binding_level->level_chain;
767
768               /* Don't remove the binding. */
769               name = NULL_TREE;
770             }
771         }
772       /* Remove the binding.  */
773       if (TREE_CODE (decl) == LABEL_DECL)
774         pop_local_label (name, decl);
775       else
776         pop_local_binding (name, decl);
777     }
778
779   /* Remove declarations for any `for' variables from inner scopes
780      that we kept around.  */
781   FOR_EACH_VEC_SAFE_ELT_REVERSE (current_binding_level->dead_vars_from_for,
782                                  ix, decl)
783     pop_local_binding (DECL_NAME (decl), decl);
784
785   /* Restore the IDENTIFIER_TYPE_VALUEs.  */
786   for (link = current_binding_level->type_shadowed;
787        link; link = TREE_CHAIN (link))
788     SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (link), TREE_VALUE (link));
789
790   /* There may be OVERLOADs (wrapped in TREE_LISTs) on the BLOCK_VARs
791      list if a `using' declaration put them there.  The debugging
792      back ends won't understand OVERLOAD, so we remove them here.
793      Because the BLOCK_VARS are (temporarily) shared with
794      CURRENT_BINDING_LEVEL->NAMES we must do this fixup after we have
795      popped all the bindings.  Also remove undeduced 'auto' decls,
796      which LTO doesn't understand, and can't have been used by anything.  */
797   if (block)
798     {
799       tree* d;
800
801       for (d = &BLOCK_VARS (block); *d; )
802         {
803           if (TREE_CODE (*d) == TREE_LIST
804               || (!processing_template_decl
805                   && undeduced_auto_decl (*d)))
806             *d = TREE_CHAIN (*d);
807           else
808             d = &DECL_CHAIN (*d);
809         }
810     }
811
812   /* If the level being exited is the top level of a function,
813      check over all the labels.  */
814   if (functionbody)
815     {
816       if (block)
817         {
818           /* Since this is the top level block of a function, the vars are
819              the function's parameters.  Don't leave them in the BLOCK
820              because they are found in the FUNCTION_DECL instead.  */
821           BLOCK_VARS (block) = 0;
822           pop_labels (block);
823         }
824       else
825         pop_labels (subblocks);
826     }
827
828   kind = current_binding_level->kind;
829   if (kind == sk_cleanup)
830     {
831       tree stmt;
832
833       /* If this is a temporary binding created for a cleanup, then we'll
834          have pushed a statement list level.  Pop that, create a new
835          BIND_EXPR for the block, and insert it into the stream.  */
836       stmt = pop_stmt_list (current_binding_level->statement_list);
837       stmt = c_build_bind_expr (input_location, block, stmt);
838       add_stmt (stmt);
839     }
840
841   leave_scope ();
842   if (functionbody)
843     {
844       /* The current function is being defined, so its DECL_INITIAL
845          should be error_mark_node.  */
846       gcc_assert (DECL_INITIAL (current_function_decl) == error_mark_node);
847       DECL_INITIAL (current_function_decl) = block ? block : subblocks;
848       if (subblocks)
849         {
850           if (FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
851             {
852               if (BLOCK_SUBBLOCKS (subblocks))
853                 BLOCK_OUTER_CURLY_BRACE_P (BLOCK_SUBBLOCKS (subblocks)) = 1;
854             }
855           else
856             BLOCK_OUTER_CURLY_BRACE_P (subblocks) = 1;
857         }
858     }
859   else if (block)
860     current_binding_level->blocks
861       = block_chainon (current_binding_level->blocks, block);
862
863   /* If we did not make a block for the level just exited,
864      any blocks made for inner levels
865      (since they cannot be recorded as subblocks in that level)
866      must be carried forward so they will later become subblocks
867      of something else.  */
868   else if (subblocks)
869     current_binding_level->blocks
870       = block_chainon (current_binding_level->blocks, subblocks);
871
872   /* Each and every BLOCK node created here in `poplevel' is important
873      (e.g. for proper debugging information) so if we created one
874      earlier, mark it as "used".  */
875   if (block)
876     TREE_USED (block) = 1;
877
878   /* All temporary bindings created for cleanups are popped silently.  */
879   if (kind == sk_cleanup)
880     goto restart;
881
882   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
883   return block;
884 }
885
886 /* Call wrapup_globals_declarations for the globals in NAMESPACE.  */
887 /* Diagnose odr-used extern inline variables without definitions
888    in the current TU.  */
889
890 int
891 wrapup_namespace_globals ()
892 {
893   if (vec<tree, va_gc> *statics = static_decls)
894     {
895       tree decl;
896       unsigned int i;
897       FOR_EACH_VEC_ELT (*statics, i, decl)
898         {
899           if (warn_unused_function
900               && TREE_CODE (decl) == FUNCTION_DECL
901               && DECL_INITIAL (decl) == 0
902               && DECL_EXTERNAL (decl)
903               && !TREE_PUBLIC (decl)
904               && !DECL_ARTIFICIAL (decl)
905               && !DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
906               && !TREE_NO_WARNING (decl))
907             warning_at (DECL_SOURCE_LOCATION (decl),
908                         OPT_Wunused_function,
909                         "%qF declared %<static%> but never defined", decl);
910
911           if (VAR_P (decl)
912               && DECL_EXTERNAL (decl)
913               && DECL_INLINE_VAR_P (decl)
914               && DECL_ODR_USED (decl))
915             error_at (DECL_SOURCE_LOCATION (decl),
916                       "odr-used inline variable %qD is not defined", decl);
917         }
918
919       /* Clear out the list, so we don't rescan next time.  */
920       static_decls = NULL;
921
922       /* Write out any globals that need to be output.  */
923       return wrapup_global_declarations (statics->address (),
924                                          statics->length ());
925     }
926   return 0;
927 }
928 \f
929 /* In C++, you don't have to write `struct S' to refer to `S'; you
930    can just use `S'.  We accomplish this by creating a TYPE_DECL as
931    if the user had written `typedef struct S S'.  Create and return
932    the TYPE_DECL for TYPE.  */
933
934 tree
935 create_implicit_typedef (tree name, tree type)
936 {
937   tree decl;
938
939   decl = build_decl (input_location, TYPE_DECL, name, type);
940   DECL_ARTIFICIAL (decl) = 1;
941   /* There are other implicit type declarations, like the one *within*
942      a class that allows you to write `S::S'.  We must distinguish
943      amongst these.  */
944   SET_DECL_IMPLICIT_TYPEDEF_P (decl);
945   TYPE_NAME (type) = decl;
946   TYPE_STUB_DECL (type) = decl;
947
948   return decl;
949 }
950
951 /* Remember a local name for name-mangling purposes.  */
952
953 static void
954 push_local_name (tree decl)
955 {
956   size_t i, nelts;
957   tree t, name;
958
959   timevar_start (TV_NAME_LOOKUP);
960
961   name = DECL_NAME (decl);
962
963   nelts = vec_safe_length (local_names);
964   for (i = 0; i < nelts; i++)
965     {
966       t = (*local_names)[i];
967       if (DECL_NAME (t) == name)
968         {
969           retrofit_lang_decl (decl);
970           DECL_LANG_SPECIFIC (decl)->u.base.u2sel = 1;
971           if (DECL_DISCRIMINATOR_SET_P (t))
972             DECL_DISCRIMINATOR (decl) = DECL_DISCRIMINATOR (t) + 1;
973           else
974             DECL_DISCRIMINATOR (decl) = 1;
975
976           (*local_names)[i] = decl;
977           timevar_stop (TV_NAME_LOOKUP);
978           return;
979         }
980     }
981
982   vec_safe_push (local_names, decl);
983   timevar_stop (TV_NAME_LOOKUP);
984 }
985 \f
986 /* Subroutine of duplicate_decls: return truthvalue of whether
987    or not types of these decls match.
988
989    For C++, we must compare the parameter list so that `int' can match
990    `int&' in a parameter position, but `int&' is not confused with
991    `const int&'.  */
992
993 int
994 decls_match (tree newdecl, tree olddecl, bool record_versions /* = true */)
995 {
996   int types_match;
997
998   if (newdecl == olddecl)
999     return 1;
1000
1001   if (TREE_CODE (newdecl) != TREE_CODE (olddecl))
1002     /* If the two DECLs are not even the same kind of thing, we're not
1003        interested in their types.  */
1004     return 0;
1005
1006   gcc_assert (DECL_P (newdecl));
1007
1008   if (TREE_CODE (newdecl) == FUNCTION_DECL)
1009     {
1010       tree f1 = TREE_TYPE (newdecl);
1011       tree f2 = TREE_TYPE (olddecl);
1012       tree p1 = TYPE_ARG_TYPES (f1);
1013       tree p2 = TYPE_ARG_TYPES (f2);
1014       tree r2;
1015
1016       /* Specializations of different templates are different functions
1017          even if they have the same type.  */
1018       tree t1 = (DECL_USE_TEMPLATE (newdecl)
1019                  ? DECL_TI_TEMPLATE (newdecl)
1020                  : NULL_TREE);
1021       tree t2 = (DECL_USE_TEMPLATE (olddecl)
1022                  ? DECL_TI_TEMPLATE (olddecl)
1023                  : NULL_TREE);
1024       if (t1 != t2)
1025         return 0;
1026
1027       if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1028           && ! (DECL_EXTERN_C_P (newdecl)
1029                 && DECL_EXTERN_C_P (olddecl)))
1030         return 0;
1031
1032       /* A new declaration doesn't match a built-in one unless it
1033          is also extern "C".  */
1034       if (DECL_IS_BUILTIN (olddecl)
1035           && DECL_EXTERN_C_P (olddecl) && !DECL_EXTERN_C_P (newdecl))
1036         return 0;
1037
1038       if (TREE_CODE (f1) != TREE_CODE (f2))
1039         return 0;
1040
1041       /* A declaration with deduced return type should use its pre-deduction
1042          type for declaration matching.  */
1043       r2 = fndecl_declared_return_type (olddecl);
1044
1045       if (same_type_p (TREE_TYPE (f1), r2))
1046         {
1047           if (!prototype_p (f2) && DECL_EXTERN_C_P (olddecl)
1048               && (DECL_BUILT_IN (olddecl)
1049 #ifndef NO_IMPLICIT_EXTERN_C
1050                   || (DECL_IN_SYSTEM_HEADER (newdecl) && !DECL_CLASS_SCOPE_P (newdecl))
1051                   || (DECL_IN_SYSTEM_HEADER (olddecl) && !DECL_CLASS_SCOPE_P (olddecl))
1052 #endif
1053               ))
1054             {
1055               types_match = self_promoting_args_p (p1);
1056               if (p1 == void_list_node)
1057                 TREE_TYPE (newdecl) = TREE_TYPE (olddecl);
1058             }
1059 #ifndef NO_IMPLICIT_EXTERN_C
1060           else if (!prototype_p (f1)
1061                    && (DECL_EXTERN_C_P (olddecl)
1062                        && DECL_IN_SYSTEM_HEADER (olddecl)
1063                        && !DECL_CLASS_SCOPE_P (olddecl))
1064                    && (DECL_EXTERN_C_P (newdecl)
1065                        && DECL_IN_SYSTEM_HEADER (newdecl)
1066                        && !DECL_CLASS_SCOPE_P (newdecl)))
1067             {
1068               types_match = self_promoting_args_p (p2);
1069               TREE_TYPE (newdecl) = TREE_TYPE (olddecl);
1070             }
1071 #endif
1072           else
1073             types_match =
1074               compparms (p1, p2)
1075               && type_memfn_rqual (f1) == type_memfn_rqual (f2)
1076               && (TYPE_ATTRIBUTES (TREE_TYPE (newdecl)) == NULL_TREE
1077                   || comp_type_attributes (TREE_TYPE (newdecl),
1078                                            TREE_TYPE (olddecl)) != 0);
1079         }
1080       else
1081         types_match = 0;
1082
1083       /* The decls dont match if they correspond to two different versions
1084          of the same function.   Disallow extern "C" functions to be
1085          versions for now.  */
1086       if (types_match
1087           && !DECL_EXTERN_C_P (newdecl)
1088           && !DECL_EXTERN_C_P (olddecl)
1089           && record_versions
1090           && maybe_version_functions (newdecl, olddecl,
1091                                       (!DECL_FUNCTION_VERSIONED (newdecl)
1092                                        || !DECL_FUNCTION_VERSIONED (olddecl))))
1093         return 0;
1094     }
1095   else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1096     {
1097       tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1098       tree newres = DECL_TEMPLATE_RESULT (newdecl);
1099
1100       if (TREE_CODE (newres) != TREE_CODE (oldres))
1101         return 0;
1102
1103       if (!comp_template_parms (DECL_TEMPLATE_PARMS (newdecl),
1104                                 DECL_TEMPLATE_PARMS (olddecl)))
1105         return 0;
1106
1107       if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == TYPE_DECL)
1108         types_match = (same_type_p (TREE_TYPE (oldres), TREE_TYPE (newres))
1109                        && equivalently_constrained (olddecl, newdecl));
1110       else
1111         // We don't need to check equivalently_constrained for variable and
1112         // function templates because we check it on the results.
1113         types_match = decls_match (oldres, newres);
1114     }
1115   else
1116     {
1117       /* Need to check scope for variable declaration (VAR_DECL).
1118          For typedef (TYPE_DECL), scope is ignored.  */
1119       if (VAR_P (newdecl)
1120           && CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1121           /* [dcl.link]
1122              Two declarations for an object with C language linkage
1123              with the same name (ignoring the namespace that qualify
1124              it) that appear in different namespace scopes refer to
1125              the same object.  */
1126           && !(DECL_EXTERN_C_P (olddecl) && DECL_EXTERN_C_P (newdecl)))
1127         return 0;
1128
1129       if (TREE_TYPE (newdecl) == error_mark_node)
1130         types_match = TREE_TYPE (olddecl) == error_mark_node;
1131       else if (TREE_TYPE (olddecl) == NULL_TREE)
1132         types_match = TREE_TYPE (newdecl) == NULL_TREE;
1133       else if (TREE_TYPE (newdecl) == NULL_TREE)
1134         types_match = 0;
1135       else
1136         types_match = comptypes (TREE_TYPE (newdecl),
1137                                  TREE_TYPE (olddecl),
1138                                  COMPARE_REDECLARATION);
1139     }
1140
1141   // Normal functions can be constrained, as can variable partial
1142   // specializations.
1143   if (types_match && VAR_OR_FUNCTION_DECL_P (newdecl))
1144     types_match = equivalently_constrained (newdecl, olddecl);
1145
1146   return types_match;
1147 }
1148
1149 /* NEWDECL and OLDDECL have identical signatures.  If they are
1150    different versions adjust them and return true.
1151    If RECORD is set to true, record function versions.  */
1152
1153 bool
1154 maybe_version_functions (tree newdecl, tree olddecl, bool record)
1155 {
1156   if (!targetm.target_option.function_versions (newdecl, olddecl))
1157     return false;
1158
1159   if (!DECL_FUNCTION_VERSIONED (olddecl))
1160     {
1161       DECL_FUNCTION_VERSIONED (olddecl) = 1;
1162       if (DECL_ASSEMBLER_NAME_SET_P (olddecl))
1163         mangle_decl (olddecl);
1164     }
1165
1166   if (!DECL_FUNCTION_VERSIONED (newdecl))
1167     {
1168       DECL_FUNCTION_VERSIONED (newdecl) = 1;
1169       if (DECL_ASSEMBLER_NAME_SET_P (newdecl))
1170         mangle_decl (newdecl);
1171     }
1172
1173   if (record)
1174     cgraph_node::record_function_versions (olddecl, newdecl);
1175
1176   return true;
1177 }
1178
1179 /* If NEWDECL is `static' and an `extern' was seen previously,
1180    warn about it.  OLDDECL is the previous declaration.
1181
1182    Note that this does not apply to the C++ case of declaring
1183    a variable `extern const' and then later `const'.
1184
1185    Don't complain about built-in functions, since they are beyond
1186    the user's control.  */
1187
1188 void
1189 warn_extern_redeclared_static (tree newdecl, tree olddecl)
1190 {
1191   if (TREE_CODE (newdecl) == TYPE_DECL
1192       || TREE_CODE (newdecl) == TEMPLATE_DECL
1193       || TREE_CODE (newdecl) == CONST_DECL
1194       || TREE_CODE (newdecl) == NAMESPACE_DECL)
1195     return;
1196
1197   /* Don't get confused by static member functions; that's a different
1198      use of `static'.  */
1199   if (TREE_CODE (newdecl) == FUNCTION_DECL
1200       && DECL_STATIC_FUNCTION_P (newdecl))
1201     return;
1202
1203   /* If the old declaration was `static', or the new one isn't, then
1204      everything is OK.  */
1205   if (DECL_THIS_STATIC (olddecl) || !DECL_THIS_STATIC (newdecl))
1206     return;
1207
1208   /* It's OK to declare a builtin function as `static'.  */
1209   if (TREE_CODE (olddecl) == FUNCTION_DECL
1210       && DECL_ARTIFICIAL (olddecl))
1211     return;
1212
1213   if (permerror (DECL_SOURCE_LOCATION (newdecl),
1214                  "%qD was declared %<extern%> and later %<static%>", newdecl))
1215     inform (DECL_SOURCE_LOCATION (olddecl),
1216             "previous declaration of %qD", olddecl);
1217 }
1218
1219 /* NEW_DECL is a redeclaration of OLD_DECL; both are functions or
1220    function templates.  If their exception specifications do not
1221    match, issue a diagnostic.  */
1222
1223 static void
1224 check_redeclaration_exception_specification (tree new_decl,
1225                                              tree old_decl)
1226 {
1227   tree new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1228   tree old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1229
1230   /* Two default specs are equivalent, don't force evaluation.  */
1231   if (UNEVALUATED_NOEXCEPT_SPEC_P (new_exceptions)
1232       && UNEVALUATED_NOEXCEPT_SPEC_P (old_exceptions))
1233     return;
1234
1235   maybe_instantiate_noexcept (new_decl);
1236   maybe_instantiate_noexcept (old_decl);
1237   new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1238   old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1239
1240   /* [except.spec]
1241
1242      If any declaration of a function has an exception-specification,
1243      all declarations, including the definition and an explicit
1244      specialization, of that function shall have an
1245      exception-specification with the same set of type-ids.  */
1246   if (! DECL_IS_BUILTIN (old_decl)
1247       && !comp_except_specs (new_exceptions, old_exceptions, ce_normal))
1248     {
1249       const char *const msg
1250         = G_("declaration of %qF has a different exception specifier");
1251       bool complained = true;
1252       location_t new_loc = DECL_SOURCE_LOCATION (new_decl);
1253       if (DECL_IN_SYSTEM_HEADER (old_decl))
1254         complained = pedwarn (new_loc, OPT_Wsystem_headers, msg, new_decl);
1255       else if (!flag_exceptions)
1256         /* We used to silently permit mismatched eh specs with
1257            -fno-exceptions, so make them a pedwarn now.  */
1258         complained = pedwarn (new_loc, OPT_Wpedantic, msg, new_decl);
1259       else
1260         error_at (new_loc, msg, new_decl);
1261       if (complained)
1262         inform (DECL_SOURCE_LOCATION (old_decl),
1263                 "from previous declaration %qF", old_decl);
1264     }
1265 }
1266
1267 /* Return true if OLD_DECL and NEW_DECL agree on constexprness.
1268    Otherwise issue diagnostics.  */
1269
1270 static bool
1271 validate_constexpr_redeclaration (tree old_decl, tree new_decl)
1272 {
1273   old_decl = STRIP_TEMPLATE (old_decl);
1274   new_decl = STRIP_TEMPLATE (new_decl);
1275   if (!VAR_OR_FUNCTION_DECL_P (old_decl)
1276       || !VAR_OR_FUNCTION_DECL_P (new_decl))
1277     return true;
1278   if (DECL_DECLARED_CONSTEXPR_P (old_decl)
1279       == DECL_DECLARED_CONSTEXPR_P (new_decl))
1280     return true;
1281   if (TREE_CODE (old_decl) == FUNCTION_DECL)
1282     {
1283       if (DECL_BUILT_IN (old_decl))
1284         {
1285           /* Hide a built-in declaration.  */
1286           DECL_DECLARED_CONSTEXPR_P (old_decl)
1287             = DECL_DECLARED_CONSTEXPR_P (new_decl);
1288           return true;
1289         }
1290       /* 7.1.5 [dcl.constexpr]
1291          Note: An explicit specialization can differ from the template
1292          declaration with respect to the constexpr specifier.  */
1293       if (! DECL_TEMPLATE_SPECIALIZATION (old_decl)
1294           && DECL_TEMPLATE_SPECIALIZATION (new_decl))
1295         return true;
1296
1297       error_at (DECL_SOURCE_LOCATION (new_decl),
1298                 "redeclaration %qD differs in %<constexpr%> "
1299                 "from previous declaration", new_decl);
1300       inform (DECL_SOURCE_LOCATION (old_decl),
1301               "previous declaration %qD", old_decl);
1302       return false;
1303     }
1304   return true;
1305 }
1306
1307 // If OLDDECL and NEWDECL are concept declarations with the same type
1308 // (i.e., and template parameters), but different requirements,
1309 // emit diagnostics and return true. Otherwise, return false.
1310 static inline bool
1311 check_concept_refinement (tree olddecl, tree newdecl)
1312 {
1313   if (!DECL_DECLARED_CONCEPT_P (olddecl) || !DECL_DECLARED_CONCEPT_P (newdecl))
1314     return false;
1315
1316   tree d1 = DECL_TEMPLATE_RESULT (olddecl);
1317   tree d2 = DECL_TEMPLATE_RESULT (newdecl);
1318   if (TREE_CODE (d1) != TREE_CODE (d2))
1319     return false;
1320
1321   tree t1 = TREE_TYPE (d1);
1322   tree t2 = TREE_TYPE (d2);
1323   if (TREE_CODE (d1) == FUNCTION_DECL)
1324     {
1325       if (compparms (TYPE_ARG_TYPES (t1), TYPE_ARG_TYPES (t2))
1326           && comp_template_parms (DECL_TEMPLATE_PARMS (olddecl),
1327                                   DECL_TEMPLATE_PARMS (newdecl))
1328           && !equivalently_constrained (olddecl, newdecl))
1329         {
1330           error ("cannot specialize concept %q#D", olddecl);
1331           return true;
1332         }
1333     }
1334   return false;
1335 }
1336
1337 /* DECL is a redeclaration of a function or function template.  If
1338    it does have default arguments issue a diagnostic.  Note: this
1339    function is used to enforce the requirements in C++11 8.3.6 about
1340    no default arguments in redeclarations.  */
1341
1342 static void
1343 check_redeclaration_no_default_args (tree decl)
1344 {
1345   gcc_assert (DECL_DECLARES_FUNCTION_P (decl));
1346
1347   for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
1348        t && t != void_list_node; t = TREE_CHAIN (t))
1349     if (TREE_PURPOSE (t))
1350       {
1351         permerror (DECL_SOURCE_LOCATION (decl),
1352                    "redeclaration of %q#D may not have default "
1353                    "arguments", decl);
1354         return;
1355       }
1356 }
1357
1358 #define GNU_INLINE_P(fn) (DECL_DECLARED_INLINE_P (fn)                   \
1359                           && lookup_attribute ("gnu_inline",            \
1360                                                DECL_ATTRIBUTES (fn)))
1361
1362 /* If NEWDECL is a redeclaration of OLDDECL, merge the declarations.
1363    If the redeclaration is invalid, a diagnostic is issued, and the
1364    error_mark_node is returned.  Otherwise, OLDDECL is returned.
1365
1366    If NEWDECL is not a redeclaration of OLDDECL, NULL_TREE is
1367    returned.
1368
1369    NEWDECL_IS_FRIEND is true if NEWDECL was declared as a friend.  */
1370
1371 tree
1372 duplicate_decls (tree newdecl, tree olddecl, bool newdecl_is_friend)
1373 {
1374   unsigned olddecl_uid = DECL_UID (olddecl);
1375   int olddecl_friend = 0, types_match = 0, hidden_friend = 0;
1376   int new_defines_function = 0;
1377   tree new_template_info;
1378
1379   if (newdecl == olddecl)
1380     return olddecl;
1381
1382   types_match = decls_match (newdecl, olddecl);
1383
1384   /* If either the type of the new decl or the type of the old decl is an
1385      error_mark_node, then that implies that we have already issued an
1386      error (earlier) for some bogus type specification, and in that case,
1387      it is rather pointless to harass the user with yet more error message
1388      about the same declaration, so just pretend the types match here.  */
1389   if (TREE_TYPE (newdecl) == error_mark_node
1390       || TREE_TYPE (olddecl) == error_mark_node)
1391     return error_mark_node;
1392
1393   if (UDLIT_OPER_P (DECL_NAME (newdecl))
1394       && UDLIT_OPER_P (DECL_NAME (olddecl)))
1395     {
1396       if (TREE_CODE (newdecl) == TEMPLATE_DECL
1397           && TREE_CODE (olddecl) != TEMPLATE_DECL
1398           && check_raw_literal_operator (olddecl))
1399         error ("literal operator template %q+D conflicts with"
1400                " raw literal operator %qD", newdecl, olddecl);
1401       else if (TREE_CODE (newdecl) != TEMPLATE_DECL
1402                && TREE_CODE (olddecl) == TEMPLATE_DECL
1403                && check_raw_literal_operator (newdecl))
1404         error ("raw literal operator %q+D conflicts with"
1405                " literal operator template %qD", newdecl, olddecl);
1406     }
1407
1408   if (DECL_P (olddecl)
1409       && TREE_CODE (newdecl) == FUNCTION_DECL
1410       && TREE_CODE (olddecl) == FUNCTION_DECL
1411       && diagnose_mismatched_attributes (olddecl, newdecl))
1412     {
1413       if (DECL_INITIAL (olddecl))
1414         inform (DECL_SOURCE_LOCATION (olddecl),
1415                 "previous definition of %qD was here", olddecl);
1416       else
1417         inform (DECL_SOURCE_LOCATION (olddecl),
1418                 "previous declaration of %qD was here", olddecl);
1419     }
1420
1421   /* Check for redeclaration and other discrepancies.  */
1422   if (TREE_CODE (olddecl) == FUNCTION_DECL
1423       && DECL_ARTIFICIAL (olddecl))
1424     {
1425       gcc_assert (!DECL_HIDDEN_FRIEND_P (olddecl));
1426       if (TREE_CODE (newdecl) != FUNCTION_DECL)
1427         {
1428           /* Avoid warnings redeclaring built-ins which have not been
1429              explicitly declared.  */
1430           if (DECL_ANTICIPATED (olddecl))
1431             {
1432               if (TREE_PUBLIC (newdecl)
1433                   && CP_DECL_CONTEXT (newdecl) == global_namespace)
1434                 warning_at (DECL_SOURCE_LOCATION (newdecl),
1435                             OPT_Wbuiltin_declaration_mismatch,
1436                             "built-in function %qD declared as non-function",
1437                             newdecl);
1438               return NULL_TREE;
1439             }
1440
1441           /* If you declare a built-in or predefined function name as static,
1442              the old definition is overridden, but optionally warn this was a
1443              bad choice of name.  */
1444           if (! TREE_PUBLIC (newdecl))
1445             {
1446               warning (OPT_Wshadow, 
1447                        DECL_BUILT_IN (olddecl)
1448                        ? G_("shadowing built-in function %q#D")
1449                        : G_("shadowing library function %q#D"), olddecl);
1450               /* Discard the old built-in function.  */
1451               return NULL_TREE;
1452             }
1453           /* If the built-in is not ansi, then programs can override
1454              it even globally without an error.  */
1455           else if (! DECL_BUILT_IN (olddecl))
1456             warning_at (DECL_SOURCE_LOCATION (newdecl), 0,
1457                         "library function %q#D redeclared as non-function %q#D",
1458                         olddecl, newdecl);
1459           else
1460             error ("declaration of %q+#D conflicts with built-in "
1461                    "declaration %q#D", newdecl, olddecl);
1462           return NULL_TREE;
1463         }
1464       else if (DECL_OMP_DECLARE_REDUCTION_P (olddecl))
1465         {
1466           gcc_assert (DECL_OMP_DECLARE_REDUCTION_P (newdecl));
1467           error_at (DECL_SOURCE_LOCATION (newdecl),
1468                     "redeclaration of %<pragma omp declare reduction%>");
1469           inform (DECL_SOURCE_LOCATION (olddecl),
1470                   "previous %<pragma omp declare reduction%> declaration");
1471           return error_mark_node;
1472         }
1473       else if (!types_match)
1474         {
1475           /* Avoid warnings redeclaring built-ins which have not been
1476              explicitly declared.  */
1477           if (DECL_ANTICIPATED (olddecl))
1478             {
1479               tree t1, t2;
1480
1481               /* A new declaration doesn't match a built-in one unless it
1482                  is also extern "C".  */
1483               gcc_assert (DECL_IS_BUILTIN (olddecl));
1484               gcc_assert (DECL_EXTERN_C_P (olddecl));
1485               if (!DECL_EXTERN_C_P (newdecl))
1486                 return NULL_TREE;
1487
1488               for (t1 = TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1489                    t2 = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1490                    t1 || t2;
1491                    t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1492                 {
1493                   if (!t1 || !t2)
1494                     break;
1495                   /* FILE, tm types are not known at the time
1496                      we create the builtins.  */
1497                   for (unsigned i = 0;
1498                        i < sizeof (builtin_structptr_types)
1499                            / sizeof (builtin_structptr_type);
1500                        ++i)
1501                     if (TREE_VALUE (t2) == builtin_structptr_types[i].node)
1502                       {
1503                         tree t = TREE_VALUE (t1);
1504
1505                         if (TYPE_PTR_P (t)
1506                             && TYPE_IDENTIFIER (TREE_TYPE (t))
1507                             == get_identifier (builtin_structptr_types[i].str)
1508                             && compparms (TREE_CHAIN (t1), TREE_CHAIN (t2)))
1509                           {
1510                             tree oldargs = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1511
1512                             TYPE_ARG_TYPES (TREE_TYPE (olddecl))
1513                               = TYPE_ARG_TYPES (TREE_TYPE (newdecl));
1514                             types_match = decls_match (newdecl, olddecl);
1515                             if (types_match)
1516                               return duplicate_decls (newdecl, olddecl,
1517                                                       newdecl_is_friend);
1518                             TYPE_ARG_TYPES (TREE_TYPE (olddecl)) = oldargs;
1519                           }
1520                         goto next_arg;
1521                       }
1522
1523                   if (! same_type_p (TREE_VALUE (t1), TREE_VALUE (t2)))
1524                     break;
1525 next_arg:;
1526                 }
1527
1528               warning_at (DECL_SOURCE_LOCATION (newdecl),
1529                           OPT_Wbuiltin_declaration_mismatch,
1530                           "declaration of %q#D conflicts with built-in "
1531                           "declaration %q#D", newdecl, olddecl);
1532             }
1533           else if ((DECL_EXTERN_C_P (newdecl)
1534                     && DECL_EXTERN_C_P (olddecl))
1535                    || compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1536                                  TYPE_ARG_TYPES (TREE_TYPE (olddecl))))
1537             {
1538               /* A near match; override the builtin.  */
1539
1540               if (TREE_PUBLIC (newdecl))
1541                 warning_at (DECL_SOURCE_LOCATION (newdecl),
1542                             OPT_Wbuiltin_declaration_mismatch,
1543                             "new declaration %q#D ambiguates built-in "
1544                             "declaration %q#D", newdecl, olddecl);
1545               else
1546                 warning (OPT_Wshadow, 
1547                          DECL_BUILT_IN (olddecl)
1548                          ? G_("shadowing built-in function %q#D")
1549                          : G_("shadowing library function %q#D"), olddecl);
1550             }
1551           else
1552             /* Discard the old built-in function.  */
1553             return NULL_TREE;
1554
1555           /* Replace the old RTL to avoid problems with inlining.  */
1556           COPY_DECL_RTL (newdecl, olddecl);
1557         }
1558       /* Even if the types match, prefer the new declarations type for
1559          built-ins which have not been explicitly declared, for
1560          exception lists, etc...  */
1561       else if (DECL_IS_BUILTIN (olddecl))
1562         {
1563           tree type = TREE_TYPE (newdecl);
1564           tree attribs = (*targetm.merge_type_attributes)
1565             (TREE_TYPE (olddecl), type);
1566
1567           type = cp_build_type_attribute_variant (type, attribs);
1568           TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = type;
1569         }
1570
1571       /* If a function is explicitly declared "throw ()", propagate that to
1572          the corresponding builtin.  */
1573       if (DECL_BUILT_IN_CLASS (olddecl) == BUILT_IN_NORMAL
1574           && DECL_ANTICIPATED (olddecl)
1575           && TREE_NOTHROW (newdecl)
1576           && !TREE_NOTHROW (olddecl))
1577         {
1578           enum built_in_function fncode = DECL_FUNCTION_CODE (olddecl);
1579           tree tmpdecl = builtin_decl_explicit (fncode);
1580           if (tmpdecl && tmpdecl != olddecl && types_match)
1581             TREE_NOTHROW (tmpdecl)  = 1;
1582         }
1583
1584       /* Whether or not the builtin can throw exceptions has no
1585          bearing on this declarator.  */
1586       TREE_NOTHROW (olddecl) = 0;
1587
1588       if (DECL_THIS_STATIC (newdecl) && !DECL_THIS_STATIC (olddecl))
1589         {
1590           /* If a builtin function is redeclared as `static', merge
1591              the declarations, but make the original one static.  */
1592           DECL_THIS_STATIC (olddecl) = 1;
1593           TREE_PUBLIC (olddecl) = 0;
1594
1595           /* Make the old declaration consistent with the new one so
1596              that all remnants of the builtin-ness of this function
1597              will be banished.  */
1598           SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
1599           COPY_DECL_RTL (newdecl, olddecl);
1600         }
1601     }
1602   else if (TREE_CODE (olddecl) != TREE_CODE (newdecl))
1603     {
1604       /* C++ Standard, 3.3, clause 4:
1605          "[Note: a namespace name or a class template name must be unique
1606          in its declarative region (7.3.2, clause 14). ]"  */
1607       if (TREE_CODE (olddecl) != NAMESPACE_DECL
1608           && TREE_CODE (newdecl) != NAMESPACE_DECL
1609           && (TREE_CODE (olddecl) != TEMPLATE_DECL
1610               || TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)) != TYPE_DECL)
1611           && (TREE_CODE (newdecl) != TEMPLATE_DECL
1612               || TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) != TYPE_DECL))
1613         {
1614           if ((TREE_CODE (olddecl) == TYPE_DECL && DECL_ARTIFICIAL (olddecl)
1615                && TREE_CODE (newdecl) != TYPE_DECL)
1616               || (TREE_CODE (newdecl) == TYPE_DECL && DECL_ARTIFICIAL (newdecl)
1617                   && TREE_CODE (olddecl) != TYPE_DECL))
1618             {
1619               /* We do nothing special here, because C++ does such nasty
1620                  things with TYPE_DECLs.  Instead, just let the TYPE_DECL
1621                  get shadowed, and know that if we need to find a TYPE_DECL
1622                  for a given name, we can look in the IDENTIFIER_TYPE_VALUE
1623                  slot of the identifier.  */
1624               return NULL_TREE;
1625             }
1626             
1627             if ((TREE_CODE (newdecl) == FUNCTION_DECL
1628                  && DECL_FUNCTION_TEMPLATE_P (olddecl))
1629                 || (TREE_CODE (olddecl) == FUNCTION_DECL
1630                     && DECL_FUNCTION_TEMPLATE_P (newdecl)))
1631               return NULL_TREE;
1632         }
1633
1634       error ("%q#D redeclared as different kind of symbol", newdecl);
1635       if (TREE_CODE (olddecl) == TREE_LIST)
1636         olddecl = TREE_VALUE (olddecl);
1637       inform (DECL_SOURCE_LOCATION (olddecl),
1638               "previous declaration %q#D", olddecl);
1639
1640       return error_mark_node;
1641     }
1642   else if (!types_match)
1643     {
1644       if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl))
1645         /* These are certainly not duplicate declarations; they're
1646            from different scopes.  */
1647         return NULL_TREE;
1648
1649       if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1650         {
1651           /* The name of a class template may not be declared to refer to
1652              any other template, class, function, object, namespace, value,
1653              or type in the same scope.  */
1654           if (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)) == TYPE_DECL
1655               || TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == TYPE_DECL)
1656             {
1657               error ("conflicting declaration of template %q+#D", newdecl);
1658               inform (DECL_SOURCE_LOCATION (olddecl),
1659                       "previous declaration %q#D", olddecl);
1660               return error_mark_node;
1661             }
1662           else if (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)) == FUNCTION_DECL
1663                    && TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == FUNCTION_DECL
1664                    && compparms (TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (olddecl))),
1665                                  TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (newdecl))))
1666                    && comp_template_parms (DECL_TEMPLATE_PARMS (newdecl),
1667                                            DECL_TEMPLATE_PARMS (olddecl))
1668                    /* Template functions can be disambiguated by
1669                       return type.  */
1670                    && same_type_p (TREE_TYPE (TREE_TYPE (newdecl)),
1671                                    TREE_TYPE (TREE_TYPE (olddecl)))
1672                    // Template functions can also be disambiguated by
1673                    // constraints.
1674                    && equivalently_constrained (olddecl, newdecl))
1675             {
1676               error ("ambiguating new declaration %q+#D", newdecl);
1677               inform (DECL_SOURCE_LOCATION (olddecl),
1678                       "old declaration %q#D", olddecl);
1679             }
1680           else if (check_concept_refinement (olddecl, newdecl))
1681             return error_mark_node;
1682           return NULL_TREE;
1683         }
1684       if (TREE_CODE (newdecl) == FUNCTION_DECL)
1685         {
1686           if (DECL_EXTERN_C_P (newdecl) && DECL_EXTERN_C_P (olddecl))
1687             {
1688               error ("conflicting declaration of C function %q+#D",
1689                      newdecl);
1690               inform (DECL_SOURCE_LOCATION (olddecl),
1691                       "previous declaration %q#D", olddecl);
1692               return NULL_TREE;
1693             }
1694           /* For function versions, params and types match, but they
1695              are not ambiguous.  */
1696           else if ((!DECL_FUNCTION_VERSIONED (newdecl)
1697                     && !DECL_FUNCTION_VERSIONED (olddecl))
1698                    // The functions have the same parameter types.
1699                    && compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1700                                  TYPE_ARG_TYPES (TREE_TYPE (olddecl)))
1701                    // And the same constraints.
1702                    && equivalently_constrained (newdecl, olddecl))
1703             {
1704               error ("ambiguating new declaration of %q+#D", newdecl);
1705               inform (DECL_SOURCE_LOCATION (olddecl),
1706                       "old declaration %q#D", olddecl);
1707               return error_mark_node;
1708             }
1709           else
1710             return NULL_TREE;
1711         }
1712       else
1713         {
1714           error ("conflicting declaration %q+#D", newdecl);
1715           inform (DECL_SOURCE_LOCATION (olddecl),
1716                   "previous declaration as %q#D", olddecl);
1717           return error_mark_node;
1718         }
1719     }
1720   else if (TREE_CODE (newdecl) == FUNCTION_DECL
1721             && ((DECL_TEMPLATE_SPECIALIZATION (olddecl)
1722                  && (!DECL_TEMPLATE_INFO (newdecl)
1723                      || (DECL_TI_TEMPLATE (newdecl)
1724                          != DECL_TI_TEMPLATE (olddecl))))
1725                 || (DECL_TEMPLATE_SPECIALIZATION (newdecl)
1726                     && (!DECL_TEMPLATE_INFO (olddecl)
1727                         || (DECL_TI_TEMPLATE (olddecl)
1728                             != DECL_TI_TEMPLATE (newdecl))))))
1729     /* It's OK to have a template specialization and a non-template
1730        with the same type, or to have specializations of two
1731        different templates with the same type.  Note that if one is a
1732        specialization, and the other is an instantiation of the same
1733        template, that we do not exit at this point.  That situation
1734        can occur if we instantiate a template class, and then
1735        specialize one of its methods.  This situation is valid, but
1736        the declarations must be merged in the usual way.  */
1737     return NULL_TREE;
1738   else if (TREE_CODE (newdecl) == FUNCTION_DECL
1739            && ((DECL_TEMPLATE_INSTANTIATION (olddecl)
1740                 && !DECL_USE_TEMPLATE (newdecl))
1741                || (DECL_TEMPLATE_INSTANTIATION (newdecl)
1742                    && !DECL_USE_TEMPLATE (olddecl))))
1743     /* One of the declarations is a template instantiation, and the
1744        other is not a template at all.  That's OK.  */
1745     return NULL_TREE;
1746   else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
1747     {
1748       /* In [namespace.alias] we have:
1749
1750            In a declarative region, a namespace-alias-definition can be
1751            used to redefine a namespace-alias declared in that declarative
1752            region to refer only to the namespace to which it already
1753            refers.
1754
1755          Therefore, if we encounter a second alias directive for the same
1756          alias, we can just ignore the second directive.  */
1757       if (DECL_NAMESPACE_ALIAS (newdecl)
1758           && (DECL_NAMESPACE_ALIAS (newdecl)
1759               == DECL_NAMESPACE_ALIAS (olddecl)))
1760         return olddecl;
1761
1762       /* Leave it to update_binding to merge or report error.  */
1763       return NULL_TREE;
1764     }
1765   else
1766     {
1767       const char *errmsg = redeclaration_error_message (newdecl, olddecl);
1768       if (errmsg)
1769         {
1770           error_at (DECL_SOURCE_LOCATION (newdecl), errmsg, newdecl);
1771           if (DECL_NAME (olddecl) != NULL_TREE)
1772             inform (DECL_SOURCE_LOCATION (olddecl),
1773                     (DECL_INITIAL (olddecl) && namespace_bindings_p ())
1774                     ? G_("%q#D previously defined here")
1775                     : G_("%q#D previously declared here"), olddecl);
1776           return error_mark_node;
1777         }
1778       else if (TREE_CODE (olddecl) == FUNCTION_DECL
1779                && DECL_INITIAL (olddecl) != NULL_TREE
1780                && !prototype_p (TREE_TYPE (olddecl))
1781                && prototype_p (TREE_TYPE (newdecl)))
1782         {
1783           /* Prototype decl follows defn w/o prototype.  */
1784           if (warning_at (DECL_SOURCE_LOCATION (newdecl), 0,
1785                           "prototype specified for %q#D", newdecl))
1786             inform (DECL_SOURCE_LOCATION (olddecl),
1787                     "previous non-prototype definition here");
1788         }
1789       else if (VAR_OR_FUNCTION_DECL_P (olddecl)
1790                && DECL_LANGUAGE (newdecl) != DECL_LANGUAGE (olddecl))
1791         {
1792           /* [dcl.link]
1793              If two declarations of the same function or object
1794              specify different linkage-specifications ..., the program
1795              is ill-formed.... Except for functions with C++ linkage,
1796              a function declaration without a linkage specification
1797              shall not precede the first linkage specification for
1798              that function.  A function can be declared without a
1799              linkage specification after an explicit linkage
1800              specification has been seen; the linkage explicitly
1801              specified in the earlier declaration is not affected by
1802              such a function declaration.
1803
1804              DR 563 raises the question why the restrictions on
1805              functions should not also apply to objects.  Older
1806              versions of G++ silently ignore the linkage-specification
1807              for this example:
1808
1809                namespace N { 
1810                  extern int i;
1811                  extern "C" int i;
1812                }
1813
1814              which is clearly wrong.  Therefore, we now treat objects
1815              like functions.  */
1816           if (current_lang_depth () == 0)
1817             {
1818               /* There is no explicit linkage-specification, so we use
1819                  the linkage from the previous declaration.  */
1820               retrofit_lang_decl (newdecl);
1821               SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
1822             }
1823           else
1824             {
1825               error ("conflicting declaration of %q+#D with %qL linkage",
1826                      newdecl, DECL_LANGUAGE (newdecl));
1827               inform (DECL_SOURCE_LOCATION (olddecl),
1828                       "previous declaration with %qL linkage",
1829                       DECL_LANGUAGE (olddecl));
1830             }
1831         }
1832
1833       if (DECL_LANG_SPECIFIC (olddecl) && DECL_USE_TEMPLATE (olddecl))
1834         ;
1835       else if (TREE_CODE (olddecl) == FUNCTION_DECL)
1836         {
1837           /* Note: free functions, as TEMPLATE_DECLs, are handled below.  */
1838           if (DECL_FUNCTION_MEMBER_P (olddecl)
1839               && (/* grokfndecl passes member function templates too
1840                      as FUNCTION_DECLs.  */
1841                   DECL_TEMPLATE_INFO (olddecl)
1842                   /* C++11 8.3.6/6.
1843                      Default arguments for a member function of a class
1844                      template shall be specified on the initial declaration
1845                      of the member function within the class template.  */
1846                   || CLASSTYPE_TEMPLATE_INFO (CP_DECL_CONTEXT (olddecl))))
1847             check_redeclaration_no_default_args (newdecl);
1848           else
1849             {
1850               tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl);
1851               tree t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1852               int i = 1;
1853
1854               for (; t1 && t1 != void_list_node;
1855                    t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2), i++)
1856                 if (TREE_PURPOSE (t1) && TREE_PURPOSE (t2))
1857                   {
1858                     if (simple_cst_equal (TREE_PURPOSE (t1),
1859                                           TREE_PURPOSE (t2)) == 1)
1860                       {
1861                         if (permerror (input_location,
1862                                        "default argument given for parameter "
1863                                        "%d of %q#D", i, newdecl))
1864                           inform (DECL_SOURCE_LOCATION (olddecl),
1865                                   "previous specification in %q#D here",
1866                                   olddecl);
1867                       }
1868                     else
1869                       {
1870                         error ("default argument given for parameter %d "
1871                                "of %q#D", i, newdecl);
1872                         inform (DECL_SOURCE_LOCATION (olddecl),
1873                                 "previous specification in %q#D here",
1874                                 olddecl);
1875                       }
1876                   }
1877             }
1878         }
1879     }
1880
1881   /* Do not merge an implicit typedef with an explicit one.  In:
1882
1883        class A;
1884        ...
1885        typedef class A A __attribute__ ((foo));
1886
1887      the attribute should apply only to the typedef.  */
1888   if (TREE_CODE (olddecl) == TYPE_DECL
1889       && (DECL_IMPLICIT_TYPEDEF_P (olddecl)
1890           || DECL_IMPLICIT_TYPEDEF_P (newdecl)))
1891     return NULL_TREE;
1892
1893   /* If new decl is `static' and an `extern' was seen previously,
1894      warn about it.  */
1895   warn_extern_redeclared_static (newdecl, olddecl);
1896
1897   if (!validate_constexpr_redeclaration (olddecl, newdecl))
1898     return error_mark_node;
1899
1900   /* We have committed to returning 1 at this point.  */
1901   if (TREE_CODE (newdecl) == FUNCTION_DECL)
1902     {
1903       /* Now that functions must hold information normally held
1904          by field decls, there is extra work to do so that
1905          declaration information does not get destroyed during
1906          definition.  */
1907       if (DECL_VINDEX (olddecl))
1908         DECL_VINDEX (newdecl) = DECL_VINDEX (olddecl);
1909       if (DECL_CONTEXT (olddecl))
1910         DECL_CONTEXT (newdecl) = DECL_CONTEXT (olddecl);
1911       DECL_STATIC_CONSTRUCTOR (newdecl) |= DECL_STATIC_CONSTRUCTOR (olddecl);
1912       DECL_STATIC_DESTRUCTOR (newdecl) |= DECL_STATIC_DESTRUCTOR (olddecl);
1913       DECL_PURE_VIRTUAL_P (newdecl) |= DECL_PURE_VIRTUAL_P (olddecl);
1914       DECL_VIRTUAL_P (newdecl) |= DECL_VIRTUAL_P (olddecl);
1915       DECL_INVALID_OVERRIDER_P (newdecl) |= DECL_INVALID_OVERRIDER_P (olddecl);
1916       DECL_FINAL_P (newdecl) |= DECL_FINAL_P (olddecl);
1917       DECL_OVERRIDE_P (newdecl) |= DECL_OVERRIDE_P (olddecl);
1918       DECL_THIS_STATIC (newdecl) |= DECL_THIS_STATIC (olddecl);
1919       if (DECL_OVERLOADED_OPERATOR_P (olddecl))
1920         DECL_OVERLOADED_OPERATOR_CODE_RAW (newdecl)
1921           = DECL_OVERLOADED_OPERATOR_CODE_RAW (olddecl);
1922       new_defines_function = DECL_INITIAL (newdecl) != NULL_TREE;
1923
1924       /* Optionally warn about more than one declaration for the same
1925          name, but don't warn about a function declaration followed by a
1926          definition.  */
1927       if (warn_redundant_decls && ! DECL_ARTIFICIAL (olddecl)
1928           && !(new_defines_function && DECL_INITIAL (olddecl) == NULL_TREE)
1929           /* Don't warn about extern decl followed by definition.  */
1930           && !(DECL_EXTERNAL (olddecl) && ! DECL_EXTERNAL (newdecl))
1931           /* Don't warn about friends, let add_friend take care of it.  */
1932           && ! (newdecl_is_friend || DECL_FRIEND_P (olddecl))
1933           /* Don't warn about declaration followed by specialization.  */
1934           && (! DECL_TEMPLATE_SPECIALIZATION (newdecl)
1935               || DECL_TEMPLATE_SPECIALIZATION (olddecl)))
1936         {
1937           if (warning_at (DECL_SOURCE_LOCATION (newdecl),
1938                           OPT_Wredundant_decls,
1939                           "redundant redeclaration of %qD in same scope",
1940                           newdecl))
1941             inform (DECL_SOURCE_LOCATION (olddecl),
1942                     "previous declaration of %qD", olddecl);
1943         }
1944
1945       if (!(DECL_TEMPLATE_INSTANTIATION (olddecl)
1946             && DECL_TEMPLATE_SPECIALIZATION (newdecl)))
1947         {
1948           if (DECL_DELETED_FN (newdecl))
1949             {
1950               error ("deleted definition of %q+D", newdecl);
1951               inform (DECL_SOURCE_LOCATION (olddecl),
1952                       "previous declaration of %qD", olddecl);
1953             }
1954           DECL_DELETED_FN (newdecl) |= DECL_DELETED_FN (olddecl);
1955         }
1956     }
1957
1958   /* Deal with C++: must preserve virtual function table size.  */
1959   if (TREE_CODE (olddecl) == TYPE_DECL)
1960     {
1961       tree newtype = TREE_TYPE (newdecl);
1962       tree oldtype = TREE_TYPE (olddecl);
1963
1964       if (newtype != error_mark_node && oldtype != error_mark_node
1965           && TYPE_LANG_SPECIFIC (newtype) && TYPE_LANG_SPECIFIC (oldtype))
1966         CLASSTYPE_FRIEND_CLASSES (newtype)
1967           = CLASSTYPE_FRIEND_CLASSES (oldtype);
1968
1969       DECL_ORIGINAL_TYPE (newdecl) = DECL_ORIGINAL_TYPE (olddecl);
1970     }
1971
1972   /* Copy all the DECL_... slots specified in the new decl
1973      except for any that we copy here from the old type.  */
1974   DECL_ATTRIBUTES (newdecl)
1975     = (*targetm.merge_decl_attributes) (olddecl, newdecl);
1976
1977   if (DECL_DECLARES_FUNCTION_P (olddecl) && DECL_DECLARES_FUNCTION_P (newdecl))
1978     {
1979       olddecl_friend = DECL_FRIEND_P (olddecl);
1980       hidden_friend = (DECL_ANTICIPATED (olddecl)
1981                        && DECL_HIDDEN_FRIEND_P (olddecl)
1982                        && newdecl_is_friend);
1983       if (!hidden_friend)
1984         {
1985           DECL_ANTICIPATED (olddecl) = 0;
1986           DECL_HIDDEN_FRIEND_P (olddecl) = 0;
1987         }
1988     }
1989
1990   if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1991     {
1992       tree old_result;
1993       tree new_result;
1994       old_result = DECL_TEMPLATE_RESULT (olddecl);
1995       new_result = DECL_TEMPLATE_RESULT (newdecl);
1996       TREE_TYPE (olddecl) = TREE_TYPE (old_result);
1997       DECL_TEMPLATE_SPECIALIZATIONS (olddecl)
1998         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (olddecl),
1999                    DECL_TEMPLATE_SPECIALIZATIONS (newdecl));
2000
2001       DECL_ATTRIBUTES (old_result)
2002         = (*targetm.merge_decl_attributes) (old_result, new_result);
2003
2004       if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2005         {
2006           /* Per C++11 8.3.6/4, default arguments cannot be added in later
2007              declarations of a function template.  */
2008           if (DECL_SOURCE_LOCATION (newdecl)
2009               != DECL_SOURCE_LOCATION (olddecl))
2010             check_redeclaration_no_default_args (newdecl);
2011
2012           check_default_args (newdecl);
2013
2014           if (GNU_INLINE_P (old_result) != GNU_INLINE_P (new_result)
2015               && DECL_INITIAL (new_result))
2016             {
2017               if (DECL_INITIAL (old_result))
2018                 DECL_UNINLINABLE (old_result) = 1;
2019               else
2020                 DECL_UNINLINABLE (old_result) = DECL_UNINLINABLE (new_result);
2021               DECL_EXTERNAL (old_result) = DECL_EXTERNAL (new_result);
2022               DECL_NOT_REALLY_EXTERN (old_result)
2023                 = DECL_NOT_REALLY_EXTERN (new_result);
2024               DECL_INTERFACE_KNOWN (old_result)
2025                 = DECL_INTERFACE_KNOWN (new_result);
2026               DECL_DECLARED_INLINE_P (old_result)
2027                 = DECL_DECLARED_INLINE_P (new_result);
2028               DECL_DISREGARD_INLINE_LIMITS (old_result)
2029                 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2030
2031             }
2032           else
2033             {
2034               DECL_DECLARED_INLINE_P (old_result)
2035                 |= DECL_DECLARED_INLINE_P (new_result);
2036               DECL_DISREGARD_INLINE_LIMITS (old_result)
2037                 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2038               check_redeclaration_exception_specification (newdecl, olddecl);
2039             }
2040         }
2041
2042       /* If the new declaration is a definition, update the file and
2043          line information on the declaration, and also make
2044          the old declaration the same definition.  */
2045       if (DECL_INITIAL (new_result) != NULL_TREE)
2046         {
2047           DECL_SOURCE_LOCATION (olddecl)
2048             = DECL_SOURCE_LOCATION (old_result)
2049             = DECL_SOURCE_LOCATION (newdecl);
2050           DECL_INITIAL (old_result) = DECL_INITIAL (new_result);
2051           if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2052             {
2053               tree parm;
2054               DECL_ARGUMENTS (old_result)
2055                 = DECL_ARGUMENTS (new_result);
2056               for (parm = DECL_ARGUMENTS (old_result); parm;
2057                    parm = DECL_CHAIN (parm))
2058                 DECL_CONTEXT (parm) = old_result;
2059             }
2060         }
2061
2062       return olddecl;
2063     }
2064
2065   if (types_match)
2066     {
2067       if (TREE_CODE (newdecl) == FUNCTION_DECL)
2068         check_redeclaration_exception_specification (newdecl, olddecl);
2069
2070       /* Automatically handles default parameters.  */
2071       tree oldtype = TREE_TYPE (olddecl);
2072       tree newtype;
2073
2074       /* For typedefs use the old type, as the new type's DECL_NAME points
2075          at newdecl, which will be ggc_freed.  */
2076       if (TREE_CODE (newdecl) == TYPE_DECL)
2077         {
2078           /* But NEWTYPE might have an attribute, honor that.  */
2079           tree tem = TREE_TYPE (newdecl);
2080           newtype = oldtype;
2081
2082           if (TYPE_USER_ALIGN (tem))
2083             {
2084               if (TYPE_ALIGN (tem) > TYPE_ALIGN (newtype))
2085                 SET_TYPE_ALIGN (newtype, TYPE_ALIGN (tem));
2086               TYPE_USER_ALIGN (newtype) = true;
2087             }
2088
2089           /* And remove the new type from the variants list.  */
2090           if (TYPE_NAME (TREE_TYPE (newdecl)) == newdecl)
2091             {
2092               tree remove = TREE_TYPE (newdecl);
2093               for (tree t = TYPE_MAIN_VARIANT (remove); ;
2094                    t = TYPE_NEXT_VARIANT (t))
2095                 if (TYPE_NEXT_VARIANT (t) == remove)
2096                   {
2097                     TYPE_NEXT_VARIANT (t) = TYPE_NEXT_VARIANT (remove);
2098                     break;
2099                   }
2100             }
2101         }
2102       else
2103         /* Merge the data types specified in the two decls.  */
2104         newtype = merge_types (TREE_TYPE (newdecl), TREE_TYPE (olddecl));
2105
2106       if (VAR_P (newdecl))
2107         {
2108           DECL_THIS_EXTERN (newdecl) |= DECL_THIS_EXTERN (olddecl);
2109           /* For already initialized vars, TREE_READONLY could have been
2110              cleared in cp_finish_decl, because the var needs runtime
2111              initialization or destruction.  Make sure not to set
2112              TREE_READONLY on it again.  */
2113           if (DECL_INITIALIZED_P (olddecl)
2114               && !DECL_EXTERNAL (olddecl)
2115               && !TREE_READONLY (olddecl))
2116             TREE_READONLY (newdecl) = 0;
2117           DECL_INITIALIZED_P (newdecl) |= DECL_INITIALIZED_P (olddecl);
2118           DECL_NONTRIVIALLY_INITIALIZED_P (newdecl)
2119             |= DECL_NONTRIVIALLY_INITIALIZED_P (olddecl);
2120           if (DECL_DEPENDENT_INIT_P (olddecl))
2121             SET_DECL_DEPENDENT_INIT_P (newdecl, true);
2122           DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (newdecl)
2123             |= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (olddecl);
2124           if (DECL_CLASS_SCOPE_P (olddecl))
2125             DECL_DECLARED_CONSTEXPR_P (newdecl)
2126               |= DECL_DECLARED_CONSTEXPR_P (olddecl);
2127
2128           /* Merge the threadprivate attribute from OLDDECL into NEWDECL.  */
2129           if (DECL_LANG_SPECIFIC (olddecl)
2130               && CP_DECL_THREADPRIVATE_P (olddecl))
2131             {
2132               /* Allocate a LANG_SPECIFIC structure for NEWDECL, if needed.  */
2133               retrofit_lang_decl (newdecl);
2134               CP_DECL_THREADPRIVATE_P (newdecl) = 1;
2135             }
2136         }
2137
2138       /* An explicit specialization of a function template or of a member
2139          function of a class template can be declared transaction_safe
2140          independently of whether the corresponding template entity is declared
2141          transaction_safe. */
2142       if (flag_tm && TREE_CODE (newdecl) == FUNCTION_DECL
2143           && DECL_TEMPLATE_INSTANTIATION (olddecl)
2144           && DECL_TEMPLATE_SPECIALIZATION (newdecl)
2145           && tx_safe_fn_type_p (newtype)
2146           && !tx_safe_fn_type_p (TREE_TYPE (newdecl)))
2147         newtype = tx_unsafe_fn_variant (newtype);
2148
2149       TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = newtype;
2150
2151       if (TREE_CODE (newdecl) == FUNCTION_DECL)
2152         check_default_args (newdecl);
2153
2154       /* Lay the type out, unless already done.  */
2155       if (! same_type_p (newtype, oldtype)
2156           && TREE_TYPE (newdecl) != error_mark_node
2157           && !(processing_template_decl && uses_template_parms (newdecl)))
2158         layout_type (TREE_TYPE (newdecl));
2159
2160       if ((VAR_P (newdecl)
2161            || TREE_CODE (newdecl) == PARM_DECL
2162            || TREE_CODE (newdecl) == RESULT_DECL
2163            || TREE_CODE (newdecl) == FIELD_DECL
2164            || TREE_CODE (newdecl) == TYPE_DECL)
2165           && !(processing_template_decl && uses_template_parms (newdecl)))
2166         layout_decl (newdecl, 0);
2167
2168       /* Merge the type qualifiers.  */
2169       if (TREE_READONLY (newdecl))
2170         TREE_READONLY (olddecl) = 1;
2171       if (TREE_THIS_VOLATILE (newdecl))
2172         TREE_THIS_VOLATILE (olddecl) = 1;
2173       if (TREE_NOTHROW (newdecl))
2174         TREE_NOTHROW (olddecl) = 1;
2175
2176       /* Merge deprecatedness.  */
2177       if (TREE_DEPRECATED (newdecl))
2178         TREE_DEPRECATED (olddecl) = 1;
2179
2180       /* Preserve function specific target and optimization options */
2181       if (TREE_CODE (newdecl) == FUNCTION_DECL)
2182         {
2183           if (DECL_FUNCTION_SPECIFIC_TARGET (olddecl)
2184               && !DECL_FUNCTION_SPECIFIC_TARGET (newdecl))
2185             DECL_FUNCTION_SPECIFIC_TARGET (newdecl)
2186               = DECL_FUNCTION_SPECIFIC_TARGET (olddecl);
2187
2188           if (DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl)
2189               && !DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl))
2190             DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl)
2191               = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl);
2192         }
2193
2194       /* Merge the initialization information.  */
2195       if (DECL_INITIAL (newdecl) == NULL_TREE
2196           && DECL_INITIAL (olddecl) != NULL_TREE)
2197         {
2198           DECL_INITIAL (newdecl) = DECL_INITIAL (olddecl);
2199           DECL_SOURCE_LOCATION (newdecl) = DECL_SOURCE_LOCATION (olddecl);
2200           if (TREE_CODE (newdecl) == FUNCTION_DECL)
2201             {
2202               DECL_SAVED_TREE (newdecl) = DECL_SAVED_TREE (olddecl);
2203               DECL_STRUCT_FUNCTION (newdecl) = DECL_STRUCT_FUNCTION (olddecl);
2204             }
2205         }
2206
2207       if (TREE_CODE (newdecl) == FUNCTION_DECL)
2208         {
2209           DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (newdecl)
2210             |= DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (olddecl);
2211           DECL_NO_LIMIT_STACK (newdecl) |= DECL_NO_LIMIT_STACK (olddecl);
2212           TREE_THIS_VOLATILE (newdecl) |= TREE_THIS_VOLATILE (olddecl);
2213           TREE_NOTHROW (newdecl) |= TREE_NOTHROW (olddecl);
2214           DECL_IS_MALLOC (newdecl) |= DECL_IS_MALLOC (olddecl);
2215           DECL_IS_OPERATOR_NEW (newdecl) |= DECL_IS_OPERATOR_NEW (olddecl);
2216           DECL_PURE_P (newdecl) |= DECL_PURE_P (olddecl);
2217           TREE_READONLY (newdecl) |= TREE_READONLY (olddecl);
2218           DECL_LOOPING_CONST_OR_PURE_P (newdecl) 
2219             |= DECL_LOOPING_CONST_OR_PURE_P (olddecl);
2220           /* Keep the old RTL.  */
2221           COPY_DECL_RTL (olddecl, newdecl);
2222         }
2223       else if (VAR_P (newdecl)
2224                && (DECL_SIZE (olddecl) || !DECL_SIZE (newdecl)))
2225         {
2226           /* Keep the old RTL.  We cannot keep the old RTL if the old
2227              declaration was for an incomplete object and the new
2228              declaration is not since many attributes of the RTL will
2229              change.  */
2230           COPY_DECL_RTL (olddecl, newdecl);
2231         }
2232     }
2233   /* If cannot merge, then use the new type and qualifiers,
2234      and don't preserve the old rtl.  */
2235   else
2236     {
2237       /* Clean out any memory we had of the old declaration.  */
2238       tree oldstatic = value_member (olddecl, static_aggregates);
2239       if (oldstatic)
2240         TREE_VALUE (oldstatic) = error_mark_node;
2241
2242       TREE_TYPE (olddecl) = TREE_TYPE (newdecl);
2243       TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2244       TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2245       TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2246       TREE_SIDE_EFFECTS (olddecl) = TREE_SIDE_EFFECTS (newdecl);
2247     }
2248
2249   /* Merge the storage class information.  */
2250   merge_weak (newdecl, olddecl);
2251
2252   DECL_DEFER_OUTPUT (newdecl) |= DECL_DEFER_OUTPUT (olddecl);
2253   TREE_PUBLIC (newdecl) = TREE_PUBLIC (olddecl);
2254   TREE_STATIC (olddecl) = TREE_STATIC (newdecl) |= TREE_STATIC (olddecl);
2255   if (! DECL_EXTERNAL (olddecl))
2256     DECL_EXTERNAL (newdecl) = 0;
2257   if (! DECL_COMDAT (olddecl))
2258     DECL_COMDAT (newdecl) = 0;
2259
2260   new_template_info = NULL_TREE;
2261   if (DECL_LANG_SPECIFIC (newdecl) && DECL_LANG_SPECIFIC (olddecl))
2262     {
2263       bool new_redefines_gnu_inline = false;
2264
2265       if (new_defines_function
2266           && ((DECL_INTERFACE_KNOWN (olddecl)
2267                && TREE_CODE (olddecl) == FUNCTION_DECL)
2268               || (TREE_CODE (olddecl) == TEMPLATE_DECL
2269                   && (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl))
2270                       == FUNCTION_DECL))))
2271         {
2272           tree fn = olddecl;
2273
2274           if (TREE_CODE (fn) == TEMPLATE_DECL)
2275             fn = DECL_TEMPLATE_RESULT (olddecl);
2276
2277           new_redefines_gnu_inline = GNU_INLINE_P (fn) && DECL_INITIAL (fn);
2278         }
2279
2280       if (!new_redefines_gnu_inline)
2281         {
2282           DECL_INTERFACE_KNOWN (newdecl) |= DECL_INTERFACE_KNOWN (olddecl);
2283           DECL_NOT_REALLY_EXTERN (newdecl) |= DECL_NOT_REALLY_EXTERN (olddecl);
2284           DECL_COMDAT (newdecl) |= DECL_COMDAT (olddecl);
2285         }
2286       DECL_TEMPLATE_INSTANTIATED (newdecl)
2287         |= DECL_TEMPLATE_INSTANTIATED (olddecl);
2288       DECL_ODR_USED (newdecl) |= DECL_ODR_USED (olddecl);
2289
2290       /* If the OLDDECL is an instantiation and/or specialization,
2291          then the NEWDECL must be too.  But, it may not yet be marked
2292          as such if the caller has created NEWDECL, but has not yet
2293          figured out that it is a redeclaration.  */
2294       if (!DECL_USE_TEMPLATE (newdecl))
2295         DECL_USE_TEMPLATE (newdecl) = DECL_USE_TEMPLATE (olddecl);
2296
2297       /* Don't really know how much of the language-specific
2298          values we should copy from old to new.  */
2299       DECL_IN_AGGR_P (newdecl) = DECL_IN_AGGR_P (olddecl);
2300       DECL_REPO_AVAILABLE_P (newdecl) = DECL_REPO_AVAILABLE_P (olddecl);
2301       DECL_INITIALIZED_IN_CLASS_P (newdecl)
2302         |= DECL_INITIALIZED_IN_CLASS_P (olddecl);
2303
2304       if (LANG_DECL_HAS_MIN (newdecl))
2305         {
2306           DECL_LANG_SPECIFIC (newdecl)->u.min.u2 =
2307             DECL_LANG_SPECIFIC (olddecl)->u.min.u2;
2308           if (DECL_TEMPLATE_INFO (newdecl))
2309             {
2310               new_template_info = DECL_TEMPLATE_INFO (newdecl);
2311               if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2312                   && DECL_TEMPLATE_SPECIALIZATION (newdecl))
2313                 /* Remember the presence of explicit specialization args.  */
2314                 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (olddecl))
2315                   = TINFO_USED_TEMPLATE_ID (new_template_info);
2316             }
2317           DECL_TEMPLATE_INFO (newdecl) = DECL_TEMPLATE_INFO (olddecl);
2318         }
2319       /* Only functions have these fields.  */
2320       if (DECL_DECLARES_FUNCTION_P (newdecl))
2321         {
2322           DECL_NONCONVERTING_P (newdecl) = DECL_NONCONVERTING_P (olddecl);
2323           DECL_BEFRIENDING_CLASSES (newdecl)
2324             = chainon (DECL_BEFRIENDING_CLASSES (newdecl),
2325                        DECL_BEFRIENDING_CLASSES (olddecl));
2326           /* DECL_THUNKS is only valid for virtual functions,
2327              otherwise it is a DECL_FRIEND_CONTEXT.  */
2328           if (DECL_VIRTUAL_P (newdecl))
2329             SET_DECL_THUNKS (newdecl, DECL_THUNKS (olddecl));
2330         }
2331       /* Only variables have this field.  */
2332       else if (VAR_P (newdecl)
2333                && VAR_HAD_UNKNOWN_BOUND (olddecl))
2334         SET_VAR_HAD_UNKNOWN_BOUND (newdecl);
2335     }
2336
2337   if (TREE_CODE (newdecl) == FUNCTION_DECL)
2338     {
2339       tree parm;
2340
2341       /* Merge parameter attributes. */
2342       tree oldarg, newarg;
2343       for (oldarg = DECL_ARGUMENTS(olddecl), 
2344                newarg = DECL_ARGUMENTS(newdecl);
2345            oldarg && newarg;
2346            oldarg = DECL_CHAIN(oldarg), newarg = DECL_CHAIN(newarg)) {
2347           DECL_ATTRIBUTES (newarg)
2348               = (*targetm.merge_decl_attributes) (oldarg, newarg);
2349           DECL_ATTRIBUTES (oldarg) = DECL_ATTRIBUTES (newarg);
2350       }
2351       
2352       if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2353           && !DECL_TEMPLATE_INSTANTIATION (newdecl))
2354         {
2355           /* If newdecl is not a specialization, then it is not a
2356              template-related function at all.  And that means that we
2357              should have exited above, returning 0.  */
2358           gcc_assert (DECL_TEMPLATE_SPECIALIZATION (newdecl));
2359
2360           if (DECL_ODR_USED (olddecl))
2361             /* From [temp.expl.spec]:
2362
2363                If a template, a member template or the member of a class
2364                template is explicitly specialized then that
2365                specialization shall be declared before the first use of
2366                that specialization that would cause an implicit
2367                instantiation to take place, in every translation unit in
2368                which such a use occurs.  */
2369             error ("explicit specialization of %qD after first use",
2370                       olddecl);
2371
2372           SET_DECL_TEMPLATE_SPECIALIZATION (olddecl);
2373           DECL_COMDAT (newdecl) = (TREE_PUBLIC (newdecl)
2374                                    && DECL_DECLARED_INLINE_P (newdecl));
2375
2376           /* Don't propagate visibility from the template to the
2377              specialization here.  We'll do that in determine_visibility if
2378              appropriate.  */
2379           DECL_VISIBILITY_SPECIFIED (olddecl) = 0;
2380
2381           /* [temp.expl.spec/14] We don't inline explicit specialization
2382              just because the primary template says so.  */
2383
2384           /* But still keep DECL_DISREGARD_INLINE_LIMITS in sync with
2385              the always_inline attribute.  */
2386           if (DECL_DISREGARD_INLINE_LIMITS (olddecl)
2387               && !DECL_DISREGARD_INLINE_LIMITS (newdecl))
2388             {
2389               if (DECL_DECLARED_INLINE_P (newdecl))
2390                 DECL_DISREGARD_INLINE_LIMITS (newdecl) = true;
2391               else
2392                 DECL_ATTRIBUTES (newdecl)
2393                   = remove_attribute ("always_inline",
2394                                       DECL_ATTRIBUTES (newdecl));
2395             }
2396         }
2397       else if (new_defines_function && DECL_INITIAL (olddecl))
2398         {
2399           /* Never inline re-defined extern inline functions.
2400              FIXME: this could be better handled by keeping both
2401              function as separate declarations.  */
2402           DECL_UNINLINABLE (newdecl) = 1;
2403         }
2404       else
2405         {
2406           if (DECL_PENDING_INLINE_P (olddecl))
2407             {
2408               DECL_PENDING_INLINE_P (newdecl) = 1;
2409               DECL_PENDING_INLINE_INFO (newdecl)
2410                 = DECL_PENDING_INLINE_INFO (olddecl);
2411             }
2412           else if (DECL_PENDING_INLINE_P (newdecl))
2413             ;
2414           else if (DECL_SAVED_FUNCTION_DATA (newdecl) == NULL)
2415             DECL_SAVED_FUNCTION_DATA (newdecl)
2416               = DECL_SAVED_FUNCTION_DATA (olddecl);
2417
2418           DECL_DECLARED_INLINE_P (newdecl) |= DECL_DECLARED_INLINE_P (olddecl);
2419
2420           DECL_UNINLINABLE (newdecl) = DECL_UNINLINABLE (olddecl)
2421             = (DECL_UNINLINABLE (newdecl) || DECL_UNINLINABLE (olddecl));
2422
2423           DECL_DISREGARD_INLINE_LIMITS (newdecl)
2424             = DECL_DISREGARD_INLINE_LIMITS (olddecl)
2425             = (DECL_DISREGARD_INLINE_LIMITS (newdecl)
2426                || DECL_DISREGARD_INLINE_LIMITS (olddecl));
2427         }
2428
2429       /* Preserve abstractness on cloned [cd]tors.  */
2430       DECL_ABSTRACT_P (newdecl) = DECL_ABSTRACT_P (olddecl);
2431
2432       /* Update newdecl's parms to point at olddecl.  */
2433       for (parm = DECL_ARGUMENTS (newdecl); parm;
2434            parm = DECL_CHAIN (parm))
2435         DECL_CONTEXT (parm) = olddecl;
2436
2437       if (! types_match)
2438         {
2439           SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
2440           COPY_DECL_ASSEMBLER_NAME (newdecl, olddecl);
2441           COPY_DECL_RTL (newdecl, olddecl);
2442         }
2443       if (! types_match || new_defines_function)
2444         {
2445           /* These need to be copied so that the names are available.
2446              Note that if the types do match, we'll preserve inline
2447              info and other bits, but if not, we won't.  */
2448           DECL_ARGUMENTS (olddecl) = DECL_ARGUMENTS (newdecl);
2449           DECL_RESULT (olddecl) = DECL_RESULT (newdecl);
2450         }
2451       /* If redeclaring a builtin function, it stays built in
2452          if newdecl is a gnu_inline definition, or if newdecl is just
2453          a declaration.  */
2454       if (DECL_BUILT_IN (olddecl)
2455           && (new_defines_function ? GNU_INLINE_P (newdecl) : types_match))
2456         {
2457           DECL_BUILT_IN_CLASS (newdecl) = DECL_BUILT_IN_CLASS (olddecl);
2458           DECL_FUNCTION_CODE (newdecl) = DECL_FUNCTION_CODE (olddecl);
2459           /* If we're keeping the built-in definition, keep the rtl,
2460              regardless of declaration matches.  */
2461           COPY_DECL_RTL (olddecl, newdecl);
2462           if (DECL_BUILT_IN_CLASS (newdecl) == BUILT_IN_NORMAL)
2463             {
2464               enum built_in_function fncode = DECL_FUNCTION_CODE (newdecl);
2465               switch (fncode)
2466                 {
2467                   /* If a compatible prototype of these builtin functions
2468                      is seen, assume the runtime implements it with the
2469                      expected semantics.  */
2470                 case BUILT_IN_STPCPY:
2471                   if (builtin_decl_explicit_p (fncode))
2472                     set_builtin_decl_implicit_p (fncode, true);
2473                   break;
2474                 default:
2475                   if (builtin_decl_explicit_p (fncode))
2476                     set_builtin_decl_declared_p (fncode, true);
2477                   break;
2478                 }
2479             }
2480
2481           copy_attributes_to_builtin (newdecl);
2482         }
2483       if (new_defines_function)
2484         /* If defining a function declared with other language
2485            linkage, use the previously declared language linkage.  */
2486         SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
2487       else if (types_match)
2488         {
2489           DECL_RESULT (newdecl) = DECL_RESULT (olddecl);
2490           /* Don't clear out the arguments if we're just redeclaring a
2491              function.  */
2492           if (DECL_ARGUMENTS (olddecl))
2493             DECL_ARGUMENTS (newdecl) = DECL_ARGUMENTS (olddecl);
2494         }
2495     }
2496   else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
2497     NAMESPACE_LEVEL (newdecl) = NAMESPACE_LEVEL (olddecl);
2498
2499   /* Now preserve various other info from the definition.  */
2500   TREE_ADDRESSABLE (newdecl) = TREE_ADDRESSABLE (olddecl);
2501   TREE_ASM_WRITTEN (newdecl) = TREE_ASM_WRITTEN (olddecl);
2502   DECL_COMMON (newdecl) = DECL_COMMON (olddecl);
2503   COPY_DECL_ASSEMBLER_NAME (olddecl, newdecl);
2504
2505   /* Warn about conflicting visibility specifications.  */
2506   if (DECL_VISIBILITY_SPECIFIED (olddecl)
2507       && DECL_VISIBILITY_SPECIFIED (newdecl)
2508       && DECL_VISIBILITY (newdecl) != DECL_VISIBILITY (olddecl))
2509     {
2510       if (warning_at (DECL_SOURCE_LOCATION (newdecl), OPT_Wattributes,
2511                       "%qD: visibility attribute ignored because it "
2512                       "conflicts with previous declaration", newdecl))
2513         inform (DECL_SOURCE_LOCATION (olddecl),
2514                 "previous declaration of %qD", olddecl);
2515     }
2516   /* Choose the declaration which specified visibility.  */
2517   if (DECL_VISIBILITY_SPECIFIED (olddecl))
2518     {
2519       DECL_VISIBILITY (newdecl) = DECL_VISIBILITY (olddecl);
2520       DECL_VISIBILITY_SPECIFIED (newdecl) = 1;
2521     }
2522   /* Init priority used to be merged from newdecl to olddecl by the memcpy,
2523      so keep this behavior.  */
2524   if (VAR_P (newdecl) && DECL_HAS_INIT_PRIORITY_P (newdecl))
2525     {
2526       SET_DECL_INIT_PRIORITY (olddecl, DECL_INIT_PRIORITY (newdecl));
2527       DECL_HAS_INIT_PRIORITY_P (olddecl) = 1;
2528     }
2529   /* Likewise for DECL_ALIGN, DECL_USER_ALIGN and DECL_PACKED.  */
2530   if (DECL_ALIGN (olddecl) > DECL_ALIGN (newdecl))
2531     {
2532       SET_DECL_ALIGN (newdecl, DECL_ALIGN (olddecl));
2533       DECL_USER_ALIGN (newdecl) |= DECL_USER_ALIGN (olddecl);
2534     }
2535   DECL_USER_ALIGN (olddecl) = DECL_USER_ALIGN (newdecl);
2536   if (DECL_WARN_IF_NOT_ALIGN (olddecl)
2537       > DECL_WARN_IF_NOT_ALIGN (newdecl))
2538     SET_DECL_WARN_IF_NOT_ALIGN (newdecl,
2539                                 DECL_WARN_IF_NOT_ALIGN (olddecl));
2540   if (TREE_CODE (newdecl) == FIELD_DECL)
2541     DECL_PACKED (olddecl) = DECL_PACKED (newdecl);
2542
2543   /* The DECL_LANG_SPECIFIC information in OLDDECL will be replaced
2544      with that from NEWDECL below.  */
2545   if (DECL_LANG_SPECIFIC (olddecl))
2546     {
2547       gcc_assert (DECL_LANG_SPECIFIC (olddecl)
2548                   != DECL_LANG_SPECIFIC (newdecl));
2549       ggc_free (DECL_LANG_SPECIFIC (olddecl));
2550     }
2551
2552   /* Merge the USED information.  */
2553   if (TREE_USED (olddecl))
2554     TREE_USED (newdecl) = 1;
2555   else if (TREE_USED (newdecl))
2556     TREE_USED (olddecl) = 1;
2557   if (VAR_P (newdecl))
2558     {
2559       if (DECL_READ_P (olddecl))
2560         DECL_READ_P (newdecl) = 1;
2561       else if (DECL_READ_P (newdecl))
2562         DECL_READ_P (olddecl) = 1;
2563     }
2564   if (DECL_PRESERVE_P (olddecl))
2565     DECL_PRESERVE_P (newdecl) = 1;
2566   else if (DECL_PRESERVE_P (newdecl))
2567     DECL_PRESERVE_P (olddecl) = 1;
2568
2569   /* Merge the DECL_FUNCTION_VERSIONED information.  newdecl will be copied
2570      to olddecl and deleted.  */
2571   if (TREE_CODE (newdecl) == FUNCTION_DECL
2572       && DECL_FUNCTION_VERSIONED (olddecl))
2573     {
2574       /* Set the flag for newdecl so that it gets copied to olddecl.  */
2575       DECL_FUNCTION_VERSIONED (newdecl) = 1;
2576       /* newdecl will be purged after copying to olddecl and is no longer
2577          a version.  */
2578       cgraph_node::delete_function_version_by_decl (newdecl);
2579     }
2580
2581   if (TREE_CODE (newdecl) == FUNCTION_DECL)
2582     {
2583       int function_size;
2584       struct symtab_node *snode = symtab_node::get (olddecl);
2585
2586       function_size = sizeof (struct tree_decl_common);
2587
2588       memcpy ((char *) olddecl + sizeof (struct tree_common),
2589               (char *) newdecl + sizeof (struct tree_common),
2590               function_size - sizeof (struct tree_common));
2591
2592       memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2593               (char *) newdecl + sizeof (struct tree_decl_common),
2594               sizeof (struct tree_function_decl) - sizeof (struct tree_decl_common));
2595
2596       /* Preserve symtab node mapping.  */
2597       olddecl->decl_with_vis.symtab_node = snode;
2598
2599       if (new_template_info)
2600         /* If newdecl is a template instantiation, it is possible that
2601            the following sequence of events has occurred:
2602
2603            o A friend function was declared in a class template.  The
2604            class template was instantiated.
2605
2606            o The instantiation of the friend declaration was
2607            recorded on the instantiation list, and is newdecl.
2608
2609            o Later, however, instantiate_class_template called pushdecl
2610            on the newdecl to perform name injection.  But, pushdecl in
2611            turn called duplicate_decls when it discovered that another
2612            declaration of a global function with the same name already
2613            existed.
2614
2615            o Here, in duplicate_decls, we decided to clobber newdecl.
2616
2617            If we're going to do that, we'd better make sure that
2618            olddecl, and not newdecl, is on the list of
2619            instantiations so that if we try to do the instantiation
2620            again we won't get the clobbered declaration.  */
2621         reregister_specialization (newdecl,
2622                                    new_template_info,
2623                                    olddecl);
2624     }
2625   else
2626     {
2627       size_t size = tree_code_size (TREE_CODE (newdecl));
2628
2629       memcpy ((char *) olddecl + sizeof (struct tree_common),
2630               (char *) newdecl + sizeof (struct tree_common),
2631               sizeof (struct tree_decl_common) - sizeof (struct tree_common));
2632       switch (TREE_CODE (newdecl))
2633         {
2634         case LABEL_DECL:
2635         case VAR_DECL:
2636         case RESULT_DECL:
2637         case PARM_DECL:
2638         case FIELD_DECL:
2639         case TYPE_DECL:
2640         case CONST_DECL:
2641           {
2642             struct symtab_node *snode = NULL;
2643
2644             if (VAR_P (newdecl)
2645                 && (TREE_STATIC (olddecl) || TREE_PUBLIC (olddecl)
2646                     || DECL_EXTERNAL (olddecl)))
2647               snode = symtab_node::get (olddecl);
2648             memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2649                     (char *) newdecl + sizeof (struct tree_decl_common),
2650                     size - sizeof (struct tree_decl_common)
2651                     + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
2652             if (VAR_P (newdecl))
2653               olddecl->decl_with_vis.symtab_node = snode;
2654           }
2655           break;
2656         default:
2657           memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2658                   (char *) newdecl + sizeof (struct tree_decl_common),
2659                   sizeof (struct tree_decl_non_common) - sizeof (struct tree_decl_common)
2660                   + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
2661           break;
2662         }
2663     }
2664
2665   if (VAR_OR_FUNCTION_DECL_P (newdecl))
2666     {
2667       if (DECL_EXTERNAL (olddecl)
2668           || TREE_PUBLIC (olddecl)
2669           || TREE_STATIC (olddecl))
2670         {
2671           /* Merge the section attribute.
2672              We want to issue an error if the sections conflict but that must be
2673              done later in decl_attributes since we are called before attributes
2674              are assigned.  */
2675           if (DECL_SECTION_NAME (newdecl) != NULL)
2676             set_decl_section_name (olddecl, DECL_SECTION_NAME (newdecl));
2677
2678           if (DECL_ONE_ONLY (newdecl))
2679             {
2680               struct symtab_node *oldsym, *newsym;
2681               if (TREE_CODE (olddecl) == FUNCTION_DECL)
2682                 oldsym = cgraph_node::get_create (olddecl);
2683               else
2684                 oldsym = varpool_node::get_create (olddecl);
2685               newsym = symtab_node::get (newdecl);
2686               oldsym->set_comdat_group (newsym->get_comdat_group ());
2687             }
2688         }
2689
2690       if (VAR_P (newdecl)
2691           && CP_DECL_THREAD_LOCAL_P (newdecl))
2692         {
2693           CP_DECL_THREAD_LOCAL_P (olddecl) = true;
2694           if (!processing_template_decl)
2695             set_decl_tls_model (olddecl, DECL_TLS_MODEL (newdecl));
2696         }
2697     }
2698
2699   DECL_UID (olddecl) = olddecl_uid;
2700   if (olddecl_friend)
2701     DECL_FRIEND_P (olddecl) = 1;
2702   if (hidden_friend)
2703     {
2704       DECL_ANTICIPATED (olddecl) = 1;
2705       DECL_HIDDEN_FRIEND_P (olddecl) = 1;
2706     }
2707
2708   /* NEWDECL contains the merged attribute lists.
2709      Update OLDDECL to be the same.  */
2710   DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
2711
2712   /* If OLDDECL had its DECL_RTL instantiated, re-invoke make_decl_rtl
2713     so that encode_section_info has a chance to look at the new decl
2714     flags and attributes.  */
2715   if (DECL_RTL_SET_P (olddecl)
2716       && (TREE_CODE (olddecl) == FUNCTION_DECL
2717           || (VAR_P (olddecl)
2718               && TREE_STATIC (olddecl))))
2719     make_decl_rtl (olddecl);
2720
2721   /* The NEWDECL will no longer be needed.  Because every out-of-class
2722      declaration of a member results in a call to duplicate_decls,
2723      freeing these nodes represents in a significant savings.
2724
2725      Before releasing the node, be sore to remove function from symbol
2726      table that might have been inserted there to record comdat group.
2727      Be sure to however do not free DECL_STRUCT_FUNCTION because this
2728      structure is shared in between newdecl and oldecl.  */
2729   if (TREE_CODE (newdecl) == FUNCTION_DECL)
2730     DECL_STRUCT_FUNCTION (newdecl) = NULL;
2731   if (VAR_OR_FUNCTION_DECL_P (newdecl))
2732     {
2733       struct symtab_node *snode = symtab_node::get (newdecl);
2734       if (snode)
2735         snode->remove ();
2736     }
2737
2738   /* Remove the associated constraints for newdecl, if any, before
2739      reclaiming memory. */
2740   if (flag_concepts)
2741     remove_constraints (newdecl);
2742
2743   ggc_free (newdecl);
2744
2745   return olddecl;
2746 }
2747 \f
2748 /* Return zero if the declaration NEWDECL is valid
2749    when the declaration OLDDECL (assumed to be for the same name)
2750    has already been seen.
2751    Otherwise return an error message format string with a %s
2752    where the identifier should go.  */
2753
2754 static const char *
2755 redeclaration_error_message (tree newdecl, tree olddecl)
2756 {
2757   if (TREE_CODE (newdecl) == TYPE_DECL)
2758     {
2759       /* Because C++ can put things into name space for free,
2760          constructs like "typedef struct foo { ... } foo"
2761          would look like an erroneous redeclaration.  */
2762       if (same_type_p (TREE_TYPE (newdecl), TREE_TYPE (olddecl)))
2763         return NULL;
2764       else
2765         return G_("redefinition of %q#D");
2766     }
2767   else if (TREE_CODE (newdecl) == FUNCTION_DECL)
2768     {
2769       /* If this is a pure function, its olddecl will actually be
2770          the original initialization to `0' (which we force to call
2771          abort()).  Don't complain about redefinition in this case.  */
2772       if (DECL_LANG_SPECIFIC (olddecl) && DECL_PURE_VIRTUAL_P (olddecl)
2773           && DECL_INITIAL (olddecl) == NULL_TREE)
2774         return NULL;
2775
2776       /* If both functions come from different namespaces, this is not
2777          a redeclaration - this is a conflict with a used function.  */
2778       if (DECL_NAMESPACE_SCOPE_P (olddecl)
2779           && DECL_CONTEXT (olddecl) != DECL_CONTEXT (newdecl)
2780           && ! decls_match (olddecl, newdecl))
2781         return G_("%qD conflicts with used function");
2782
2783       /* We'll complain about linkage mismatches in
2784          warn_extern_redeclared_static.  */
2785
2786       /* Defining the same name twice is no good.  */
2787       if (decl_defined_p (olddecl)
2788           && decl_defined_p (newdecl))
2789         {
2790           if (DECL_NAME (olddecl) == NULL_TREE)
2791             return G_("%q#D not declared in class");
2792           else if (!GNU_INLINE_P (olddecl)
2793                    || GNU_INLINE_P (newdecl))
2794             return G_("redefinition of %q#D");
2795         }
2796
2797       if (DECL_DECLARED_INLINE_P (olddecl) && DECL_DECLARED_INLINE_P (newdecl))
2798         {
2799           bool olda = GNU_INLINE_P (olddecl);
2800           bool newa = GNU_INLINE_P (newdecl);
2801
2802           if (olda != newa)
2803             {
2804               if (newa)
2805                 return G_("%q+D redeclared inline with "
2806                           "%<gnu_inline%> attribute");
2807               else
2808                 return G_("%q+D redeclared inline without "
2809                           "%<gnu_inline%> attribute");
2810             }
2811         }
2812
2813       check_abi_tag_redeclaration
2814         (olddecl, lookup_attribute ("abi_tag", DECL_ATTRIBUTES (olddecl)),
2815          lookup_attribute ("abi_tag", DECL_ATTRIBUTES (newdecl)));
2816
2817       return NULL;
2818     }
2819   else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
2820     {
2821       tree nt, ot;
2822
2823       if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == TYPE_DECL)
2824         {
2825           if (COMPLETE_TYPE_P (TREE_TYPE (newdecl))
2826               && COMPLETE_TYPE_P (TREE_TYPE (olddecl)))
2827             return G_("redefinition of %q#D");
2828           return NULL;
2829         }
2830
2831       if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) != FUNCTION_DECL
2832           || (DECL_TEMPLATE_RESULT (newdecl)
2833               == DECL_TEMPLATE_RESULT (olddecl)))
2834         return NULL;
2835
2836       nt = DECL_TEMPLATE_RESULT (newdecl);
2837       if (DECL_TEMPLATE_INFO (nt))
2838         nt = DECL_TEMPLATE_RESULT (template_for_substitution (nt));
2839       ot = DECL_TEMPLATE_RESULT (olddecl);
2840       if (DECL_TEMPLATE_INFO (ot))
2841         ot = DECL_TEMPLATE_RESULT (template_for_substitution (ot));
2842       if (DECL_INITIAL (nt) && DECL_INITIAL (ot)
2843           && (!GNU_INLINE_P (ot) || GNU_INLINE_P (nt)))
2844         return G_("redefinition of %q#D");
2845
2846       if (DECL_DECLARED_INLINE_P (ot) && DECL_DECLARED_INLINE_P (nt))
2847         {
2848           bool olda = GNU_INLINE_P (ot);
2849           bool newa = GNU_INLINE_P (nt);
2850
2851           if (olda != newa)
2852             {
2853               if (newa)
2854                 return G_("%q+D redeclared inline with "
2855                           "%<gnu_inline%> attribute");
2856               else
2857                 return G_("%q+D redeclared inline without "
2858                           "%<gnu_inline%> attribute");
2859             }
2860         }
2861
2862       /* Core issue #226 (C++0x): 
2863            
2864            If a friend function template declaration specifies a
2865            default template-argument, that declaration shall be a
2866            definition and shall be the only declaration of the
2867            function template in the translation unit.  */
2868       if ((cxx_dialect != cxx98) 
2869           && TREE_CODE (ot) == FUNCTION_DECL && DECL_FRIEND_P (ot)
2870           && !check_default_tmpl_args (nt, DECL_TEMPLATE_PARMS (newdecl), 
2871                                        /*is_primary=*/true,
2872                                        /*is_partial=*/false,
2873                                        /*is_friend_decl=*/2))
2874         return G_("redeclaration of friend %q#D "
2875                   "may not have default template arguments");
2876
2877       return NULL;
2878     }
2879   else if (VAR_P (newdecl)
2880            && CP_DECL_THREAD_LOCAL_P (newdecl) != CP_DECL_THREAD_LOCAL_P (olddecl)
2881            && (! DECL_LANG_SPECIFIC (olddecl)
2882                || ! CP_DECL_THREADPRIVATE_P (olddecl)
2883                || CP_DECL_THREAD_LOCAL_P (newdecl)))
2884     {
2885       /* Only variables can be thread-local, and all declarations must
2886          agree on this property.  */
2887       if (CP_DECL_THREAD_LOCAL_P (newdecl))
2888         return G_("thread-local declaration of %q#D follows "
2889                   "non-thread-local declaration");
2890       else
2891         return G_("non-thread-local declaration of %q#D follows "
2892                   "thread-local declaration");
2893     }
2894   else if (toplevel_bindings_p () || DECL_NAMESPACE_SCOPE_P (newdecl))
2895     {
2896       /* The objects have been declared at namespace scope.  If either
2897          is a member of an anonymous union, then this is an invalid
2898          redeclaration.  For example:
2899
2900            int i;
2901            union { int i; };
2902
2903            is invalid.  */
2904       if ((VAR_P (newdecl) && DECL_ANON_UNION_VAR_P (newdecl))
2905           || (VAR_P (olddecl) && DECL_ANON_UNION_VAR_P (olddecl)))
2906         return G_("redeclaration of %q#D");
2907       /* If at least one declaration is a reference, there is no
2908          conflict.  For example:
2909
2910            int i = 3;
2911            extern int i;
2912
2913          is valid.  */
2914       if (DECL_EXTERNAL (newdecl) || DECL_EXTERNAL (olddecl))
2915         return NULL;
2916
2917       /* Static data member declared outside a class definition
2918          if the variable is defined within the class with constexpr
2919          specifier is declaration rather than definition (and
2920          deprecated).  */
2921       if (cxx_dialect >= cxx17
2922           && VAR_P (olddecl)
2923           && DECL_CLASS_SCOPE_P (olddecl)
2924           && DECL_DECLARED_CONSTEXPR_P (olddecl)
2925           && !DECL_INITIAL (newdecl))
2926         {
2927           DECL_EXTERNAL (newdecl) = 1;
2928           /* For now, only warn with explicit -Wdeprecated.  */
2929           if (global_options_set.x_warn_deprecated
2930               && warning_at (DECL_SOURCE_LOCATION (newdecl), OPT_Wdeprecated,
2931                              "redundant redeclaration of %<constexpr%> static "
2932                              "data member %qD", newdecl))
2933             inform (DECL_SOURCE_LOCATION (olddecl),
2934                     "previous declaration of %qD", olddecl);
2935           return NULL;
2936         }
2937
2938       /* Reject two definitions.  */
2939       return G_("redefinition of %q#D");
2940     }
2941   else
2942     {
2943       /* Objects declared with block scope:  */
2944       /* Reject two definitions, and reject a definition
2945          together with an external reference.  */
2946       if (!(DECL_EXTERNAL (newdecl) && DECL_EXTERNAL (olddecl)))
2947         return G_("redeclaration of %q#D");
2948       return NULL;
2949     }
2950 }
2951 \f
2952
2953 /* Hash and equality functions for the named_label table.  */
2954
2955 hashval_t
2956 named_label_hash::hash (const value_type entry)
2957 {
2958   return IDENTIFIER_HASH_VALUE (entry->name);
2959 }
2960
2961 bool
2962 named_label_hash::equal (const value_type entry, compare_type name)
2963 {
2964   return name == entry->name;
2965 }
2966
2967 /* Look for a label named ID in the current function.  If one cannot
2968    be found, create one.  Return the named_label_entry, or NULL on
2969    failure.  */
2970
2971 static named_label_entry *
2972 lookup_label_1 (tree id, bool making_local_p)
2973 {
2974   /* You can't use labels at global scope.  */
2975   if (current_function_decl == NULL_TREE)
2976     {
2977       error ("label %qE referenced outside of any function", id);
2978       return NULL;
2979     }
2980
2981   if (!named_labels)
2982     named_labels = hash_table<named_label_hash>::create_ggc (13);
2983
2984   hashval_t hash = IDENTIFIER_HASH_VALUE (id);
2985   named_label_entry **slot
2986     = named_labels->find_slot_with_hash (id, hash, INSERT);
2987   named_label_entry *old = *slot;
2988   
2989   if (old && old->label_decl)
2990     {
2991       if (!making_local_p)
2992         return old;
2993
2994       if (old->binding_level == current_binding_level)
2995         {
2996           error ("local label %qE conflicts with existing label", id);
2997           inform (DECL_SOURCE_LOCATION (old->label_decl), "previous label");
2998           return NULL;
2999         }
3000     }
3001
3002   /* We are making a new decl, create or reuse the named_label_entry  */
3003   named_label_entry *ent = NULL;
3004   if (old && !old->label_decl)
3005     ent = old;
3006   else
3007     {
3008       ent = ggc_cleared_alloc<named_label_entry> ();
3009       ent->name = id;
3010       ent->outer = old;
3011       *slot = ent;
3012     }
3013
3014   /* Now create the LABEL_DECL.  */
3015   tree decl = build_decl (input_location, LABEL_DECL, id, void_type_node);
3016
3017   DECL_CONTEXT (decl) = current_function_decl;
3018   SET_DECL_MODE (decl, VOIDmode);
3019   if (making_local_p)
3020     {
3021       C_DECLARED_LABEL_FLAG (decl) = true;
3022       DECL_CHAIN (decl) = current_binding_level->names;
3023       current_binding_level->names = decl;
3024     }
3025
3026   ent->label_decl = decl;
3027
3028   return ent;
3029 }
3030
3031 /* Wrapper for lookup_label_1.  */
3032
3033 tree
3034 lookup_label (tree id)
3035 {
3036   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
3037   named_label_entry *ent = lookup_label_1 (id, false);
3038   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
3039   return ent ? ent->label_decl : NULL_TREE;
3040 }
3041
3042 tree
3043 declare_local_label (tree id)
3044 {
3045   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
3046   named_label_entry *ent = lookup_label_1 (id, true);
3047   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
3048   return ent ? ent->label_decl : NULL_TREE;
3049 }
3050
3051 /* Returns nonzero if it is ill-formed to jump past the declaration of
3052    DECL.  Returns 2 if it's also a real problem.  */
3053
3054 static int
3055 decl_jump_unsafe (tree decl)
3056 {
3057   /* [stmt.dcl]/3: A program that jumps from a point where a local variable
3058      with automatic storage duration is not in scope to a point where it is
3059      in scope is ill-formed unless the variable has scalar type, class type
3060      with a trivial default constructor and a trivial destructor, a
3061      cv-qualified version of one of these types, or an array of one of the
3062      preceding types and is declared without an initializer (8.5).  */
3063   tree type = TREE_TYPE (decl);
3064
3065   if (!VAR_P (decl) || TREE_STATIC (decl)
3066       || type == error_mark_node)
3067     return 0;
3068
3069   if (DECL_NONTRIVIALLY_INITIALIZED_P (decl)
3070       || variably_modified_type_p (type, NULL_TREE))
3071     return 2;
3072
3073   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
3074     return 1;
3075
3076   return 0;
3077 }
3078
3079 /* A subroutine of check_previous_goto_1 and check_goto to identify a branch
3080    to the user.  */
3081
3082 static bool
3083 identify_goto (tree decl, location_t loc, const location_t *locus,
3084                diagnostic_t diag_kind)
3085 {
3086   bool complained
3087     = emit_diagnostic (diag_kind, loc, 0,
3088                        decl ? N_("jump to label %qD")
3089                        : N_("jump to case label"), decl);
3090   if (complained && locus)
3091     inform (*locus, "  from here");
3092   return complained;
3093 }
3094
3095 /* Check that a single previously seen jump to a newly defined label
3096    is OK.  DECL is the LABEL_DECL or 0; LEVEL is the binding_level for
3097    the jump context; NAMES are the names in scope in LEVEL at the jump
3098    context; LOCUS is the source position of the jump or 0.  Returns
3099    true if all is well.  */
3100
3101 static bool
3102 check_previous_goto_1 (tree decl, cp_binding_level* level, tree names,
3103                        bool exited_omp, const location_t *locus)
3104 {
3105   cp_binding_level *b;
3106   bool complained = false;
3107   int identified = 0;
3108   bool saw_eh = false, saw_omp = false, saw_tm = false, saw_cxif = false;
3109
3110   if (exited_omp)
3111     {
3112       complained = identify_goto (decl, input_location, locus, DK_ERROR);
3113       if (complained)
3114         inform (input_location, "  exits OpenMP structured block");
3115       saw_omp = true;
3116       identified = 2;
3117     }
3118
3119   for (b = current_binding_level; b ; b = b->level_chain)
3120     {
3121       tree new_decls, old_decls = (b == level ? names : NULL_TREE);
3122
3123       for (new_decls = b->names; new_decls != old_decls;
3124            new_decls = (DECL_P (new_decls) ? DECL_CHAIN (new_decls)
3125                         : TREE_CHAIN (new_decls)))
3126         {
3127           int problem = decl_jump_unsafe (new_decls);
3128           if (! problem)
3129             continue;
3130
3131           if (!identified)
3132             {
3133               complained = identify_goto (decl, input_location, locus,
3134                                           DK_PERMERROR);
3135               identified = 1;
3136             }
3137           if (complained)
3138             {
3139               if (problem > 1)
3140                 inform (DECL_SOURCE_LOCATION (new_decls),
3141                         "  crosses initialization of %q#D", new_decls);
3142               else
3143                 inform (DECL_SOURCE_LOCATION (new_decls),
3144                         "  enters scope of %q#D, which has "
3145                         "non-trivial destructor", new_decls);
3146             }
3147         }
3148
3149       if (b == level)
3150         break;
3151
3152       const char *inf = NULL;
3153       location_t loc = input_location;
3154       switch (b->kind)
3155         {
3156         case sk_try:
3157           if (!saw_eh)
3158             inf = N_("enters try block");
3159           saw_eh = true;
3160           break;
3161
3162         case sk_catch:
3163           if (!saw_eh)
3164             inf = N_("enters catch block");
3165           saw_eh = true;
3166           break;
3167
3168         case sk_omp:
3169           if (!saw_omp)
3170             inf = N_("enters OpenMP structured block");
3171           saw_omp = true;
3172           break;
3173
3174         case sk_transaction:
3175           if (!saw_tm)
3176             inf = N_("enters synchronized or atomic statement");
3177           saw_tm = true;
3178           break;
3179
3180         case sk_block:
3181           if (!saw_cxif && level_for_constexpr_if (b->level_chain))
3182             {
3183               inf = N_("enters constexpr if statement");
3184               loc = EXPR_LOCATION (b->level_chain->this_entity);
3185               saw_cxif = true;
3186             }
3187           break;
3188
3189         default:
3190           break;
3191         }
3192
3193       if (inf)
3194         {
3195           if (identified < 2)
3196             complained = identify_goto (decl, input_location, locus, DK_ERROR);
3197           identified = 2;
3198           if (complained)
3199             inform (loc, "  %s", inf);
3200         }
3201     }
3202
3203   return !identified;
3204 }
3205
3206 static void
3207 check_previous_goto (tree decl, struct named_label_use_entry *use)
3208 {
3209   check_previous_goto_1 (decl, use->binding_level,
3210                          use->names_in_scope, use->in_omp_scope,
3211                          &use->o_goto_locus);
3212 }
3213
3214 static bool
3215 check_switch_goto (cp_binding_level* level)
3216 {
3217   return check_previous_goto_1 (NULL_TREE, level, level->names, false, NULL);
3218 }
3219
3220 /* Check that a new jump to a label DECL is OK.  Called by
3221    finish_goto_stmt.  */
3222
3223 void
3224 check_goto (tree decl)
3225 {
3226   /* We can't know where a computed goto is jumping.
3227      So we assume that it's OK.  */
3228   if (TREE_CODE (decl) != LABEL_DECL)
3229     return;
3230
3231   /* We didn't record any information about this label when we created it,
3232      and there's not much point since it's trivial to analyze as a return.  */
3233   if (decl == cdtor_label)
3234     return;
3235
3236   hashval_t hash = IDENTIFIER_HASH_VALUE (DECL_NAME (decl));
3237   named_label_entry **slot
3238     = named_labels->find_slot_with_hash (DECL_NAME (decl), hash, NO_INSERT);
3239   named_label_entry *ent = *slot;
3240
3241   /* If the label hasn't been defined yet, defer checking.  */
3242   if (! DECL_INITIAL (decl))
3243     {
3244       /* Don't bother creating another use if the last goto had the
3245          same data, and will therefore create the same set of errors.  */
3246       if (ent->uses
3247           && ent->uses->names_in_scope == current_binding_level->names)
3248         return;
3249
3250       named_label_use_entry *new_use
3251         = ggc_alloc<named_label_use_entry> ();
3252       new_use->binding_level = current_binding_level;
3253       new_use->names_in_scope = current_binding_level->names;
3254       new_use->o_goto_locus = input_location;
3255       new_use->in_omp_scope = false;
3256
3257       new_use->next = ent->uses;
3258       ent->uses = new_use;
3259       return;
3260     }
3261
3262   bool saw_catch = false, complained = false;
3263   int identified = 0;
3264   tree bad;
3265   unsigned ix;
3266
3267   if (ent->in_try_scope || ent->in_catch_scope || ent->in_transaction_scope
3268       || ent->in_constexpr_if
3269       || ent->in_omp_scope || !vec_safe_is_empty (ent->bad_decls))
3270     {
3271       diagnostic_t diag_kind = DK_PERMERROR;
3272       if (ent->in_try_scope || ent->in_catch_scope || ent->in_constexpr_if
3273           || ent->in_transaction_scope || ent->in_omp_scope)
3274         diag_kind = DK_ERROR;
3275       complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3276                                   &input_location, diag_kind);
3277       identified = 1 + (diag_kind == DK_ERROR);
3278     }
3279
3280   FOR_EACH_VEC_SAFE_ELT (ent->bad_decls, ix, bad)
3281     {
3282       int u = decl_jump_unsafe (bad);
3283
3284       if (u > 1 && DECL_ARTIFICIAL (bad))
3285         {
3286           /* Can't skip init of __exception_info.  */
3287           if (identified == 1)
3288             {
3289               complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3290                                           &input_location, DK_ERROR);
3291               identified = 2;
3292             }
3293           if (complained)
3294             inform (DECL_SOURCE_LOCATION (bad), "  enters catch block");
3295           saw_catch = true;
3296         }
3297       else if (complained)
3298         {
3299           if (u > 1)
3300             inform (DECL_SOURCE_LOCATION (bad),
3301                     "  skips initialization of %q#D", bad);
3302           else
3303             inform (DECL_SOURCE_LOCATION (bad),
3304                     "  enters scope of %q#D which has "
3305                     "non-trivial destructor", bad);
3306         }
3307     }
3308
3309   if (complained)
3310     {
3311       if (ent->in_try_scope)
3312         inform (input_location, "  enters try block");
3313       else if (ent->in_catch_scope && !saw_catch)
3314         inform (input_location, "  enters catch block");
3315       else if (ent->in_transaction_scope)
3316         inform (input_location, "  enters synchronized or atomic statement");
3317       else if (ent->in_constexpr_if)
3318         inform (input_location, "  enters %<constexpr%> if statement");
3319     }
3320
3321   if (ent->in_omp_scope)
3322     {
3323       if (complained)
3324         inform (input_location, "  enters OpenMP structured block");
3325     }
3326   else if (flag_openmp)
3327     for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3328       {
3329         if (b == ent->binding_level)
3330           break;
3331         if (b->kind == sk_omp)
3332           {
3333             if (identified < 2)
3334               {
3335                 complained = identify_goto (decl,
3336                                             DECL_SOURCE_LOCATION (decl),
3337                                             &input_location, DK_ERROR);
3338                 identified = 2;
3339               }
3340             if (complained)
3341               inform (input_location, "  exits OpenMP structured block");
3342             break;
3343           }
3344       }
3345 }
3346
3347 /* Check that a return is ok wrt OpenMP structured blocks.
3348    Called by finish_return_stmt.  Returns true if all is well.  */
3349
3350 bool
3351 check_omp_return (void)
3352 {
3353   for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3354     if (b->kind == sk_omp)
3355       {
3356         error ("invalid exit from OpenMP structured block");
3357         return false;
3358       }
3359     else if (b->kind == sk_function_parms)
3360       break;
3361   return true;
3362 }
3363
3364 /* Define a label, specifying the location in the source file.
3365    Return the LABEL_DECL node for the label.  */
3366
3367 static tree
3368 define_label_1 (location_t location, tree name)
3369 {
3370   /* After labels, make any new cleanups in the function go into their
3371      own new (temporary) binding contour.  */
3372   for (cp_binding_level *p = current_binding_level;
3373        p->kind != sk_function_parms;
3374        p = p->level_chain)
3375     p->more_cleanups_ok = 0;
3376
3377   named_label_entry *ent = lookup_label_1 (name, false);
3378   tree decl = ent->label_decl;
3379
3380   if (DECL_INITIAL (decl) != NULL_TREE)
3381     {
3382       error ("duplicate label %qD", decl);
3383       return error_mark_node;
3384     }
3385   else
3386     {
3387       /* Mark label as having been defined.  */
3388       DECL_INITIAL (decl) = error_mark_node;
3389       /* Say where in the source.  */
3390       DECL_SOURCE_LOCATION (decl) = location;
3391
3392       ent->binding_level = current_binding_level;
3393       ent->names_in_scope = current_binding_level->names;
3394
3395       for (named_label_use_entry *use = ent->uses; use; use = use->next)
3396         check_previous_goto (decl, use);
3397       ent->uses = NULL;
3398     }
3399
3400   return decl;
3401 }
3402
3403 /* Wrapper for define_label_1.  */
3404
3405 tree
3406 define_label (location_t location, tree name)
3407 {
3408   bool running = timevar_cond_start (TV_NAME_LOOKUP);
3409   tree ret = define_label_1 (location, name);
3410   timevar_cond_stop (TV_NAME_LOOKUP, running);
3411   return ret;
3412 }
3413
3414
3415 struct cp_switch
3416 {
3417   cp_binding_level *level;
3418   struct cp_switch *next;
3419   /* The SWITCH_STMT being built.  */
3420   tree switch_stmt;
3421   /* A splay-tree mapping the low element of a case range to the high
3422      element, or NULL_TREE if there is no high element.  Used to
3423      determine whether or not a new case label duplicates an old case
3424      label.  We need a tree, rather than simply a hash table, because
3425      of the GNU case range extension.  */
3426   splay_tree cases;
3427   /* Remember whether there was a case value that is outside the
3428      range of the original type of the controlling expression.  */
3429   bool outside_range_p;
3430   /* Remember whether a default: case label has been seen.  */
3431   bool has_default_p;
3432   /* Remember whether a BREAK_STMT has been seen in this SWITCH_STMT.  */
3433   bool break_stmt_seen_p;
3434   /* Set if inside of {FOR,DO,WHILE}_BODY nested inside of a switch,
3435      where BREAK_STMT doesn't belong to the SWITCH_STMT.  */
3436   bool in_loop_body_p;
3437 };
3438
3439 /* A stack of the currently active switch statements.  The innermost
3440    switch statement is on the top of the stack.  There is no need to
3441    mark the stack for garbage collection because it is only active
3442    during the processing of the body of a function, and we never
3443    collect at that point.  */
3444
3445 static struct cp_switch *switch_stack;
3446
3447 /* Called right after a switch-statement condition is parsed.
3448    SWITCH_STMT is the switch statement being parsed.  */
3449
3450 void
3451 push_switch (tree switch_stmt)
3452 {
3453   struct cp_switch *p = XNEW (struct cp_switch);
3454   p->level = current_binding_level;
3455   p->next = switch_stack;
3456   p->switch_stmt = switch_stmt;
3457   p->cases = splay_tree_new (case_compare, NULL, NULL);
3458   p->outside_range_p = false;
3459   p->has_default_p = false;
3460   p->break_stmt_seen_p = false;
3461   p->in_loop_body_p = false;
3462   switch_stack = p;
3463 }
3464
3465 void
3466 pop_switch (void)
3467 {
3468   struct cp_switch *cs = switch_stack;
3469   location_t switch_location;
3470
3471   /* Emit warnings as needed.  */
3472   switch_location = EXPR_LOC_OR_LOC (cs->switch_stmt, input_location);
3473   const bool bool_cond_p
3474     = (SWITCH_STMT_TYPE (cs->switch_stmt)
3475        && TREE_CODE (SWITCH_STMT_TYPE (cs->switch_stmt)) == BOOLEAN_TYPE);
3476   if (!processing_template_decl)
3477     c_do_switch_warnings (cs->cases, switch_location,
3478                           SWITCH_STMT_TYPE (cs->switch_stmt),
3479                           SWITCH_STMT_COND (cs->switch_stmt),
3480                           bool_cond_p, cs->outside_range_p);
3481
3482   /* For the benefit of block_may_fallthru remember if the switch body
3483      case labels cover all possible values and if there are break; stmts.  */
3484   if (cs->has_default_p
3485       || (!processing_template_decl
3486           && c_switch_covers_all_cases_p (cs->cases,
3487                                           SWITCH_STMT_TYPE (cs->switch_stmt))))
3488     SWITCH_STMT_ALL_CASES_P (cs->switch_stmt) = 1;
3489   if (!cs->break_stmt_seen_p)
3490     SWITCH_STMT_NO_BREAK_P (cs->switch_stmt) = 1;
3491   gcc_assert (!cs->in_loop_body_p);
3492   splay_tree_delete (cs->cases);
3493   switch_stack = switch_stack->next;
3494   free (cs);
3495 }
3496
3497 /* Note that a BREAK_STMT is about to be added.  If it is inside of
3498    a SWITCH_STMT and not inside of a loop body inside of it, note
3499    in switch_stack we've seen a BREAK_STMT.  */
3500
3501 void
3502 note_break_stmt (void)
3503 {
3504   if (switch_stack && !switch_stack->in_loop_body_p)
3505     switch_stack->break_stmt_seen_p = true;
3506 }
3507
3508 /* Note the start of processing of an iteration statement's body.
3509    The note_break_stmt function will do nothing while processing it.
3510    Return a flag that should be passed to note_iteration_stmt_body_end.  */
3511
3512 bool
3513 note_iteration_stmt_body_start (void)
3514 {
3515   if (!switch_stack)
3516     return false;
3517   bool ret = switch_stack->in_loop_body_p;
3518   switch_stack->in_loop_body_p = true;
3519   return ret;
3520 }
3521
3522 /* Note the end of processing of an iteration statement's body.  */
3523
3524 void
3525 note_iteration_stmt_body_end (bool prev)
3526 {
3527   if (switch_stack)
3528     switch_stack->in_loop_body_p = prev;
3529 }
3530
3531 /* Convert a case constant VALUE in a switch to the type TYPE of the switch
3532    condition.  Note that if TYPE and VALUE are already integral we don't
3533    really do the conversion because the language-independent
3534    warning/optimization code will work better that way.  */
3535
3536 static tree
3537 case_conversion (tree type, tree value)
3538 {
3539   if (value == NULL_TREE)
3540     return value;
3541
3542   value = mark_rvalue_use (value);
3543
3544   if (cxx_dialect >= cxx11
3545       && (SCOPED_ENUM_P (type)
3546           || !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (value))))
3547     {
3548       if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3549         type = type_promotes_to (type);
3550       value = (perform_implicit_conversion_flags
3551                (type, value, tf_warning_or_error,
3552                 LOOKUP_IMPLICIT | LOOKUP_NO_NON_INTEGRAL));
3553     }
3554   return cxx_constant_value (value);
3555 }
3556
3557 /* Note that we've seen a definition of a case label, and complain if this
3558    is a bad place for one.  */
3559
3560 tree
3561 finish_case_label (location_t loc, tree low_value, tree high_value)
3562 {
3563   tree cond, r;
3564   cp_binding_level *p;
3565   tree type;
3566
3567   if (low_value == NULL_TREE && high_value == NULL_TREE)
3568     switch_stack->has_default_p = true;
3569
3570   if (processing_template_decl)
3571     {
3572       tree label;
3573
3574       /* For templates, just add the case label; we'll do semantic
3575          analysis at instantiation-time.  */
3576       label = build_decl (loc, LABEL_DECL, NULL_TREE, NULL_TREE);
3577       return add_stmt (build_case_label (low_value, high_value, label));
3578     }
3579
3580   /* Find the condition on which this switch statement depends.  */
3581   cond = SWITCH_STMT_COND (switch_stack->switch_stmt);
3582   if (cond && TREE_CODE (cond) == TREE_LIST)
3583     cond = TREE_VALUE (cond);
3584
3585   if (!check_switch_goto (switch_stack->level))
3586     return error_mark_node;
3587
3588   type = SWITCH_STMT_TYPE (switch_stack->switch_stmt);
3589
3590   low_value = case_conversion (type, low_value);
3591   high_value = case_conversion (type, high_value);
3592
3593   r = c_add_case_label (loc, switch_stack->cases, cond, type,
3594                         low_value, high_value,
3595                         &switch_stack->outside_range_p);
3596
3597   /* After labels, make any new cleanups in the function go into their
3598      own new (temporary) binding contour.  */
3599   for (p = current_binding_level;
3600        p->kind != sk_function_parms;
3601        p = p->level_chain)
3602     p->more_cleanups_ok = 0;
3603
3604   return r;
3605 }
3606 \f
3607 struct typename_info {
3608   tree scope;
3609   tree name;
3610   tree template_id;
3611   bool enum_p;
3612   bool class_p;
3613 };
3614
3615 struct typename_hasher : ggc_ptr_hash<tree_node>
3616 {
3617   typedef typename_info *compare_type;
3618
3619   /* Hash a TYPENAME_TYPE.  */
3620
3621   static hashval_t
3622   hash (tree t)
3623   {
3624     hashval_t hash;
3625
3626     hash = (htab_hash_pointer (TYPE_CONTEXT (t))
3627             ^ htab_hash_pointer (TYPE_IDENTIFIER (t)));
3628
3629     return hash;
3630   }
3631
3632   /* Compare two TYPENAME_TYPEs.  */
3633
3634   static bool
3635   equal (tree t1, const typename_info *t2)
3636   {
3637     return (TYPE_IDENTIFIER (t1) == t2->name
3638             && TYPE_CONTEXT (t1) == t2->scope
3639             && TYPENAME_TYPE_FULLNAME (t1) == t2->template_id
3640             && TYPENAME_IS_ENUM_P (t1) == t2->enum_p
3641             && TYPENAME_IS_CLASS_P (t1) == t2->class_p);
3642   }
3643 };
3644
3645 /* Build a TYPENAME_TYPE.  If the type is `typename T::t', CONTEXT is
3646    the type of `T', NAME is the IDENTIFIER_NODE for `t'.
3647
3648    Returns the new TYPENAME_TYPE.  */
3649
3650 static GTY (()) hash_table<typename_hasher> *typename_htab;
3651
3652 tree
3653 build_typename_type (tree context, tree name, tree fullname,
3654                      enum tag_types tag_type)
3655 {
3656   tree t;
3657   tree d;
3658   typename_info ti;
3659   tree *e;
3660   hashval_t hash;
3661
3662   if (typename_htab == NULL)
3663     typename_htab = hash_table<typename_hasher>::create_ggc (61);
3664
3665   ti.scope = FROB_CONTEXT (context);
3666   ti.name = name;
3667   ti.template_id = fullname;
3668   ti.enum_p = tag_type == enum_type;
3669   ti.class_p = (tag_type == class_type
3670                 || tag_type == record_type
3671                 || tag_type == union_type);
3672   hash =  (htab_hash_pointer (ti.scope)
3673            ^ htab_hash_pointer (ti.name));
3674
3675   /* See if we already have this type.  */
3676   e = typename_htab->find_slot_with_hash (&ti, hash, INSERT);
3677   if (*e)
3678     t = *e;
3679   else
3680     {
3681       /* Build the TYPENAME_TYPE.  */
3682       t = cxx_make_type (TYPENAME_TYPE);
3683       TYPE_CONTEXT (t) = ti.scope;
3684       TYPENAME_TYPE_FULLNAME (t) = ti.template_id;
3685       TYPENAME_IS_ENUM_P (t) = ti.enum_p;
3686       TYPENAME_IS_CLASS_P (t) = ti.class_p;
3687
3688       /* Build the corresponding TYPE_DECL.  */
3689       d = build_decl (input_location, TYPE_DECL, name, t);
3690       TYPE_NAME (TREE_TYPE (d)) = d;
3691       TYPE_STUB_DECL (TREE_TYPE (d)) = d;
3692       DECL_CONTEXT (d) = FROB_CONTEXT (context);
3693       DECL_ARTIFICIAL (d) = 1;
3694
3695       /* Store it in the hash table.  */
3696       *e = t;
3697
3698       /* TYPENAME_TYPEs must always be compared structurally, because
3699          they may or may not resolve down to another type depending on
3700          the currently open classes. */
3701       SET_TYPE_STRUCTURAL_EQUALITY (t);
3702     }
3703
3704   return t;
3705 }
3706
3707 /* Resolve `typename CONTEXT::NAME'.  TAG_TYPE indicates the tag
3708    provided to name the type.  Returns an appropriate type, unless an
3709    error occurs, in which case error_mark_node is returned.  If we
3710    locate a non-artificial TYPE_DECL and TF_KEEP_TYPE_DECL is set, we
3711    return that, rather than the _TYPE it corresponds to, in other
3712    cases we look through the type decl.  If TF_ERROR is set, complain
3713    about errors, otherwise be quiet.  */
3714
3715 tree
3716 make_typename_type (tree context, tree name, enum tag_types tag_type,
3717                     tsubst_flags_t complain)
3718 {
3719   tree fullname;
3720   tree t;
3721   bool want_template;
3722
3723   if (name == error_mark_node
3724       || context == NULL_TREE
3725       || context == error_mark_node)
3726     return error_mark_node;
3727
3728   if (TYPE_P (name))
3729     {
3730       if (!(TYPE_LANG_SPECIFIC (name)
3731             && (CLASSTYPE_IS_TEMPLATE (name)
3732                 || CLASSTYPE_USE_TEMPLATE (name))))
3733         name = TYPE_IDENTIFIER (name);
3734       else
3735         /* Create a TEMPLATE_ID_EXPR for the type.  */
3736         name = build_nt (TEMPLATE_ID_EXPR,
3737                          CLASSTYPE_TI_TEMPLATE (name),
3738                          CLASSTYPE_TI_ARGS (name));
3739     }
3740   else if (TREE_CODE (name) == TYPE_DECL)
3741     name = DECL_NAME (name);
3742
3743   fullname = name;
3744
3745   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
3746     {
3747       name = TREE_OPERAND (name, 0);
3748       if (DECL_TYPE_TEMPLATE_P (name))
3749         name = TREE_OPERAND (fullname, 0) = DECL_NAME (name);
3750       if (TREE_CODE (name) != IDENTIFIER_NODE)
3751         {
3752           if (complain & tf_error)
3753             error ("%qD is not a type", name);
3754           return error_mark_node;
3755         }
3756     }
3757   if (TREE_CODE (name) == TEMPLATE_DECL)
3758     {
3759       if (complain & tf_error)
3760         error ("%qD used without template parameters", name);
3761       return error_mark_node;
3762     }
3763   gcc_assert (identifier_p (name));
3764   gcc_assert (TYPE_P (context));
3765
3766   if (!MAYBE_CLASS_TYPE_P (context))
3767     {
3768       if (complain & tf_error)
3769         error ("%q#T is not a class", context);
3770       return error_mark_node;
3771     }
3772   
3773   /* When the CONTEXT is a dependent type,  NAME could refer to a
3774      dependent base class of CONTEXT.  But look inside it anyway
3775      if CONTEXT is a currently open scope, in case it refers to a
3776      member of the current instantiation or a non-dependent base;
3777      lookup will stop when we hit a dependent base.  */
3778   if (!dependent_scope_p (context))
3779     /* We should only set WANT_TYPE when we're a nested typename type.
3780        Then we can give better diagnostics if we find a non-type.  */
3781     t = lookup_field (context, name, 2, /*want_type=*/true);
3782   else
3783     t = NULL_TREE;
3784
3785   if ((!t || TREE_CODE (t) == TREE_LIST) && dependent_type_p (context))
3786     return build_typename_type (context, name, fullname, tag_type);
3787
3788   want_template = TREE_CODE (fullname) == TEMPLATE_ID_EXPR;
3789   
3790   if (!t)
3791     {
3792       if (complain & tf_error)
3793         {
3794           if (!COMPLETE_TYPE_P (context))
3795             cxx_incomplete_type_error (NULL_TREE, context);
3796           else
3797             error (want_template ? G_("no class template named %q#T in %q#T")
3798                    : G_("no type named %q#T in %q#T"), name, context);
3799         }
3800       return error_mark_node;
3801     }
3802   
3803   /* Pull out the template from an injected-class-name (or multiple).  */
3804   if (want_template)
3805     t = maybe_get_template_decl_from_type_decl (t);
3806
3807   if (TREE_CODE (t) == TREE_LIST)
3808     {
3809       if (complain & tf_error)
3810         {
3811           error ("lookup of %qT in %qT is ambiguous", name, context);
3812           print_candidates (t);
3813         }
3814       return error_mark_node;
3815     }
3816
3817   if (want_template && !DECL_TYPE_TEMPLATE_P (t))
3818     {
3819       if (complain & tf_error)
3820         error ("%<typename %T::%D%> names %q#T, which is not a class template",
3821                context, name, t);
3822       return error_mark_node;
3823     }
3824   if (!want_template && TREE_CODE (t) != TYPE_DECL)
3825     {
3826       if (complain & tf_error)
3827         error ("%<typename %T::%D%> names %q#T, which is not a type",
3828                context, name, t);
3829       return error_mark_node;
3830     }
3831
3832   if (!perform_or_defer_access_check (TYPE_BINFO (context), t, t, complain))
3833     return error_mark_node;
3834
3835   /* If we are currently parsing a template and if T is a typedef accessed
3836      through CONTEXT then we need to remember and check access of T at
3837      template instantiation time.  */
3838   add_typedef_to_current_template_for_access_check (t, context, input_location);
3839
3840   if (want_template)
3841     return lookup_template_class (t, TREE_OPERAND (fullname, 1),
3842                                   NULL_TREE, context,
3843                                   /*entering_scope=*/0,
3844                                   complain | tf_user);
3845   
3846   if (DECL_ARTIFICIAL (t) || !(complain & tf_keep_type_decl))
3847     t = TREE_TYPE (t);
3848
3849   maybe_record_typedef_use (t);
3850
3851   return t;
3852 }
3853
3854 /* Resolve `CONTEXT::template NAME'.  Returns a TEMPLATE_DECL if the name
3855    can be resolved or an UNBOUND_CLASS_TEMPLATE, unless an error occurs,
3856    in which case error_mark_node is returned.
3857
3858    If PARM_LIST is non-NULL, also make sure that the template parameter
3859    list of TEMPLATE_DECL matches.
3860
3861    If COMPLAIN zero, don't complain about any errors that occur.  */
3862
3863 tree
3864 make_unbound_class_template (tree context, tree name, tree parm_list,
3865                              tsubst_flags_t complain)
3866 {
3867   tree t;
3868   tree d;
3869
3870   if (TYPE_P (name))
3871     name = TYPE_IDENTIFIER (name);
3872   else if (DECL_P (name))
3873     name = DECL_NAME (name);
3874   gcc_assert (identifier_p (name));
3875
3876   if (!dependent_type_p (context)
3877       || currently_open_class (context))
3878     {
3879       tree tmpl = NULL_TREE;
3880
3881       if (MAYBE_CLASS_TYPE_P (context))
3882         tmpl = lookup_field (context, name, 0, false);
3883
3884       if (tmpl && TREE_CODE (tmpl) == TYPE_DECL)
3885         tmpl = maybe_get_template_decl_from_type_decl (tmpl);
3886
3887       if (!tmpl || !DECL_TYPE_TEMPLATE_P (tmpl))
3888         {
3889           if (complain & tf_error)
3890             error ("no class template named %q#T in %q#T", name, context);
3891           return error_mark_node;
3892         }
3893
3894       if (parm_list
3895           && !comp_template_parms (DECL_TEMPLATE_PARMS (tmpl), parm_list))
3896         {
3897           if (complain & tf_error)
3898             {
3899               error ("template parameters do not match template %qD", tmpl);
3900               inform (DECL_SOURCE_LOCATION (tmpl),
3901                       "%qD declared here", tmpl);
3902             }
3903           return error_mark_node;
3904         }
3905
3906       if (!perform_or_defer_access_check (TYPE_BINFO (context), tmpl, tmpl,
3907                                           complain))
3908         return error_mark_node;
3909
3910       return tmpl;
3911     }
3912
3913   /* Build the UNBOUND_CLASS_TEMPLATE.  */
3914   t = cxx_make_type (UNBOUND_CLASS_TEMPLATE);
3915   TYPE_CONTEXT (t) = FROB_CONTEXT (context);
3916   TREE_TYPE (t) = NULL_TREE;
3917   SET_TYPE_STRUCTURAL_EQUALITY (t);
3918
3919   /* Build the corresponding TEMPLATE_DECL.  */
3920   d = build_decl (input_location, TEMPLATE_DECL, name, t);
3921   TYPE_NAME (TREE_TYPE (d)) = d;
3922   TYPE_STUB_DECL (TREE_TYPE (d)) = d;
3923   DECL_CONTEXT (d) = FROB_CONTEXT (context);
3924   DECL_ARTIFICIAL (d) = 1;
3925   DECL_TEMPLATE_PARMS (d) = parm_list;
3926
3927   return t;
3928 }
3929
3930 \f
3931
3932 /* Push the declarations of builtin types into the global namespace.
3933    RID_INDEX is the index of the builtin type in the array
3934    RID_POINTERS.  NAME is the name used when looking up the builtin
3935    type.  TYPE is the _TYPE node for the builtin type.
3936
3937    The calls to set_global_binding below should be
3938    eliminated.  Built-in types should not be looked up name; their
3939    names are keywords that the parser can recognize.  However, there
3940    is code in c-common.c that uses identifier_global_value to look up
3941    built-in types by name.  */
3942
3943 void
3944 record_builtin_type (enum rid rid_index,
3945                      const char* name,
3946                      tree type)
3947 {
3948   tree decl = NULL_TREE;
3949
3950   if (name)
3951     {
3952       tree tname = get_identifier (name);
3953       tree tdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, tname, type);
3954       DECL_ARTIFICIAL (tdecl) = 1;
3955       set_global_binding (tdecl);
3956       decl = tdecl;
3957     }
3958
3959   if ((int) rid_index < (int) RID_MAX)
3960     if (tree rname = ridpointers[(int) rid_index])
3961       if (!decl || DECL_NAME (decl) != rname)
3962         {
3963           tree rdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, rname, type);
3964           DECL_ARTIFICIAL (rdecl) = 1;
3965           set_global_binding (rdecl);
3966           if (!decl)
3967             decl = rdecl;
3968         }
3969
3970   if (decl)
3971     {
3972       if (!TYPE_NAME (type))
3973         TYPE_NAME (type) = decl;
3974       debug_hooks->type_decl (decl, 0);
3975     }
3976 }
3977
3978 /* Push a type into the namespace so that the back ends ignore it.  */
3979
3980 static void
3981 record_unknown_type (tree type, const char* name)
3982 {
3983   tree decl = pushdecl (build_decl (UNKNOWN_LOCATION,
3984                                     TYPE_DECL, get_identifier (name), type));
3985   /* Make sure the "unknown type" typedecl gets ignored for debug info.  */
3986   DECL_IGNORED_P (decl) = 1;
3987   TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
3988   TYPE_SIZE (type) = TYPE_SIZE (void_type_node);
3989   SET_TYPE_ALIGN (type, 1);
3990   TYPE_USER_ALIGN (type) = 0;
3991   SET_TYPE_MODE (type, TYPE_MODE (void_type_node));
3992 }
3993
3994 /* Create all the predefined identifiers.  */
3995
3996 static void
3997 initialize_predefined_identifiers (void)
3998 {
3999   struct predefined_identifier
4000   {
4001     const char *name; /* Name.  */
4002     tree *node;  /* Node to store it in.  */
4003     cp_identifier_kind kind;  /* Kind of identifier.  */
4004   };
4005
4006   /* A table of identifiers to create at startup.  */
4007   static const predefined_identifier predefined_identifiers[] = {
4008     {"C++", &lang_name_cplusplus, cik_normal},
4009     {"C", &lang_name_c, cik_normal},
4010     /* Some of these names have a trailing space so that it is
4011        impossible for them to conflict with names written by users.  */
4012     {"__ct ", &ctor_identifier, cik_ctor},
4013     {"__ct_base ", &base_ctor_identifier, cik_ctor},
4014     {"__ct_comp ", &complete_ctor_identifier, cik_ctor},
4015     {"__dt ", &dtor_identifier, cik_dtor},
4016     {"__dt_base ", &base_dtor_identifier, cik_dtor},
4017     {"__dt_comp ", &complete_dtor_identifier, cik_dtor},
4018     {"__dt_del ", &deleting_dtor_identifier, cik_dtor},
4019     {"__conv_op ", &conv_op_identifier, cik_conv_op},
4020     {"__in_chrg", &in_charge_identifier, cik_normal},
4021     {"this", &this_identifier, cik_normal},
4022     {"__delta", &delta_identifier, cik_normal},
4023     {"__pfn", &pfn_identifier, cik_normal},
4024     {"_vptr", &vptr_identifier, cik_normal},
4025     {"__vtt_parm", &vtt_parm_identifier, cik_normal},
4026     {"::", &global_identifier, cik_normal},
4027     {"std", &std_identifier, cik_normal},
4028       /* The demangler expects anonymous namespaces to be called
4029          something starting with '_GLOBAL__N_'.  It no longer needs
4030          to be unique to the TU.  */
4031     {"_GLOBAL__N_1", &anon_identifier, cik_normal},
4032     {"auto", &auto_identifier, cik_normal},
4033     {"decltype(auto)", &decltype_auto_identifier, cik_normal},
4034     {"initializer_list", &init_list_identifier, cik_normal},
4035     {NULL, NULL, cik_normal}
4036   };
4037
4038   for (const predefined_identifier *pid = predefined_identifiers;
4039        pid->name; ++pid)
4040     {
4041       *pid->node = get_identifier (pid->name);
4042       /* Some of these identifiers already have a special kind.  */
4043       if (pid->kind != cik_normal)
4044         set_identifier_kind (*pid->node, pid->kind);
4045     }
4046 }
4047
4048 /* Create the predefined scalar types of C,
4049    and some nodes representing standard constants (0, 1, (void *)0).
4050    Initialize the global binding level.
4051    Make definitions for built-in primitive functions.  */
4052
4053 void
4054 cxx_init_decl_processing (void)
4055 {
4056   tree void_ftype;
4057   tree void_ftype_ptr;
4058
4059   /* Create all the identifiers we need.  */
4060   initialize_predefined_identifiers ();
4061
4062   /* Create the global variables.  */
4063   push_to_top_level ();
4064
4065   current_function_decl = NULL_TREE;
4066   current_binding_level = NULL;
4067   /* Enter the global namespace.  */
4068   gcc_assert (global_namespace == NULL_TREE);
4069   global_namespace = build_lang_decl (NAMESPACE_DECL, global_identifier,
4070                                       void_type_node);
4071   TREE_PUBLIC (global_namespace) = 1;
4072   DECL_CONTEXT (global_namespace)
4073     = build_translation_unit_decl (get_identifier (main_input_filename));
4074   /* Remember whether we want the empty class passing ABI change warning
4075      in this TU.  */
4076   TRANSLATION_UNIT_WARN_EMPTY_P (DECL_CONTEXT (global_namespace))
4077     = warn_abi && abi_version_crosses (12);
4078   debug_hooks->register_main_translation_unit
4079     (DECL_CONTEXT (global_namespace));
4080   begin_scope (sk_namespace, global_namespace);
4081   current_namespace = global_namespace;
4082
4083   if (flag_visibility_ms_compat)
4084     default_visibility = VISIBILITY_HIDDEN;
4085
4086   /* Initially, C.  */
4087   current_lang_name = lang_name_c;
4088
4089   /* Create the `std' namespace.  */
4090   push_namespace (std_identifier);
4091   std_node = current_namespace;
4092   pop_namespace ();
4093
4094   flag_noexcept_type = (cxx_dialect >= cxx17);
4095   /* There's no fixed location for <command-line>, the current
4096      location is <builtins>, which is somewhat confusing.  */
4097   if (!flag_new_for_scope)
4098     warning_at (UNKNOWN_LOCATION, OPT_Wdeprecated,
4099                 "%<-fno-for-scope%> is deprecated");
4100   if (flag_friend_injection)
4101     warning_at (UNKNOWN_LOCATION, OPT_Wdeprecated,
4102                 "%<-ffriend-injection%> is deprecated");
4103
4104   c_common_nodes_and_builtins ();
4105
4106   integer_two_node = build_int_cst (NULL_TREE, 2);
4107
4108   /* Guess at the initial static decls size.  */
4109   vec_alloc (static_decls, 500);
4110
4111   /* ... and keyed classes.  */
4112   vec_alloc (keyed_classes, 100);
4113
4114   record_builtin_type (RID_BOOL, "bool", boolean_type_node);
4115   truthvalue_type_node = boolean_type_node;
4116   truthvalue_false_node = boolean_false_node;
4117   truthvalue_true_node = boolean_true_node;
4118
4119   empty_except_spec = build_tree_list (NULL_TREE, NULL_TREE);
4120   noexcept_true_spec = build_tree_list (boolean_true_node, NULL_TREE);
4121   noexcept_false_spec = build_tree_list (boolean_false_node, NULL_TREE);
4122   noexcept_deferred_spec = build_tree_list (make_node (DEFERRED_NOEXCEPT),
4123                                             NULL_TREE);
4124
4125 #if 0
4126   record_builtin_type (RID_MAX, NULL, string_type_node);
4127 #endif
4128
4129   delta_type_node = ptrdiff_type_node;
4130   vtable_index_type = ptrdiff_type_node;
4131
4132   vtt_parm_type = build_pointer_type (const_ptr_type_node);
4133   void_ftype = build_function_type_list (void_type_node, NULL_TREE);
4134   void_ftype_ptr = build_function_type_list (void_type_node,
4135                                              ptr_type_node, NULL_TREE);
4136   void_ftype_ptr
4137     = build_exception_variant (void_ftype_ptr, empty_except_spec);
4138
4139   /* Create the conversion operator marker.  This operator's DECL_NAME
4140      is in the identifier table, so we can use identifier equality to
4141      find it.  */
4142   conv_op_marker = build_lang_decl (FUNCTION_DECL, conv_op_identifier,
4143                                     void_ftype);
4144
4145   /* C++ extensions */
4146
4147   unknown_type_node = make_node (LANG_TYPE);
4148   record_unknown_type (unknown_type_node, "unknown type");
4149
4150   /* Indirecting an UNKNOWN_TYPE node yields an UNKNOWN_TYPE node.  */
4151   TREE_TYPE (unknown_type_node) = unknown_type_node;
4152
4153   /* Looking up TYPE_POINTER_TO and TYPE_REFERENCE_TO yield the same
4154      result.  */
4155   TYPE_POINTER_TO (unknown_type_node) = unknown_type_node;
4156   TYPE_REFERENCE_TO (unknown_type_node) = unknown_type_node;
4157
4158   init_list_type_node = make_node (LANG_TYPE);
4159   record_unknown_type (init_list_type_node, "init list");
4160
4161   {
4162     /* Make sure we get a unique function type, so we can give
4163        its pointer type a name.  (This wins for gdb.) */
4164     tree vfunc_type = make_node (FUNCTION_TYPE);
4165     TREE_TYPE (vfunc_type) = integer_type_node;
4166     TYPE_ARG_TYPES (vfunc_type) = NULL_TREE;
4167     layout_type (vfunc_type);
4168
4169     vtable_entry_type = build_pointer_type (vfunc_type);
4170   }
4171   record_builtin_type (RID_MAX, "__vtbl_ptr_type", vtable_entry_type);
4172
4173   vtbl_type_node
4174     = build_cplus_array_type (vtable_entry_type, NULL_TREE);
4175   layout_type (vtbl_type_node);
4176   vtbl_type_node = cp_build_qualified_type (vtbl_type_node, TYPE_QUAL_CONST);
4177   record_builtin_type (RID_MAX, NULL, vtbl_type_node);
4178   vtbl_ptr_type_node = build_pointer_type (vtable_entry_type);
4179   layout_type (vtbl_ptr_type_node);
4180   record_builtin_type (RID_MAX, NULL, vtbl_ptr_type_node);
4181
4182   push_namespace (get_identifier ("__cxxabiv1"));
4183   abi_node = current_namespace;
4184   pop_namespace ();
4185
4186   global_type_node = make_node (LANG_TYPE);
4187   record_unknown_type (global_type_node, "global type");
4188
4189   any_targ_node = make_node (LANG_TYPE);
4190   record_unknown_type (any_targ_node, "any type");
4191
4192   /* Now, C++.  */
4193   current_lang_name = lang_name_cplusplus;
4194
4195   if (aligned_new_threshold > 1
4196       && !pow2p_hwi (aligned_new_threshold))
4197     {
4198       error ("-faligned-new=%d is not a power of two", aligned_new_threshold);
4199       aligned_new_threshold = 1;
4200     }
4201   if (aligned_new_threshold == -1)
4202     aligned_new_threshold = (cxx_dialect >= cxx17) ? 1 : 0;
4203   if (aligned_new_threshold == 1)
4204     aligned_new_threshold = malloc_alignment () / BITS_PER_UNIT;
4205
4206   {
4207     tree newattrs, extvisattr;
4208     tree newtype, deltype;
4209     tree ptr_ftype_sizetype;
4210     tree new_eh_spec;
4211
4212     ptr_ftype_sizetype
4213       = build_function_type_list (ptr_type_node, size_type_node, NULL_TREE);
4214     if (cxx_dialect == cxx98)
4215       {
4216         tree bad_alloc_id;
4217         tree bad_alloc_type_node;
4218         tree bad_alloc_decl;
4219
4220         push_namespace (std_identifier);
4221         bad_alloc_id = get_identifier ("bad_alloc");
4222         bad_alloc_type_node = make_class_type (RECORD_TYPE);
4223         TYPE_CONTEXT (bad_alloc_type_node) = current_namespace;
4224         bad_alloc_decl
4225           = create_implicit_typedef (bad_alloc_id, bad_alloc_type_node);
4226         DECL_CONTEXT (bad_alloc_decl) = current_namespace;
4227         pop_namespace ();
4228
4229         new_eh_spec
4230           = add_exception_specifier (NULL_TREE, bad_alloc_type_node, -1);
4231       }
4232     else
4233       new_eh_spec = noexcept_false_spec;
4234
4235     /* Ensure attribs.c is initialized.  */
4236     init_attributes ();
4237
4238     /* Ensure constraint.cc is initialized. */
4239     init_constraint_processing ();
4240
4241     extvisattr = build_tree_list (get_identifier ("externally_visible"),
4242                                   NULL_TREE);
4243     newattrs = tree_cons (get_identifier ("alloc_size"),
4244                           build_tree_list (NULL_TREE, integer_one_node),
4245                           extvisattr);
4246     newtype = cp_build_type_attribute_variant (ptr_ftype_sizetype, newattrs);
4247     newtype = build_exception_variant (newtype, new_eh_spec);
4248     deltype = cp_build_type_attribute_variant (void_ftype_ptr, extvisattr);
4249     deltype = build_exception_variant (deltype, empty_except_spec);
4250     tree opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
4251     DECL_IS_MALLOC (opnew) = 1;
4252     DECL_IS_OPERATOR_NEW (opnew) = 1;
4253     opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
4254     DECL_IS_MALLOC (opnew) = 1;
4255     DECL_IS_OPERATOR_NEW (opnew) = 1;
4256     push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4257     push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4258     if (flag_sized_deallocation)
4259       {
4260         /* Also push the sized deallocation variants:
4261              void operator delete(void*, std::size_t) throw();
4262              void operator delete[](void*, std::size_t) throw();  */
4263         tree void_ftype_ptr_size
4264           = build_function_type_list (void_type_node, ptr_type_node,
4265                                       size_type_node, NULL_TREE);
4266         deltype = cp_build_type_attribute_variant (void_ftype_ptr_size,
4267                                                    extvisattr);
4268         deltype = build_exception_variant (deltype, empty_except_spec);
4269         push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4270         push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4271       }
4272
4273     if (aligned_new_threshold)
4274       {
4275         push_namespace (std_identifier);
4276         tree align_id = get_identifier ("align_val_t");
4277         align_type_node = start_enum (align_id, NULL_TREE, size_type_node,
4278                                       NULL_TREE, /*scoped*/true, NULL);
4279         pop_namespace ();
4280
4281         /* operator new (size_t, align_val_t); */
4282         newtype = build_function_type_list (ptr_type_node, size_type_node,
4283                                             align_type_node, NULL_TREE);
4284         newtype = cp_build_type_attribute_variant (newtype, newattrs);
4285         newtype = build_exception_variant (newtype, new_eh_spec);
4286         opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
4287         DECL_IS_MALLOC (opnew) = 1;
4288         DECL_IS_OPERATOR_NEW (opnew) = 1;
4289         opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
4290         DECL_IS_MALLOC (opnew) = 1;
4291         DECL_IS_OPERATOR_NEW (opnew) = 1;
4292
4293         /* operator delete (void *, align_val_t); */
4294         deltype = build_function_type_list (void_type_node, ptr_type_node,
4295                                             align_type_node, NULL_TREE);
4296         deltype = cp_build_type_attribute_variant (deltype, extvisattr);
4297         deltype = build_exception_variant (deltype, empty_except_spec);
4298         push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4299         push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4300
4301         if (flag_sized_deallocation)
4302           {
4303             /* operator delete (void *, size_t, align_val_t); */
4304             deltype = build_function_type_list (void_type_node, ptr_type_node,
4305                                                 size_type_node, align_type_node,
4306                                                 NULL_TREE);
4307             deltype = cp_build_type_attribute_variant (deltype, extvisattr);
4308             deltype = build_exception_variant (deltype, empty_except_spec);
4309             push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4310             push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4311           }
4312       }
4313
4314     nullptr_type_node = make_node (NULLPTR_TYPE);
4315     TYPE_SIZE (nullptr_type_node) = bitsize_int (GET_MODE_BITSIZE (ptr_mode));
4316     TYPE_SIZE_UNIT (nullptr_type_node) = size_int (GET_MODE_SIZE (ptr_mode));
4317     TYPE_UNSIGNED (nullptr_type_node) = 1;
4318     TYPE_PRECISION (nullptr_type_node) = GET_MODE_BITSIZE (ptr_mode);
4319     if (abi_version_at_least (9))
4320       SET_TYPE_ALIGN (nullptr_type_node, GET_MODE_ALIGNMENT (ptr_mode));
4321     SET_TYPE_MODE (nullptr_type_node, ptr_mode);
4322     record_builtin_type (RID_MAX, "decltype(nullptr)", nullptr_type_node);
4323     nullptr_node = build_int_cst (nullptr_type_node, 0);
4324   }
4325
4326   abort_fndecl
4327     = build_library_fn_ptr ("__cxa_pure_virtual", void_ftype,
4328                             ECF_NORETURN | ECF_NOTHROW | ECF_COLD);
4329
4330   /* Perform other language dependent initializations.  */
4331   init_class_processing ();
4332   init_rtti_processing ();
4333   init_template_processing ();
4334
4335   if (flag_exceptions)
4336     init_exception_processing ();
4337
4338   if (! supports_one_only ())
4339     flag_weak = 0;
4340
4341   make_fname_decl = cp_make_fname_decl;
4342   start_fname_decls ();
4343
4344   /* Show we use EH for cleanups.  */
4345   if (flag_exceptions)
4346     using_eh_for_cleanups ();
4347 }
4348
4349 /* Generate an initializer for a function naming variable from
4350    NAME. NAME may be NULL, to indicate a dependent name.  TYPE_P is
4351    filled in with the type of the init.  */
4352
4353 tree
4354 cp_fname_init (const char* name, tree *type_p)
4355 {
4356   tree domain = NULL_TREE;
4357   tree type;
4358   tree init = NULL_TREE;
4359   size_t length = 0;
4360
4361   if (name)
4362     {
4363       length = strlen (name);
4364       domain = build_index_type (size_int (length));
4365       init = build_string (length + 1, name);
4366     }
4367
4368   type = cp_build_qualified_type (char_type_node, TYPE_QUAL_CONST);
4369   type = build_cplus_array_type (type, domain);
4370
4371   *type_p = type;
4372
4373   if (init)
4374     TREE_TYPE (init) = type;
4375   else
4376     init = error_mark_node;
4377
4378   return init;
4379 }
4380
4381 /* Create the VAR_DECL for __FUNCTION__ etc. ID is the name to give
4382    the decl, LOC is the location to give the decl, NAME is the
4383    initialization string and TYPE_DEP indicates whether NAME depended
4384    on the type of the function. We make use of that to detect
4385    __PRETTY_FUNCTION__ inside a template fn. This is being done lazily
4386    at the point of first use, so we mustn't push the decl now.  */
4387
4388 static tree
4389 cp_make_fname_decl (location_t loc, tree id, int type_dep)
4390 {
4391   const char *const name = (type_dep && processing_template_decl
4392                             ? NULL : fname_as_string (type_dep));
4393   tree type;
4394   tree init = cp_fname_init (name, &type);
4395   tree decl = build_decl (loc, VAR_DECL, id, type);
4396
4397   if (name)
4398     free (CONST_CAST (char *, name));
4399
4400   TREE_STATIC (decl) = 1;
4401   TREE_READONLY (decl) = 1;
4402   DECL_ARTIFICIAL (decl) = 1;
4403
4404   TREE_USED (decl) = 1;
4405
4406   if (current_function_decl)
4407     {
4408       DECL_CONTEXT (decl) = current_function_decl;
4409       decl = pushdecl_outermost_localscope (decl);
4410       cp_finish_decl (decl, init, /*init_const_expr_p=*/false, NULL_TREE,
4411                       LOOKUP_ONLYCONVERTING);
4412     }
4413   else
4414     {
4415       DECL_THIS_STATIC (decl) = true;
4416       pushdecl_top_level_and_finish (decl, init);
4417     }
4418
4419   return decl;
4420 }
4421
4422 static tree
4423 builtin_function_1 (tree decl, tree context, bool is_global)
4424 {
4425   tree          id = DECL_NAME (decl);
4426   const char *name = IDENTIFIER_POINTER (id);
4427
4428   retrofit_lang_decl (decl);
4429
4430   DECL_ARTIFICIAL (decl) = 1;
4431   SET_DECL_LANGUAGE (decl, lang_c);
4432   /* Runtime library routines are, by definition, available in an
4433      external shared object.  */
4434   DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
4435   DECL_VISIBILITY_SPECIFIED (decl) = 1;
4436
4437   DECL_CONTEXT (decl) = context;
4438
4439   /* A function in the user's namespace should have an explicit
4440      declaration before it is used.  Mark the built-in function as
4441      anticipated but not actually declared.  */
4442   if (name[0] != '_' || name[1] != '_')
4443     DECL_ANTICIPATED (decl) = 1;
4444   else if (strncmp (name + 2, "builtin_", strlen ("builtin_")) != 0)
4445     {
4446       size_t len = strlen (name);
4447
4448       /* Treat __*_chk fortification functions as anticipated as well,
4449          unless they are __builtin_*.  */
4450       if (len > strlen ("___chk")
4451           && memcmp (name + len - strlen ("_chk"),
4452                      "_chk", strlen ("_chk") + 1) == 0)
4453         DECL_ANTICIPATED (decl) = 1;
4454     }
4455
4456   if (is_global)
4457     pushdecl_top_level (decl);
4458   else
4459     pushdecl (decl);
4460
4461   return decl;
4462 }
4463
4464 tree
4465 cxx_builtin_function (tree decl)
4466 {
4467   tree          id = DECL_NAME (decl);
4468   const char *name = IDENTIFIER_POINTER (id);
4469   /* All builtins that don't begin with an '_' should additionally
4470      go in the 'std' namespace.  */
4471   if (name[0] != '_')
4472     {
4473       tree decl2 = copy_node(decl);
4474       push_namespace (std_identifier);
4475       builtin_function_1 (decl2, std_node, false);
4476       pop_namespace ();
4477     }
4478
4479   return builtin_function_1 (decl, NULL_TREE, false);
4480 }
4481
4482 /* Like cxx_builtin_function, but guarantee the function is added to the global
4483    scope.  This is to allow function specific options to add new machine
4484    dependent builtins when the target ISA changes via attribute((target(...)))
4485    which saves space on program startup if the program does not use non-generic
4486    ISAs.  */
4487
4488 tree
4489 cxx_builtin_function_ext_scope (tree decl)
4490 {
4491
4492   tree          id = DECL_NAME (decl);
4493   const char *name = IDENTIFIER_POINTER (id);
4494   /* All builtins that don't begin with an '_' should additionally
4495      go in the 'std' namespace.  */
4496   if (name[0] != '_')
4497     {
4498       tree decl2 = copy_node(decl);
4499       push_namespace (std_identifier);
4500       builtin_function_1 (decl2, std_node, true);
4501       pop_namespace ();
4502     }
4503
4504   return builtin_function_1 (decl, NULL_TREE, true);
4505 }
4506
4507 /* Generate a FUNCTION_DECL with the typical flags for a runtime library
4508    function.  Not called directly.  */
4509
4510 static tree
4511 build_library_fn (tree name, enum tree_code operator_code, tree type,
4512                   int ecf_flags)
4513 {
4514   tree fn = build_lang_decl (FUNCTION_DECL, name, type);
4515   DECL_EXTERNAL (fn) = 1;
4516   TREE_PUBLIC (fn) = 1;
4517   DECL_ARTIFICIAL (fn) = 1;
4518   DECL_OVERLOADED_OPERATOR_CODE_RAW (fn)
4519     = OVL_OP_INFO (false, operator_code)->ovl_op_code;
4520   SET_DECL_LANGUAGE (fn, lang_c);
4521   /* Runtime library routines are, by definition, available in an
4522      external shared object.  */
4523   DECL_VISIBILITY (fn) = VISIBILITY_DEFAULT;
4524   DECL_VISIBILITY_SPECIFIED (fn) = 1;
4525   set_call_expr_flags (fn, ecf_flags);
4526   return fn;
4527 }
4528
4529 /* Returns the _DECL for a library function with C++ linkage.  */
4530
4531 static tree
4532 build_cp_library_fn (tree name, enum tree_code operator_code, tree type,
4533                      int ecf_flags)
4534 {
4535   tree fn = build_library_fn (name, operator_code, type, ecf_flags);
4536   DECL_CONTEXT (fn) = FROB_CONTEXT (current_namespace);
4537   SET_DECL_LANGUAGE (fn, lang_cplusplus);
4538   return fn;
4539 }
4540
4541 /* Like build_library_fn, but takes a C string instead of an
4542    IDENTIFIER_NODE.  */
4543
4544 tree
4545 build_library_fn_ptr (const char* name, tree type, int ecf_flags)
4546 {
4547   return build_library_fn (get_identifier (name), ERROR_MARK, type, ecf_flags);
4548 }
4549
4550 /* Like build_cp_library_fn, but takes a C string instead of an
4551    IDENTIFIER_NODE.  */
4552
4553 tree
4554 build_cp_library_fn_ptr (const char* name, tree type, int ecf_flags)
4555 {
4556   return build_cp_library_fn (get_identifier (name), ERROR_MARK, type,
4557                               ecf_flags);
4558 }
4559
4560 /* Like build_library_fn, but also pushes the function so that we will
4561    be able to find it via get_global_binding.  Also, the function
4562    may throw exceptions listed in RAISES.  */
4563
4564 tree
4565 push_library_fn (tree name, tree type, tree raises, int ecf_flags)
4566 {
4567   tree fn;
4568
4569   if (raises)
4570     type = build_exception_variant (type, raises);
4571
4572   fn = build_library_fn (name, ERROR_MARK, type, ecf_flags);
4573   pushdecl_top_level (fn);
4574   return fn;
4575 }
4576
4577 /* Like build_cp_library_fn, but also pushes the function so that it
4578    will be found by normal lookup.  */
4579
4580 static tree
4581 push_cp_library_fn (enum tree_code operator_code, tree type,
4582                     int ecf_flags)
4583 {
4584   tree fn = build_cp_library_fn (ovl_op_identifier (false, operator_code),
4585                                  operator_code, type, ecf_flags);
4586   pushdecl (fn);
4587   if (flag_tm)
4588     apply_tm_attr (fn, get_identifier ("transaction_safe"));
4589   return fn;
4590 }
4591
4592 /* Like push_library_fn, but takes a TREE_LIST of parm types rather than
4593    a FUNCTION_TYPE.  */
4594
4595 tree
4596 push_void_library_fn (tree name, tree parmtypes, int ecf_flags)
4597 {
4598   tree type = build_function_type (void_type_node, parmtypes);
4599   return push_library_fn (name, type, NULL_TREE, ecf_flags);
4600 }
4601
4602 /* Like push_library_fn, but also note that this function throws
4603    and does not return.  Used for __throw_foo and the like.  */
4604
4605 tree
4606 push_throw_library_fn (tree name, tree type)
4607 {
4608   tree fn = push_library_fn (name, type, NULL_TREE, ECF_NORETURN | ECF_COLD);
4609   return fn;
4610 }
4611 \f
4612 /* When we call finish_struct for an anonymous union, we create
4613    default copy constructors and such.  But, an anonymous union
4614    shouldn't have such things; this function undoes the damage to the
4615    anonymous union type T.
4616
4617    (The reason that we create the synthesized methods is that we don't
4618    distinguish `union { int i; }' from `typedef union { int i; } U'.
4619    The first is an anonymous union; the second is just an ordinary
4620    union type.)  */
4621
4622 void
4623 fixup_anonymous_aggr (tree t)
4624 {
4625   /* Wipe out memory of synthesized methods.  */
4626   TYPE_HAS_USER_CONSTRUCTOR (t) = 0;
4627   TYPE_HAS_DEFAULT_CONSTRUCTOR (t) = 0;
4628   TYPE_HAS_COPY_CTOR (t) = 0;
4629   TYPE_HAS_CONST_COPY_CTOR (t) = 0;
4630   TYPE_HAS_COPY_ASSIGN (t) = 0;
4631   TYPE_HAS_CONST_COPY_ASSIGN (t) = 0;
4632
4633   /* Splice the implicitly generated functions out of TYPE_FIELDS.  */
4634   for (tree probe, *prev_p = &TYPE_FIELDS (t); (probe = *prev_p);)
4635     if (TREE_CODE (probe) == FUNCTION_DECL && DECL_ARTIFICIAL (probe))
4636       *prev_p = DECL_CHAIN (probe);
4637     else
4638       prev_p = &DECL_CHAIN (probe);
4639
4640   /* Anonymous aggregates cannot have fields with ctors, dtors or complex
4641      assignment operators (because they cannot have these methods themselves).
4642      For anonymous unions this is already checked because they are not allowed
4643      in any union, otherwise we have to check it.  */
4644   if (TREE_CODE (t) != UNION_TYPE)
4645     {
4646       tree field, type;
4647
4648       for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
4649         if (TREE_CODE (field) == FIELD_DECL)
4650           {
4651             type = TREE_TYPE (field);
4652             if (CLASS_TYPE_P (type))
4653               {
4654                 if (TYPE_NEEDS_CONSTRUCTING (type))
4655                   error ("member %q+#D with constructor not allowed "
4656                          "in anonymous aggregate", field);
4657                 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
4658                   error ("member %q+#D with destructor not allowed "
4659                          "in anonymous aggregate", field);
4660                 if (TYPE_HAS_COMPLEX_COPY_ASSIGN (type))
4661                   error ("member %q+#D with copy assignment operator "
4662                          "not allowed in anonymous aggregate", field);
4663               }
4664           }
4665     }
4666 }
4667
4668 /* Warn for an attribute located at LOCATION that appertains to the
4669    class type CLASS_TYPE that has not been properly placed after its
4670    class-key, in it class-specifier.  */
4671
4672 void
4673 warn_misplaced_attr_for_class_type (source_location location,
4674                                     tree class_type)
4675 {
4676   gcc_assert (OVERLOAD_TYPE_P (class_type));
4677
4678   if (warning_at (location, OPT_Wattributes,
4679                   "attribute ignored in declaration "
4680                   "of %q#T", class_type))
4681     inform (location,
4682             "attribute for %q#T must follow the %qs keyword",
4683             class_type, class_key_or_enum_as_string (class_type));
4684 }
4685
4686 /* Make sure that a declaration with no declarator is well-formed, i.e.
4687    just declares a tagged type or anonymous union.
4688
4689    Returns the type declared; or NULL_TREE if none.  */
4690
4691 tree
4692 check_tag_decl (cp_decl_specifier_seq *declspecs,
4693                 bool explicit_type_instantiation_p)
4694 {
4695   int saw_friend = decl_spec_seq_has_spec_p (declspecs, ds_friend);
4696   int saw_typedef = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
4697   /* If a class, struct, or enum type is declared by the DECLSPECS
4698      (i.e, if a class-specifier, enum-specifier, or non-typename
4699      elaborated-type-specifier appears in the DECLSPECS),
4700      DECLARED_TYPE is set to the corresponding type.  */
4701   tree declared_type = NULL_TREE;
4702   bool error_p = false;
4703
4704   if (declspecs->multiple_types_p)
4705     error ("multiple types in one declaration");
4706   else if (declspecs->redefined_builtin_type)
4707     {
4708       if (!in_system_header_at (input_location))
4709         permerror (declspecs->locations[ds_redefined_builtin_type_spec],
4710                    "redeclaration of C++ built-in type %qT",
4711                    declspecs->redefined_builtin_type);
4712       return NULL_TREE;
4713     }
4714
4715   if (declspecs->type
4716       && TYPE_P (declspecs->type)
4717       && ((TREE_CODE (declspecs->type) != TYPENAME_TYPE
4718            && MAYBE_CLASS_TYPE_P (declspecs->type))
4719           || TREE_CODE (declspecs->type) == ENUMERAL_TYPE))
4720     declared_type = declspecs->type;
4721   else if (declspecs->type == error_mark_node)
4722     error_p = true;
4723   if (declared_type == NULL_TREE && ! saw_friend && !error_p)
4724     permerror (input_location, "declaration does not declare anything");
4725   else if (declared_type != NULL_TREE && type_uses_auto (declared_type))
4726     {
4727       error_at (declspecs->locations[ds_type_spec],
4728                 "%<auto%> can only be specified for variables "
4729                 "or function declarations");
4730       return error_mark_node;
4731     }
4732   /* Check for an anonymous union.  */
4733   else if (declared_type && RECORD_OR_UNION_CODE_P (TREE_CODE (declared_type))
4734            && TYPE_UNNAMED_P (declared_type))
4735     {
4736       /* 7/3 In a simple-declaration, the optional init-declarator-list
4737          can be omitted only when declaring a class (clause 9) or
4738          enumeration (7.2), that is, when the decl-specifier-seq contains
4739          either a class-specifier, an elaborated-type-specifier with
4740          a class-key (9.1), or an enum-specifier.  In these cases and
4741          whenever a class-specifier or enum-specifier is present in the
4742          decl-specifier-seq, the identifiers in these specifiers are among
4743          the names being declared by the declaration (as class-name,
4744          enum-names, or enumerators, depending on the syntax).  In such
4745          cases, and except for the declaration of an unnamed bit-field (9.6),
4746          the decl-specifier-seq shall introduce one or more names into the
4747          program, or shall redeclare a name introduced by a previous
4748          declaration.  [Example:
4749              enum { };                  // ill-formed
4750              typedef class { };         // ill-formed
4751          --end example]  */
4752       if (saw_typedef)
4753         {
4754           error ("missing type-name in typedef-declaration");
4755           return NULL_TREE;
4756         }
4757       /* Anonymous unions are objects, so they can have specifiers.  */;
4758       SET_ANON_AGGR_TYPE_P (declared_type);
4759
4760       if (TREE_CODE (declared_type) != UNION_TYPE
4761           && !in_system_header_at (input_location))
4762         pedwarn (input_location, OPT_Wpedantic, "ISO C++ prohibits anonymous structs");
4763     }
4764
4765   else
4766     {
4767       if (decl_spec_seq_has_spec_p (declspecs, ds_inline))
4768         error_at (declspecs->locations[ds_inline],
4769                   "%<inline%> can only be specified for functions");
4770       else if (decl_spec_seq_has_spec_p (declspecs, ds_virtual))
4771         error_at (declspecs->locations[ds_virtual],
4772                   "%<virtual%> can only be specified for functions");
4773       else if (saw_friend
4774                && (!current_class_type
4775                    || current_scope () != current_class_type))
4776         error_at (declspecs->locations[ds_friend],
4777                   "%<friend%> can only be specified inside a class");
4778       else if (decl_spec_seq_has_spec_p (declspecs, ds_explicit))
4779         error_at (declspecs->locations[ds_explicit],
4780                   "%<explicit%> can only be specified for constructors");
4781       else if (declspecs->storage_class)
4782         error_at (declspecs->locations[ds_storage_class],
4783                   "a storage class can only be specified for objects "
4784                   "and functions");
4785       else if (decl_spec_seq_has_spec_p (declspecs, ds_const))
4786         error_at (declspecs->locations[ds_const],
4787                   "%<const%> can only be specified for objects and "
4788                   "functions");
4789       else if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
4790         error_at (declspecs->locations[ds_volatile],
4791                   "%<volatile%> can only be specified for objects and "
4792                   "functions");
4793       else if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
4794         error_at (declspecs->locations[ds_restrict],
4795                   "%<__restrict%> can only be specified for objects and "
4796                   "functions");
4797       else if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
4798         error_at (declspecs->locations[ds_thread],
4799                   "%<__thread%> can only be specified for objects "
4800                   "and functions");
4801       else if (saw_typedef)
4802         warning_at (declspecs->locations[ds_typedef], 0,
4803                     "%<typedef%> was ignored in this declaration");
4804       else if (decl_spec_seq_has_spec_p (declspecs,  ds_constexpr))
4805         error_at (declspecs->locations[ds_constexpr],
4806                   "%<constexpr%> cannot be used for type declarations");
4807     }
4808
4809   if (declspecs->attributes && warn_attributes && declared_type)
4810     {
4811       location_t loc;
4812       if (!CLASS_TYPE_P (declared_type)
4813           || !CLASSTYPE_TEMPLATE_INSTANTIATION (declared_type))
4814         /* For a non-template class, use the name location.  */
4815         loc = location_of (declared_type);
4816       else
4817         /* For a template class (an explicit instantiation), use the
4818            current location.  */
4819         loc = input_location;
4820
4821       if (explicit_type_instantiation_p)
4822         /* [dcl.attr.grammar]/4:
4823
4824                No attribute-specifier-seq shall appertain to an explicit
4825                instantiation.  */
4826         {
4827           if (warning_at (loc, OPT_Wattributes,
4828                           "attribute ignored in explicit instantiation %q#T",
4829                           declared_type))
4830             inform (loc,
4831                     "no attribute can be applied to "
4832                     "an explicit instantiation");
4833         }
4834       else
4835         warn_misplaced_attr_for_class_type (loc, declared_type);
4836     }
4837
4838   return declared_type;
4839 }
4840
4841 /* Called when a declaration is seen that contains no names to declare.
4842    If its type is a reference to a structure, union or enum inherited
4843    from a containing scope, shadow that tag name for the current scope
4844    with a forward reference.
4845    If its type defines a new named structure or union
4846    or defines an enum, it is valid but we need not do anything here.
4847    Otherwise, it is an error.
4848
4849    C++: may have to grok the declspecs to learn about static,
4850    complain for anonymous unions.
4851
4852    Returns the TYPE declared -- or NULL_TREE if none.  */
4853
4854 tree
4855 shadow_tag (cp_decl_specifier_seq *declspecs)
4856 {
4857   tree t = check_tag_decl (declspecs,
4858                            /*explicit_type_instantiation_p=*/false);
4859
4860   if (!t)
4861     return NULL_TREE;
4862
4863   if (maybe_process_partial_specialization (t) == error_mark_node)
4864     return NULL_TREE;
4865
4866   /* This is where the variables in an anonymous union are
4867      declared.  An anonymous union declaration looks like:
4868      union { ... } ;
4869      because there is no declarator after the union, the parser
4870      sends that declaration here.  */
4871   if (ANON_AGGR_TYPE_P (t))
4872     {
4873       fixup_anonymous_aggr (t);
4874
4875       if (TYPE_FIELDS (t))
4876         {
4877           tree decl = grokdeclarator (/*declarator=*/NULL,
4878                                       declspecs, NORMAL, 0, NULL);
4879           finish_anon_union (decl);
4880         }
4881     }
4882
4883   return t;
4884 }
4885 \f
4886 /* Decode a "typename", such as "int **", returning a ..._TYPE node.  */
4887
4888 tree
4889 groktypename (cp_decl_specifier_seq *type_specifiers,
4890               const cp_declarator *declarator,
4891               bool is_template_arg)
4892 {
4893   tree attrs;
4894   tree type;
4895   enum decl_context context
4896     = is_template_arg ? TEMPLATE_TYPE_ARG : TYPENAME;
4897   attrs = type_specifiers->attributes;
4898   type_specifiers->attributes = NULL_TREE;
4899   type = grokdeclarator (declarator, type_specifiers, context, 0, &attrs);
4900   if (attrs && type != error_mark_node)
4901     {
4902       if (CLASS_TYPE_P (type))
4903         warning (OPT_Wattributes, "ignoring attributes applied to class type %qT "
4904                  "outside of definition", type);
4905       else if (MAYBE_CLASS_TYPE_P (type))
4906         /* A template type parameter or other dependent type.  */
4907         warning (OPT_Wattributes, "ignoring attributes applied to dependent "
4908                  "type %qT without an associated declaration", type);
4909       else
4910         cplus_decl_attributes (&type, attrs, 0);
4911     }
4912   return type;
4913 }
4914
4915 /* Process a DECLARATOR for a function-scope variable declaration,
4916    namespace-scope variable declaration, or function declaration.
4917    (Function definitions go through start_function; class member
4918    declarations appearing in the body of the class go through
4919    grokfield.)  The DECL corresponding to the DECLARATOR is returned.
4920    If an error occurs, the error_mark_node is returned instead.
4921    
4922    DECLSPECS are the decl-specifiers for the declaration.  INITIALIZED is
4923    SD_INITIALIZED if an explicit initializer is present, or SD_DEFAULTED
4924    for an explicitly defaulted function, or SD_DELETED for an explicitly
4925    deleted function, but 0 (SD_UNINITIALIZED) if this is a variable
4926    implicitly initialized via a default constructor.  ATTRIBUTES and
4927    PREFIX_ATTRIBUTES are GNU attributes associated with this declaration.
4928
4929    The scope represented by the context of the returned DECL is pushed
4930    (if it is not the global namespace) and is assigned to
4931    *PUSHED_SCOPE_P.  The caller is then responsible for calling
4932    pop_scope on *PUSHED_SCOPE_P if it is set.  */
4933
4934 tree
4935 start_decl (const cp_declarator *declarator,
4936             cp_decl_specifier_seq *declspecs,
4937             int initialized,
4938             tree attributes,
4939             tree prefix_attributes,
4940             tree *pushed_scope_p)
4941 {
4942   tree decl;
4943   tree context;
4944   bool was_public;
4945   int flags;
4946   bool alias;
4947
4948   *pushed_scope_p = NULL_TREE;
4949
4950   /* An object declared as __attribute__((deprecated)) suppresses
4951      warnings of uses of other deprecated items.  */
4952   if (lookup_attribute ("deprecated", attributes))
4953     deprecated_state = DEPRECATED_SUPPRESS;
4954
4955   attributes = chainon (attributes, prefix_attributes);
4956
4957   decl = grokdeclarator (declarator, declspecs, NORMAL, initialized,
4958                          &attributes);
4959
4960   deprecated_state = DEPRECATED_NORMAL;
4961
4962   if (decl == NULL_TREE || VOID_TYPE_P (decl)
4963       || decl == error_mark_node)
4964     return error_mark_node;
4965
4966   context = CP_DECL_CONTEXT (decl);
4967   if (context != global_namespace)
4968     *pushed_scope_p = push_scope (context);
4969
4970   /* Is it valid for this decl to have an initializer at all?
4971      If not, set INITIALIZED to zero, which will indirectly
4972      tell `cp_finish_decl' to ignore the initializer once it is parsed.  */
4973   if (initialized
4974       && TREE_CODE (decl) == TYPE_DECL)
4975     {
4976       error ("typedef %qD is initialized (use decltype instead)", decl);
4977       return error_mark_node;
4978     }
4979
4980   if (initialized)
4981     {
4982       if (! toplevel_bindings_p ()
4983           && DECL_EXTERNAL (decl))
4984         warning (0, "declaration of %q#D has %<extern%> and is initialized",
4985                  decl);
4986       DECL_EXTERNAL (decl) = 0;
4987       if (toplevel_bindings_p ())
4988         TREE_STATIC (decl) = 1;
4989     }
4990   alias = lookup_attribute ("alias", DECL_ATTRIBUTES (decl)) != 0;
4991   
4992   if (alias && TREE_CODE (decl) == FUNCTION_DECL)
4993     record_key_method_defined (decl);
4994
4995   /* If this is a typedef that names the class for linkage purposes
4996      (7.1.3p8), apply any attributes directly to the type.  */
4997   if (TREE_CODE (decl) == TYPE_DECL
4998       && OVERLOAD_TYPE_P (TREE_TYPE (decl))
4999       && decl == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (decl))))
5000     flags = ATTR_FLAG_TYPE_IN_PLACE;
5001   else
5002     flags = 0;
5003
5004   /* Set attributes here so if duplicate decl, will have proper attributes.  */
5005   cplus_decl_attributes (&decl, attributes, flags);
5006
5007   /* Dllimported symbols cannot be defined.  Static data members (which
5008      can be initialized in-class and dllimported) go through grokfield,
5009      not here, so we don't need to exclude those decls when checking for
5010      a definition.  */
5011   if (initialized && DECL_DLLIMPORT_P (decl))
5012     {
5013       error ("definition of %q#D is marked %<dllimport%>", decl);
5014       DECL_DLLIMPORT_P (decl) = 0;
5015     }
5016
5017   /* If #pragma weak was used, mark the decl weak now.  */
5018   if (!processing_template_decl)
5019     maybe_apply_pragma_weak (decl);
5020
5021   if (TREE_CODE (decl) == FUNCTION_DECL
5022       && DECL_DECLARED_INLINE_P (decl)
5023       && DECL_UNINLINABLE (decl)
5024       && lookup_attribute ("noinline", DECL_ATTRIBUTES (decl)))
5025     warning_at (DECL_SOURCE_LOCATION (decl), 0,
5026                 "inline function %qD given attribute noinline", decl);
5027
5028   if (TYPE_P (context) && COMPLETE_TYPE_P (complete_type (context)))
5029     {
5030       bool this_tmpl = (processing_template_decl
5031                         > template_class_depth (context));
5032       if (VAR_P (decl))
5033         {
5034           tree field = lookup_field (context, DECL_NAME (decl), 0, false);
5035           if (field == NULL_TREE
5036               || !(VAR_P (field) || variable_template_p (field)))
5037             error ("%q+#D is not a static data member of %q#T", decl, context);
5038           else if (variable_template_p (field) && !this_tmpl)
5039             {
5040               if (DECL_LANG_SPECIFIC (decl)
5041                   && DECL_TEMPLATE_SPECIALIZATION (decl))
5042                 /* OK, specialization was already checked.  */;
5043               else
5044                 {
5045                   error_at (DECL_SOURCE_LOCATION (decl),
5046                             "non-member-template declaration of %qD", decl);
5047                   inform (DECL_SOURCE_LOCATION (field), "does not match "
5048                           "member template declaration here");
5049                   return error_mark_node;
5050                 }
5051             }
5052           else
5053             {
5054               if (variable_template_p (field))
5055                 field = DECL_TEMPLATE_RESULT (field);
5056
5057               if (DECL_CONTEXT (field) != context)
5058                 {
5059                   if (!same_type_p (DECL_CONTEXT (field), context))
5060                     permerror (input_location, "ISO C++ does not permit %<%T::%D%> "
5061                                "to be defined as %<%T::%D%>",
5062                                DECL_CONTEXT (field), DECL_NAME (decl),
5063                                context, DECL_NAME (decl));
5064                   DECL_CONTEXT (decl) = DECL_CONTEXT (field);
5065                 }
5066               /* Static data member are tricky; an in-class initialization
5067                  still doesn't provide a definition, so the in-class
5068                  declaration will have DECL_EXTERNAL set, but will have an
5069                  initialization.  Thus, duplicate_decls won't warn
5070                  about this situation, and so we check here.  */
5071               if (initialized && DECL_INITIALIZED_IN_CLASS_P (field))
5072                 error ("duplicate initialization of %qD", decl);
5073               field = duplicate_decls (decl, field,
5074                                        /*newdecl_is_friend=*/false);
5075               if (field == error_mark_node)
5076                 return error_mark_node;
5077               else if (field)
5078                 decl = field;
5079             }
5080         }
5081       else
5082         {
5083           tree field = check_classfn (context, decl,
5084                                       this_tmpl
5085                                       ? current_template_parms
5086                                       : NULL_TREE);
5087           if (field && field != error_mark_node
5088               && duplicate_decls (decl, field,
5089                                  /*newdecl_is_friend=*/false))
5090             decl = field;
5091         }
5092
5093       /* cp_finish_decl sets DECL_EXTERNAL if DECL_IN_AGGR_P is set.  */
5094       DECL_IN_AGGR_P (decl) = 0;
5095       /* Do not mark DECL as an explicit specialization if it was not
5096          already marked as an instantiation; a declaration should
5097          never be marked as a specialization unless we know what
5098          template is being specialized.  */
5099       if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
5100         {
5101           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
5102           if (TREE_CODE (decl) == FUNCTION_DECL)
5103             DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
5104                                   && DECL_DECLARED_INLINE_P (decl));
5105           else
5106             DECL_COMDAT (decl) = false;
5107
5108           /* [temp.expl.spec] An explicit specialization of a static data
5109              member of a template is a definition if the declaration
5110              includes an initializer; otherwise, it is a declaration.
5111
5112              We check for processing_specialization so this only applies
5113              to the new specialization syntax.  */
5114           if (!initialized && processing_specialization)
5115             DECL_EXTERNAL (decl) = 1;
5116         }
5117
5118       if (DECL_EXTERNAL (decl) && ! DECL_TEMPLATE_SPECIALIZATION (decl)
5119           /* Aliases are definitions. */
5120           && !alias)
5121         permerror (input_location, "declaration of %q#D outside of class is not definition",
5122                    decl);
5123     }
5124
5125   was_public = TREE_PUBLIC (decl);
5126
5127   /* Enter this declaration into the symbol table.  Don't push the plain
5128      VAR_DECL for a variable template.  */
5129   if (!template_parm_scope_p ()
5130       || !VAR_P (decl))
5131     decl = maybe_push_decl (decl);
5132
5133   if (processing_template_decl)
5134     decl = push_template_decl (decl);
5135   if (decl == error_mark_node)
5136     return error_mark_node;
5137
5138   if (VAR_P (decl)
5139       && DECL_NAMESPACE_SCOPE_P (decl) && !TREE_PUBLIC (decl) && !was_public
5140       && !DECL_THIS_STATIC (decl) && !DECL_ARTIFICIAL (decl))
5141     {
5142       /* This is a const variable with implicit 'static'.  Set
5143          DECL_THIS_STATIC so we can tell it from variables that are
5144          !TREE_PUBLIC because of the anonymous namespace.  */
5145       gcc_assert (CP_TYPE_CONST_P (TREE_TYPE (decl)) || errorcount);
5146       DECL_THIS_STATIC (decl) = 1;
5147     }
5148
5149   if (current_function_decl && VAR_P (decl)
5150       && DECL_DECLARED_CONSTEXPR_P (current_function_decl))
5151     {
5152       bool ok = false;
5153       if (CP_DECL_THREAD_LOCAL_P (decl))
5154         error ("%qD declared %<thread_local%> in %<constexpr%> function",
5155                decl);
5156       else if (TREE_STATIC (decl))
5157         error ("%qD declared %<static%> in %<constexpr%> function", decl);
5158       else
5159         ok = true;
5160       if (!ok)
5161         cp_function_chain->invalid_constexpr = true;
5162     }
5163
5164   if (!processing_template_decl && VAR_P (decl))
5165     start_decl_1 (decl, initialized);
5166
5167   return decl;
5168 }
5169
5170 /* Process the declaration of a variable DECL.  INITIALIZED is true
5171    iff DECL is explicitly initialized.  (INITIALIZED is false if the
5172    variable is initialized via an implicitly-called constructor.)
5173    This function must be called for ordinary variables (including, for
5174    example, implicit instantiations of templates), but must not be
5175    called for template declarations.  */
5176
5177 void
5178 start_decl_1 (tree decl, bool initialized)
5179 {
5180   tree type;
5181   bool complete_p;
5182   bool aggregate_definition_p;
5183
5184   gcc_assert (!processing_template_decl);
5185
5186   if (error_operand_p (decl))
5187     return;
5188
5189   gcc_assert (VAR_P (decl));
5190
5191   type = TREE_TYPE (decl);
5192   complete_p = COMPLETE_TYPE_P (type);
5193   aggregate_definition_p = MAYBE_CLASS_TYPE_P (type) && !DECL_EXTERNAL (decl);
5194
5195   /* If an explicit initializer is present, or if this is a definition
5196      of an aggregate, then we need a complete type at this point.
5197      (Scalars are always complete types, so there is nothing to
5198      check.)  This code just sets COMPLETE_P; errors (if necessary)
5199      are issued below.  */
5200   if ((initialized || aggregate_definition_p) 
5201       && !complete_p
5202       && COMPLETE_TYPE_P (complete_type (type)))
5203     {
5204       complete_p = true;
5205       /* We will not yet have set TREE_READONLY on DECL if the type
5206          was "const", but incomplete, before this point.  But, now, we
5207          have a complete type, so we can try again.  */
5208       cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
5209     }
5210
5211   if (initialized)
5212     /* Is it valid for this decl to have an initializer at all?  */
5213     {
5214       /* Don't allow initializations for incomplete types except for
5215          arrays which might be completed by the initialization.  */
5216       if (complete_p)
5217         ;                       /* A complete type is ok.  */
5218       else if (type_uses_auto (type))
5219         ;                       /* An auto type is ok.  */
5220       else if (TREE_CODE (type) != ARRAY_TYPE)
5221         {
5222           error ("variable %q#D has initializer but incomplete type", decl);
5223           type = TREE_TYPE (decl) = error_mark_node;
5224         }
5225       else if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (type))))
5226         {
5227           if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
5228             error ("elements of array %q#D have incomplete type", decl);
5229           /* else we already gave an error in start_decl.  */
5230         }
5231     }
5232   else if (aggregate_definition_p && !complete_p)
5233     {
5234       if (type_uses_auto (type))
5235         gcc_assert (CLASS_PLACEHOLDER_TEMPLATE (type));
5236       else
5237         {
5238           error ("aggregate %q#D has incomplete type and cannot be defined",
5239                  decl);
5240           /* Change the type so that assemble_variable will give
5241              DECL an rtl we can live with: (mem (const_int 0)).  */
5242           type = TREE_TYPE (decl) = error_mark_node;
5243         }
5244     }
5245
5246   /* Create a new scope to hold this declaration if necessary.
5247      Whether or not a new scope is necessary cannot be determined
5248      until after the type has been completed; if the type is a
5249      specialization of a class template it is not until after
5250      instantiation has occurred that TYPE_HAS_NONTRIVIAL_DESTRUCTOR
5251      will be set correctly.  */
5252   maybe_push_cleanup_level (type);
5253 }
5254
5255 /* Handle initialization of references.  DECL, TYPE, and INIT have the
5256    same meaning as in cp_finish_decl.  *CLEANUP must be NULL on entry,
5257    but will be set to a new CLEANUP_STMT if a temporary is created
5258    that must be destroyed subsequently.
5259
5260    Returns an initializer expression to use to initialize DECL, or
5261    NULL if the initialization can be performed statically.
5262
5263    Quotes on semantics can be found in ARM 8.4.3.  */
5264
5265 static tree
5266 grok_reference_init (tree decl, tree type, tree init, int flags)
5267 {
5268   if (init == NULL_TREE)
5269     {
5270       if ((DECL_LANG_SPECIFIC (decl) == 0
5271            || DECL_IN_AGGR_P (decl) == 0)
5272           && ! DECL_THIS_EXTERN (decl))
5273         error ("%qD declared as reference but not initialized", decl);
5274       return NULL_TREE;
5275     }
5276
5277   if (TREE_CODE (init) == TREE_LIST)
5278     init = build_x_compound_expr_from_list (init, ELK_INIT,
5279                                             tf_warning_or_error);
5280
5281   tree ttype = TREE_TYPE (type);
5282   if (TREE_CODE (ttype) != ARRAY_TYPE
5283       && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
5284     /* Note: default conversion is only called in very special cases.  */
5285     init = decay_conversion (init, tf_warning_or_error);
5286
5287   /* check_initializer handles this for non-reference variables, but for
5288      references we need to do it here or the initializer will get the
5289      incomplete array type and confuse later calls to
5290      cp_complete_array_type.  */
5291   if (TREE_CODE (ttype) == ARRAY_TYPE
5292       && TYPE_DOMAIN (ttype) == NULL_TREE
5293       && (BRACE_ENCLOSED_INITIALIZER_P (init)
5294           || TREE_CODE (init) == STRING_CST))
5295     {
5296       cp_complete_array_type (&ttype, init, false);
5297       if (ttype != TREE_TYPE (type))
5298         type = cp_build_reference_type (ttype, TYPE_REF_IS_RVALUE (type));
5299     }
5300
5301   /* Convert INIT to the reference type TYPE.  This may involve the
5302      creation of a temporary, whose lifetime must be the same as that
5303      of the reference.  If so, a DECL_EXPR for the temporary will be
5304      added just after the DECL_EXPR for DECL.  That's why we don't set
5305      DECL_INITIAL for local references (instead assigning to them
5306      explicitly); we need to allow the temporary to be initialized
5307      first.  */
5308   return initialize_reference (type, init, flags,
5309                                tf_warning_or_error);
5310 }
5311
5312 /* Designated initializers in arrays are not supported in GNU C++.
5313    The parser cannot detect this error since it does not know whether
5314    a given brace-enclosed initializer is for a class type or for an
5315    array.  This function checks that CE does not use a designated
5316    initializer.  If it does, an error is issued.  Returns true if CE
5317    is valid, i.e., does not have a designated initializer.  */
5318
5319 bool
5320 check_array_designated_initializer (constructor_elt *ce,
5321                                     unsigned HOST_WIDE_INT index)
5322 {
5323   /* Designated initializers for array elements are not supported.  */
5324   if (ce->index)
5325     {
5326       /* The parser only allows identifiers as designated
5327          initializers.  */
5328       if (ce->index == error_mark_node)
5329         {
5330           error ("name used in a GNU-style designated "
5331                  "initializer for an array");
5332           return false;
5333         }
5334       else if (identifier_p (ce->index))
5335         {
5336           error ("name %qD used in a GNU-style designated "
5337                  "initializer for an array", ce->index);
5338           return false;
5339         }
5340
5341       tree ce_index = build_expr_type_conversion (WANT_INT | WANT_ENUM,
5342                                                   ce->index, true);
5343       if (ce_index
5344           && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ce_index))
5345           && (TREE_CODE (ce_index = maybe_constant_value (ce_index))
5346               == INTEGER_CST))
5347         {
5348           /* A C99 designator is OK if it matches the current index.  */
5349           if (wi::to_wide (ce_index) == index)
5350             return true;
5351           else
5352             sorry ("non-trivial designated initializers not supported");
5353         }
5354       else
5355         error ("C99 designator %qE is not an integral constant-expression",
5356                ce->index);
5357
5358       return false;
5359     }
5360
5361   return true;
5362 }
5363
5364 /* When parsing `int a[] = {1, 2};' we don't know the size of the
5365    array until we finish parsing the initializer.  If that's the
5366    situation we're in, update DECL accordingly.  */
5367
5368 static void
5369 maybe_deduce_size_from_array_init (tree decl, tree init)
5370 {
5371   tree type = TREE_TYPE (decl);
5372
5373   if (TREE_CODE (type) == ARRAY_TYPE
5374       && TYPE_DOMAIN (type) == NULL_TREE
5375       && TREE_CODE (decl) != TYPE_DECL)
5376     {
5377       /* do_default is really a C-ism to deal with tentative definitions.
5378          But let's leave it here to ease the eventual merge.  */
5379       int do_default = !DECL_EXTERNAL (decl);
5380       tree initializer = init ? init : DECL_INITIAL (decl);
5381       int failure = 0;
5382
5383       /* Check that there are no designated initializers in INIT, as
5384          those are not supported in GNU C++, and as the middle-end
5385          will crash if presented with a non-numeric designated
5386          initializer.  */
5387       if (initializer && BRACE_ENCLOSED_INITIALIZER_P (initializer))
5388         {
5389           vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initializer);
5390           constructor_elt *ce;
5391           HOST_WIDE_INT i;
5392           FOR_EACH_VEC_SAFE_ELT (v, i, ce)
5393             if (!check_array_designated_initializer (ce, i))
5394               failure = 1;
5395         }
5396
5397       if (!failure)
5398         {
5399           failure = cp_complete_array_type (&TREE_TYPE (decl), initializer,
5400                                             do_default);
5401           if (failure == 1)
5402             {
5403               error_at (EXPR_LOC_OR_LOC (initializer,
5404                                          DECL_SOURCE_LOCATION (decl)),
5405                         "initializer fails to determine size of %qD", decl);
5406             }
5407           else if (failure == 2)
5408             {
5409               if (do_default)
5410                 {
5411                   error_at (DECL_SOURCE_LOCATION (decl),
5412                             "array size missing in %qD", decl);
5413                 }
5414               /* If a `static' var's size isn't known, make it extern as
5415                  well as static, so it does not get allocated.  If it's not
5416                  `static', then don't mark it extern; finish_incomplete_decl
5417                  will give it a default size and it will get allocated.  */
5418               else if (!pedantic && TREE_STATIC (decl) && !TREE_PUBLIC (decl))
5419                 DECL_EXTERNAL (decl) = 1;
5420             }
5421           else if (failure == 3)
5422             {
5423               error_at (DECL_SOURCE_LOCATION (decl),
5424                         "zero-size array %qD", decl);
5425             }
5426         }
5427
5428       cp_apply_type_quals_to_decl (cp_type_quals (TREE_TYPE (decl)), decl);
5429
5430       relayout_decl (decl);
5431     }
5432 }
5433
5434 /* Set DECL_SIZE, DECL_ALIGN, etc. for DECL (a VAR_DECL), and issue
5435    any appropriate error messages regarding the layout.  */
5436
5437 static void
5438 layout_var_decl (tree decl)
5439 {
5440   tree type;
5441
5442   type = TREE_TYPE (decl);
5443   if (type == error_mark_node)
5444     return;
5445
5446   /* If we haven't already laid out this declaration, do so now.
5447      Note that we must not call complete type for an external object
5448      because it's type might involve templates that we are not
5449      supposed to instantiate yet.  (And it's perfectly valid to say
5450      `extern X x' for some incomplete type `X'.)  */
5451   if (!DECL_EXTERNAL (decl))
5452     complete_type (type);
5453   if (!DECL_SIZE (decl)
5454       && TREE_TYPE (decl) != error_mark_node
5455       && complete_or_array_type_p (type))
5456     layout_decl (decl, 0);
5457
5458   if (!DECL_EXTERNAL (decl) && DECL_SIZE (decl) == NULL_TREE)
5459     {
5460       /* An automatic variable with an incomplete type: that is an error.
5461          Don't talk about array types here, since we took care of that
5462          message in grokdeclarator.  */
5463       error_at (DECL_SOURCE_LOCATION (decl),
5464                 "storage size of %qD isn%'t known", decl);
5465       TREE_TYPE (decl) = error_mark_node;
5466     }
5467 #if 0
5468   /* Keep this code around in case we later want to control debug info
5469      based on whether a type is "used".  (jason 1999-11-11) */
5470
5471   else if (!DECL_EXTERNAL (decl) && MAYBE_CLASS_TYPE_P (ttype))
5472     /* Let debugger know it should output info for this type.  */
5473     note_debug_info_needed (ttype);
5474
5475   if (TREE_STATIC (decl) && DECL_CLASS_SCOPE_P (decl))
5476     note_debug_info_needed (DECL_CONTEXT (decl));
5477 #endif
5478
5479   if ((DECL_EXTERNAL (decl) || TREE_STATIC (decl))
5480       && DECL_SIZE (decl) != NULL_TREE
5481       && ! TREE_CONSTANT (DECL_SIZE (decl)))
5482     {
5483       if (TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST)
5484         constant_expression_warning (DECL_SIZE (decl));
5485       else
5486         {
5487           error_at (DECL_SOURCE_LOCATION (decl),
5488                     "storage size of %qD isn%'t constant", decl);
5489           TREE_TYPE (decl) = error_mark_node;
5490         }
5491     }
5492 }
5493
5494 /* If a local static variable is declared in an inline function, or if
5495    we have a weak definition, we must endeavor to create only one
5496    instance of the variable at link-time.  */
5497
5498 void
5499 maybe_commonize_var (tree decl)
5500 {
5501   /* Static data in a function with comdat linkage also has comdat
5502      linkage.  */
5503   if ((TREE_STATIC (decl)
5504        /* Don't mess with __FUNCTION__.  */
5505        && ! DECL_ARTIFICIAL (decl)
5506        && DECL_FUNCTION_SCOPE_P (decl)
5507        && vague_linkage_p (DECL_CONTEXT (decl)))
5508       || (TREE_PUBLIC (decl) && DECL_INLINE_VAR_P (decl)))
5509     {
5510       if (flag_weak)
5511         {
5512           /* With weak symbols, we simply make the variable COMDAT;
5513              that will cause copies in multiple translations units to
5514              be merged.  */
5515           comdat_linkage (decl);
5516         }
5517       else
5518         {
5519           if (DECL_INITIAL (decl) == NULL_TREE
5520               || DECL_INITIAL (decl) == error_mark_node)
5521             {
5522               /* Without weak symbols, we can use COMMON to merge
5523                  uninitialized variables.  */
5524               TREE_PUBLIC (decl) = 1;
5525               DECL_COMMON (decl) = 1;
5526             }
5527           else
5528             {
5529               /* While for initialized variables, we must use internal
5530                  linkage -- which means that multiple copies will not
5531                  be merged.  */
5532               TREE_PUBLIC (decl) = 0;
5533               DECL_COMMON (decl) = 0;
5534               const char *msg;
5535               if (DECL_INLINE_VAR_P (decl))
5536                 msg = G_("sorry: semantics of inline variable "
5537                          "%q#D are wrong (you%'ll wind up with "
5538                          "multiple copies)");
5539               else
5540                 msg = G_("sorry: semantics of inline function "
5541                          "static data %q#D are wrong (you%'ll wind "
5542                          "up with multiple copies)");
5543               if (warning_at (DECL_SOURCE_LOCATION (decl), 0,
5544                               msg, decl))
5545                 inform (DECL_SOURCE_LOCATION (decl),
5546                         "you can work around this by removing the initializer");
5547             }
5548         }
5549     }
5550 }
5551
5552 /* Issue an error message if DECL is an uninitialized const variable.
5553    CONSTEXPR_CONTEXT_P is true when the function is called in a constexpr
5554    context from potential_constant_expression.  Returns true if all is well,
5555    false otherwise.  */
5556
5557 bool
5558 check_for_uninitialized_const_var (tree decl, bool constexpr_context_p,
5559                                    tsubst_flags_t complain)
5560 {
5561   tree type = strip_array_types (TREE_TYPE (decl));
5562
5563   /* ``Unless explicitly declared extern, a const object does not have
5564      external linkage and must be initialized. ($8.4; $12.1)'' ARM
5565      7.1.6 */
5566   if (VAR_P (decl)
5567       && TREE_CODE (type) != REFERENCE_TYPE
5568       && (constexpr_context_p
5569           || CP_TYPE_CONST_P (type) || var_in_constexpr_fn (decl))
5570       && !DECL_NONTRIVIALLY_INITIALIZED_P (decl))
5571     {
5572       tree field = default_init_uninitialized_part (type);
5573       if (!field)
5574         return true;
5575
5576       if (!constexpr_context_p)
5577         {
5578           if (CP_TYPE_CONST_P (type))
5579             {
5580               if (complain & tf_error)
5581                 permerror (DECL_SOURCE_LOCATION (decl),
5582                            "uninitialized const %qD", decl);
5583             }
5584           else
5585             {
5586               if (!is_instantiation_of_constexpr (current_function_decl)
5587                   && (complain & tf_error))
5588                 error_at (DECL_SOURCE_LOCATION (decl),
5589                           "uninitialized variable %qD in %<constexpr%> "
5590                           "function", decl);
5591               cp_function_chain->invalid_constexpr = true;
5592             }
5593         }
5594       else if (complain & tf_error)
5595         error_at (DECL_SOURCE_LOCATION (decl),
5596                   "uninitialized variable %qD in %<constexpr%> context",
5597                   decl);
5598
5599       if (CLASS_TYPE_P (type) && (complain & tf_error))
5600         {
5601           tree defaulted_ctor;
5602
5603           inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)),
5604                   "%q#T has no user-provided default constructor", type);
5605           defaulted_ctor = in_class_defaulted_default_constructor (type);
5606           if (defaulted_ctor)
5607             inform (DECL_SOURCE_LOCATION (defaulted_ctor),
5608                     "constructor is not user-provided because it is "
5609                     "explicitly defaulted in the class body");
5610           inform (DECL_SOURCE_LOCATION (field),
5611                   "and the implicitly-defined constructor does not "
5612                   "initialize %q#D", field);
5613         }
5614
5615       return false;
5616     }
5617
5618   return true;
5619 }
5620 \f
5621 /* Structure holding the current initializer being processed by reshape_init.
5622    CUR is a pointer to the current element being processed, END is a pointer
5623    after the last element present in the initializer.  */
5624 struct reshape_iter
5625 {
5626   constructor_elt *cur;
5627   constructor_elt *end;
5628 };
5629
5630 static tree reshape_init_r (tree, reshape_iter *, bool, tsubst_flags_t);
5631
5632 /* FIELD is a FIELD_DECL or NULL.  In the former case, the value
5633    returned is the next FIELD_DECL (possibly FIELD itself) that can be
5634    initialized.  If there are no more such fields, the return value
5635    will be NULL.  */
5636
5637 tree
5638 next_initializable_field (tree field)
5639 {
5640   while (field
5641          && (TREE_CODE (field) != FIELD_DECL
5642              || DECL_UNNAMED_BIT_FIELD (field)
5643              || (DECL_ARTIFICIAL (field)
5644                  && !(cxx_dialect >= cxx17 && DECL_FIELD_IS_BASE (field)))))
5645     field = DECL_CHAIN (field);
5646
5647   return field;
5648 }
5649
5650 /* Return true for [dcl.init.list] direct-list-initialization from
5651    single element of enumeration with a fixed underlying type.  */
5652
5653 bool
5654 is_direct_enum_init (tree type, tree init)
5655 {
5656   if (cxx_dialect >= cxx17
5657       && TREE_CODE (type) == ENUMERAL_TYPE
5658       && ENUM_FIXED_UNDERLYING_TYPE_P (type)
5659       && TREE_CODE (init) == CONSTRUCTOR
5660       && CONSTRUCTOR_IS_DIRECT_INIT (init)
5661       && CONSTRUCTOR_NELTS (init) == 1)
5662     return true;
5663   return false;
5664 }
5665
5666 /* Subroutine of reshape_init_array and reshape_init_vector, which does
5667    the actual work. ELT_TYPE is the element type of the array. MAX_INDEX is an
5668    INTEGER_CST representing the size of the array minus one (the maximum index),
5669    or NULL_TREE if the array was declared without specifying the size. D is
5670    the iterator within the constructor.  */
5671
5672 static tree
5673 reshape_init_array_1 (tree elt_type, tree max_index, reshape_iter *d,
5674                       tsubst_flags_t complain)
5675 {
5676   tree new_init;
5677   bool sized_array_p = (max_index && TREE_CONSTANT (max_index));
5678   unsigned HOST_WIDE_INT max_index_cst = 0;
5679   unsigned HOST_WIDE_INT index;
5680
5681   /* The initializer for an array is always a CONSTRUCTOR.  */
5682   new_init = build_constructor (init_list_type_node, NULL);
5683
5684   if (sized_array_p)
5685     {
5686       /* Minus 1 is used for zero sized arrays.  */
5687       if (integer_all_onesp (max_index))
5688         return new_init;
5689
5690       if (tree_fits_uhwi_p (max_index))
5691         max_index_cst = tree_to_uhwi (max_index);
5692       /* sizetype is sign extended, not zero extended.  */
5693       else
5694         max_index_cst = tree_to_uhwi (fold_convert (size_type_node, max_index));
5695     }
5696
5697   /* Loop until there are no more initializers.  */
5698   for (index = 0;
5699        d->cur != d->end && (!sized_array_p || index <= max_index_cst);
5700        ++index)
5701     {
5702       tree elt_init;
5703       constructor_elt *old_cur = d->cur;
5704
5705       check_array_designated_initializer (d->cur, index);
5706       elt_init = reshape_init_r (elt_type, d, /*first_initializer_p=*/false,
5707                                  complain);
5708       if (elt_init == error_mark_node)
5709         return error_mark_node;
5710       CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
5711                               size_int (index), elt_init);
5712       if (!TREE_CONSTANT (elt_init))
5713         TREE_CONSTANT (new_init) = false;
5714
5715       /* This can happen with an invalid initializer (c++/54501).  */
5716       if (d->cur == old_cur && !sized_array_p)
5717         break;
5718     }
5719
5720   return new_init;
5721 }
5722
5723 /* Subroutine of reshape_init_r, processes the initializers for arrays.
5724    Parameters are the same of reshape_init_r.  */
5725
5726 static tree
5727 reshape_init_array (tree type, reshape_iter *d, tsubst_flags_t complain)
5728 {
5729   tree max_index = NULL_TREE;
5730
5731   gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
5732
5733   if (TYPE_DOMAIN (type))
5734     max_index = array_type_nelts (type);
5735
5736   return reshape_init_array_1 (TREE_TYPE (type), max_index, d, complain);
5737 }
5738
5739 /* Subroutine of reshape_init_r, processes the initializers for vectors.
5740    Parameters are the same of reshape_init_r.  */
5741
5742 static tree
5743 reshape_init_vector (tree type, reshape_iter *d, tsubst_flags_t complain)
5744 {
5745   tree max_index = NULL_TREE;
5746
5747   gcc_assert (VECTOR_TYPE_P (type));
5748
5749   if (COMPOUND_LITERAL_P (d->cur->value))
5750     {
5751       tree value = d->cur->value;
5752       if (!same_type_p (TREE_TYPE (value), type))
5753         {
5754           if (complain & tf_error)
5755             error ("invalid type %qT as initializer for a vector of type %qT",
5756                    TREE_TYPE (d->cur->value), type);
5757           value = error_mark_node;
5758         }
5759       ++d->cur;
5760       return value;
5761     }
5762
5763   /* For a vector, we initialize it as an array of the appropriate size.  */
5764   if (VECTOR_TYPE_P (type))
5765     max_index = size_int (TYPE_VECTOR_SUBPARTS (type) - 1);
5766
5767   return reshape_init_array_1 (TREE_TYPE (type), max_index, d, complain);
5768 }
5769
5770 /* Subroutine of reshape_init_r, processes the initializers for classes
5771    or union. Parameters are the same of reshape_init_r.  */
5772
5773 static tree
5774 reshape_init_class (tree type, reshape_iter *d, bool first_initializer_p,
5775                     tsubst_flags_t complain)
5776 {
5777   tree field;
5778   tree new_init;
5779
5780   gcc_assert (CLASS_TYPE_P (type));
5781
5782   /* The initializer for a class is always a CONSTRUCTOR.  */
5783   new_init = build_constructor (init_list_type_node, NULL);
5784   field = next_initializable_field (TYPE_FIELDS (type));
5785
5786   if (!field)
5787     {
5788       /* [dcl.init.aggr]
5789
5790         An initializer for an aggregate member that is an
5791         empty class shall have the form of an empty
5792         initializer-list {}.  */
5793       if (!first_initializer_p)
5794         {
5795           if (complain & tf_error)
5796             error ("initializer for %qT must be brace-enclosed", type);
5797           return error_mark_node;
5798         }
5799       return new_init;
5800     }
5801
5802   /* Loop through the initializable fields, gathering initializers.  */
5803   while (d->cur != d->end)
5804     {
5805       tree field_init;
5806       constructor_elt *old_cur = d->cur;
5807
5808       /* Handle designated initializers, as an extension.  */
5809       if (d->cur->index)
5810         {
5811           if (d->cur->index == error_mark_node)
5812             return error_mark_node;
5813
5814           if (TREE_CODE (d->cur->index) == FIELD_DECL)
5815             /* We already reshaped this.  */
5816             gcc_assert (d->cur->index == field);
5817           else if (TREE_CODE (d->cur->index) == IDENTIFIER_NODE)
5818             field = get_class_binding (type, d->cur->index, false);
5819           else
5820             {
5821               if (complain & tf_error)
5822                 error ("%<[%E] =%> used in a GNU-style designated initializer"
5823                        " for class %qT", d->cur->index, type);
5824               return error_mark_node;
5825             }
5826
5827           if (!field || TREE_CODE (field) != FIELD_DECL)
5828             {
5829               if (complain & tf_error)
5830                 error ("%qT has no non-static data member named %qD", type,
5831                        d->cur->index);
5832               return error_mark_node;
5833             }
5834         }
5835
5836       /* If we processed all the member of the class, we are done.  */
5837       if (!field)
5838         break;
5839
5840       field_init = reshape_init_r (TREE_TYPE (field), d,
5841                                    /*first_initializer_p=*/false, complain);
5842       if (field_init == error_mark_node)
5843         return error_mark_node;
5844
5845       if (d->cur == old_cur && d->cur->index)
5846         {
5847           /* This can happen with an invalid initializer for a flexible
5848              array member (c++/54441).  */
5849           if (complain & tf_error)
5850             error ("invalid initializer for %q#D", field);
5851           return error_mark_node;
5852         }
5853
5854       CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init), field, field_init);
5855
5856       /* [dcl.init.aggr]
5857
5858         When a union  is  initialized with a brace-enclosed
5859         initializer, the braces shall only contain an
5860         initializer for the first member of the union.  */
5861       if (TREE_CODE (type) == UNION_TYPE)
5862         break;
5863
5864       field = next_initializable_field (DECL_CHAIN (field));
5865     }
5866
5867   return new_init;
5868 }
5869
5870 /* Subroutine of reshape_init_r.  We're in a context where C99 initializer
5871    designators are not valid; either complain or return true to indicate
5872    that reshape_init_r should return error_mark_node.  */
5873
5874 static bool
5875 has_designator_problem (reshape_iter *d, tsubst_flags_t complain)
5876 {
5877   if (d->cur->index)
5878     {
5879       if (complain & tf_error)
5880         error ("C99 designator %qE outside aggregate initializer",
5881                d->cur->index);
5882       else
5883         return true;
5884     }
5885   return false;
5886 }
5887
5888 /* Subroutine of reshape_init, which processes a single initializer (part of
5889    a CONSTRUCTOR). TYPE is the type of the variable being initialized, D is the
5890    iterator within the CONSTRUCTOR which points to the initializer to process.
5891    FIRST_INITIALIZER_P is true if this is the first initializer of the
5892    outermost CONSTRUCTOR node.  */
5893
5894 static tree
5895 reshape_init_r (tree type, reshape_iter *d, bool first_initializer_p,
5896                 tsubst_flags_t complain)
5897 {
5898   tree init = d->cur->value;
5899
5900   if (error_operand_p (init))
5901     return error_mark_node;
5902
5903   if (first_initializer_p && !CP_AGGREGATE_TYPE_P (type)
5904       && has_designator_problem (d, complain))
5905     return error_mark_node;
5906
5907   if (TREE_CODE (type) == COMPLEX_TYPE)
5908     {
5909       /* A complex type can be initialized from one or two initializers,
5910          but braces are not elided.  */
5911       d->cur++;
5912       if (BRACE_ENCLOSED_INITIALIZER_P (init))
5913         {
5914           if (CONSTRUCTOR_NELTS (init) > 2)
5915             {
5916               if (complain & tf_error)
5917                 error ("too many initializers for %qT", type);
5918               else
5919                 return error_mark_node;
5920             }
5921         }
5922       else if (first_initializer_p && d->cur != d->end)
5923         {
5924           vec<constructor_elt, va_gc> *v = 0;
5925           CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
5926           CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, d->cur->value);
5927           if (has_designator_problem (d, complain))
5928             return error_mark_node;
5929           d->cur++;
5930           init = build_constructor (init_list_type_node, v);
5931         }
5932       return init;
5933     }
5934
5935   /* A non-aggregate type is always initialized with a single
5936      initializer.  */
5937   if (!CP_AGGREGATE_TYPE_P (type))
5938     {
5939       /* It is invalid to initialize a non-aggregate type with a
5940          brace-enclosed initializer before C++0x.
5941          We need to check for BRACE_ENCLOSED_INITIALIZER_P here because
5942          of g++.old-deja/g++.mike/p7626.C: a pointer-to-member constant is
5943          a CONSTRUCTOR (with a record type).  */
5944       if (TREE_CODE (init) == CONSTRUCTOR
5945           /* Don't complain about a capture-init.  */
5946           && !CONSTRUCTOR_IS_DIRECT_INIT (init)
5947           && BRACE_ENCLOSED_INITIALIZER_P (init))  /* p7626.C */
5948         {
5949           if (SCALAR_TYPE_P (type))
5950             {
5951               if (cxx_dialect < cxx11
5952                   /* Isn't value-initialization.  */
5953                   || CONSTRUCTOR_NELTS (init) > 0)
5954                 {
5955                   if (complain & tf_error)
5956                     error ("braces around scalar initializer for type %qT",
5957                            type);
5958                   init = error_mark_node;
5959                 }
5960             }
5961           else
5962             maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
5963         }
5964
5965       d->cur++;
5966       return init;
5967     }
5968
5969   /* "If T is a class type and the initializer list has a single element of
5970      type cv U, where U is T or a class derived from T, the object is
5971      initialized from that element."  Even if T is an aggregate.  */
5972   if (cxx_dialect >= cxx11 && (CLASS_TYPE_P (type) || VECTOR_TYPE_P (type))
5973       && first_initializer_p
5974       && d->end - d->cur == 1
5975       && reference_related_p (type, TREE_TYPE (init)))
5976     {
5977       d->cur++;
5978       return init;
5979     }
5980
5981   /* [dcl.init.aggr]
5982
5983      All implicit type conversions (clause _conv_) are considered when
5984      initializing the aggregate member with an initializer from an
5985      initializer-list.  If the initializer can initialize a member,
5986      the member is initialized.  Otherwise, if the member is itself a
5987      non-empty subaggregate, brace elision is assumed and the
5988      initializer is considered for the initialization of the first
5989      member of the subaggregate.  */
5990   if (TREE_CODE (init) != CONSTRUCTOR
5991       /* But don't try this for the first initializer, since that would be
5992          looking through the outermost braces; A a2 = { a1 }; is not a
5993          valid aggregate initialization.  */
5994       && !first_initializer_p
5995       && (same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (init))
5996           || can_convert_arg (type, TREE_TYPE (init), init, LOOKUP_NORMAL,
5997                               complain)))
5998     {
5999       d->cur++;
6000       return init;
6001     }
6002
6003   /* [dcl.init.string]
6004
6005       A char array (whether plain char, signed char, or unsigned char)
6006       can be initialized by a string-literal (optionally enclosed in
6007       braces); a wchar_t array can be initialized by a wide
6008       string-literal (optionally enclosed in braces).  */
6009   if (TREE_CODE (type) == ARRAY_TYPE
6010       && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type))))
6011     {
6012       tree str_init = init;
6013
6014       /* Strip one level of braces if and only if they enclose a single
6015          element (as allowed by [dcl.init.string]).  */
6016       if (!first_initializer_p
6017           && TREE_CODE (str_init) == CONSTRUCTOR
6018           && CONSTRUCTOR_NELTS (str_init) == 1)
6019         {
6020           str_init = (*CONSTRUCTOR_ELTS (str_init))[0].value;
6021         }
6022
6023       /* If it's a string literal, then it's the initializer for the array
6024          as a whole. Otherwise, continue with normal initialization for
6025          array types (one value per array element).  */
6026       if (TREE_CODE (str_init) == STRING_CST)
6027         {
6028           if (has_designator_problem (d, complain))
6029             return error_mark_node;
6030           d->cur++;
6031           return str_init;
6032         }
6033     }
6034
6035   /* The following cases are about aggregates. If we are not within a full
6036      initializer already, and there is not a CONSTRUCTOR, it means that there
6037      is a missing set of braces (that is, we are processing the case for
6038      which reshape_init exists).  */
6039   if (!first_initializer_p)
6040     {
6041       if (TREE_CODE (init) == CONSTRUCTOR)
6042         {
6043           if (TREE_TYPE (init) && TYPE_PTRMEMFUNC_P (TREE_TYPE (init)))
6044             /* There is no need to reshape pointer-to-member function
6045                initializers, as they are always constructed correctly
6046                by the front end.  */
6047            ;
6048           else if (COMPOUND_LITERAL_P (init))
6049           /* For a nested compound literal, there is no need to reshape since
6050              brace elision is not allowed. Even if we decided to allow it,
6051              we should add a call to reshape_init in finish_compound_literal,
6052              before calling digest_init, so changing this code would still
6053              not be necessary.  */
6054             gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (init));
6055           else
6056             {
6057               ++d->cur;
6058               gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (init));
6059               return reshape_init (type, init, complain);
6060             }
6061         }
6062
6063       if (complain & tf_warning)
6064         warning (OPT_Wmissing_braces,
6065                  "missing braces around initializer for %qT",
6066                  type);
6067     }
6068
6069   /* Dispatch to specialized routines.  */
6070   if (CLASS_TYPE_P (type))
6071     return reshape_init_class (type, d, first_initializer_p, complain);
6072   else if (TREE_CODE (type) == ARRAY_TYPE)
6073     return reshape_init_array (type, d, complain);
6074   else if (VECTOR_TYPE_P (type))
6075     return reshape_init_vector (type, d, complain);
6076   else
6077     gcc_unreachable();
6078 }
6079
6080 /* Undo the brace-elision allowed by [dcl.init.aggr] in a
6081    brace-enclosed aggregate initializer.
6082
6083    INIT is the CONSTRUCTOR containing the list of initializers describing
6084    a brace-enclosed initializer for an entity of the indicated aggregate TYPE.
6085    It may not presently match the shape of the TYPE; for example:
6086
6087      struct S { int a; int b; };
6088      struct S a[] = { 1, 2, 3, 4 };
6089
6090    Here INIT will hold a vector of four elements, rather than a
6091    vector of two elements, each itself a vector of two elements.  This
6092    routine transforms INIT from the former form into the latter.  The
6093    revised CONSTRUCTOR node is returned.  */
6094
6095 tree
6096 reshape_init (tree type, tree init, tsubst_flags_t complain)
6097 {
6098   vec<constructor_elt, va_gc> *v;
6099   reshape_iter d;
6100   tree new_init;
6101
6102   gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (init));
6103
6104   v = CONSTRUCTOR_ELTS (init);
6105
6106   /* An empty constructor does not need reshaping, and it is always a valid
6107      initializer.  */
6108   if (vec_safe_is_empty (v))
6109     return init;
6110
6111   /* Handle [dcl.init.list] direct-list-initialization from
6112      single element of enumeration with a fixed underlying type.  */
6113   if (is_direct_enum_init (type, init))
6114     {
6115       tree elt = CONSTRUCTOR_ELT (init, 0)->value;
6116       type = cv_unqualified (type);
6117       if (check_narrowing (ENUM_UNDERLYING_TYPE (type), elt, complain))
6118         {
6119           warning_sentinel w (warn_useless_cast);
6120           warning_sentinel w2 (warn_ignored_qualifiers);
6121           return cp_build_c_cast (type, elt, tf_warning_or_error);
6122         }
6123       else
6124         return error_mark_node;
6125     }
6126
6127   /* Recurse on this CONSTRUCTOR.  */
6128   d.cur = &(*v)[0];
6129   d.end = d.cur + v->length ();
6130
6131   new_init = reshape_init_r (type, &d, true, complain);
6132   if (new_init == error_mark_node)
6133     return error_mark_node;
6134
6135   /* Make sure all the element of the constructor were used. Otherwise,
6136      issue an error about exceeding initializers.  */
6137   if (d.cur != d.end)
6138     {
6139       if (complain & tf_error)
6140         error ("too many initializers for %qT", type);
6141       return error_mark_node;
6142     }
6143
6144   if (CONSTRUCTOR_IS_DIRECT_INIT (init)
6145       && BRACE_ENCLOSED_INITIALIZER_P (new_init))
6146     CONSTRUCTOR_IS_DIRECT_INIT (new_init) = true;
6147
6148   return new_init;
6149 }
6150
6151 /* Verify array initializer.  Returns true if errors have been reported.  */
6152
6153 bool
6154 check_array_initializer (tree decl, tree type, tree init)
6155 {
6156   tree element_type = TREE_TYPE (type);
6157
6158   /* The array type itself need not be complete, because the
6159      initializer may tell us how many elements are in the array.
6160      But, the elements of the array must be complete.  */
6161   if (!COMPLETE_TYPE_P (complete_type (element_type)))
6162     {
6163       if (decl)
6164         error_at (DECL_SOURCE_LOCATION (decl),
6165                   "elements of array %q#D have incomplete type", decl);
6166       else
6167         error ("elements of array %q#T have incomplete type", type);
6168       return true;
6169     }
6170   /* A compound literal can't have variable size.  */
6171   if (init && !decl
6172       && ((COMPLETE_TYPE_P (type) && !TREE_CONSTANT (TYPE_SIZE (type)))
6173           || !TREE_CONSTANT (TYPE_SIZE (element_type))))
6174     {
6175       error ("variable-sized compound literal");
6176       return true;
6177     }
6178   return false;
6179 }
6180
6181 /* Subroutine of check_initializer; args are passed down from that function.
6182    Set stmts_are_full_exprs_p to 1 across a call to build_aggr_init.  */
6183
6184 static tree
6185 build_aggr_init_full_exprs (tree decl, tree init, int flags)
6186      
6187 {
6188   gcc_assert (stmts_are_full_exprs_p ());
6189   return build_aggr_init (decl, init, flags, tf_warning_or_error);
6190 }
6191
6192 /* Verify INIT (the initializer for DECL), and record the
6193    initialization in DECL_INITIAL, if appropriate.  CLEANUP is as for
6194    grok_reference_init.
6195
6196    If the return value is non-NULL, it is an expression that must be
6197    evaluated dynamically to initialize DECL.  */
6198
6199 static tree
6200 check_initializer (tree decl, tree init, int flags, vec<tree, va_gc> **cleanups)
6201 {
6202   tree type = TREE_TYPE (decl);
6203   tree init_code = NULL;
6204   tree core_type;
6205
6206   /* Things that are going to be initialized need to have complete
6207      type.  */
6208   TREE_TYPE (decl) = type = complete_type (TREE_TYPE (decl));
6209
6210   if (DECL_HAS_VALUE_EXPR_P (decl))
6211     {
6212       /* A variable with DECL_HAS_VALUE_EXPR_P set is just a placeholder,
6213          it doesn't have storage to be initialized.  */
6214       gcc_assert (init == NULL_TREE);
6215       return NULL_TREE;
6216     }
6217
6218   if (type == error_mark_node)
6219     /* We will have already complained.  */
6220     return NULL_TREE;
6221
6222   if (TREE_CODE (type) == ARRAY_TYPE)
6223     {
6224       if (check_array_initializer (decl, type, init))
6225         return NULL_TREE;
6226     }
6227   else if (!COMPLETE_TYPE_P (type))
6228     {
6229       error_at (DECL_SOURCE_LOCATION (decl),
6230                 "%q#D has incomplete type", decl);
6231       TREE_TYPE (decl) = error_mark_node;
6232       return NULL_TREE;
6233     }
6234   else
6235     /* There is no way to make a variable-sized class type in GNU C++.  */
6236     gcc_assert (TREE_CONSTANT (TYPE_SIZE (type)));
6237
6238   if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
6239     {
6240       int init_len = CONSTRUCTOR_NELTS (init);
6241       if (SCALAR_TYPE_P (type))
6242         {
6243           if (init_len == 0)
6244             {
6245               maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
6246               init = build_zero_init (type, NULL_TREE, false);
6247             }
6248           else if (init_len != 1 && TREE_CODE (type) != COMPLEX_TYPE)
6249             {
6250               error_at (EXPR_LOC_OR_LOC (init, DECL_SOURCE_LOCATION (decl)),
6251                         "scalar object %qD requires one element in "
6252                         "initializer", decl);
6253               TREE_TYPE (decl) = error_mark_node;
6254               return NULL_TREE;
6255             }
6256         }
6257     }
6258
6259   if (TREE_CODE (decl) == CONST_DECL)
6260     {
6261       gcc_assert (TREE_CODE (type) != REFERENCE_TYPE);
6262
6263       DECL_INITIAL (decl) = init;
6264
6265       gcc_assert (init != NULL_TREE);
6266       init = NULL_TREE;
6267     }
6268   else if (!init && DECL_REALLY_EXTERN (decl))
6269     ;
6270   else if (init || type_build_ctor_call (type)
6271            || TREE_CODE (type) == REFERENCE_TYPE)
6272     {
6273       if (TREE_CODE (type) == REFERENCE_TYPE)
6274         {
6275           init = grok_reference_init (decl, type, init, flags);
6276           flags |= LOOKUP_ALREADY_DIGESTED;
6277         }
6278       else if (!init)
6279         check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
6280                                            tf_warning_or_error);
6281       /* Do not reshape constructors of vectors (they don't need to be
6282          reshaped.  */
6283       else if (BRACE_ENCLOSED_INITIALIZER_P (init))
6284         {
6285           if (is_std_init_list (type))
6286             {
6287               init = perform_implicit_conversion (type, init,
6288                                                   tf_warning_or_error);
6289               flags |= LOOKUP_ALREADY_DIGESTED;
6290             }
6291           else if (TYPE_NON_AGGREGATE_CLASS (type))
6292             {
6293               /* Don't reshape if the class has constructors.  */
6294               if (cxx_dialect == cxx98)
6295                 error_at (EXPR_LOC_OR_LOC (init, DECL_SOURCE_LOCATION (decl)),
6296                           "in C++98 %qD must be initialized by "
6297                           "constructor, not by %<{...}%>",
6298                           decl);
6299             }
6300           else if (VECTOR_TYPE_P (type) && TYPE_VECTOR_OPAQUE (type))
6301             {
6302               error ("opaque vector types cannot be initialized");
6303               init = error_mark_node;
6304             }
6305           else
6306             {
6307               init = reshape_init (type, init, tf_warning_or_error);
6308               flags |= LOOKUP_NO_NARROWING;
6309             }
6310         }
6311       else if (TREE_CODE (init) == TREE_LIST
6312                && TREE_TYPE (init) != unknown_type_node
6313                && !MAYBE_CLASS_TYPE_P (type))
6314         {
6315           gcc_assert (TREE_CODE (decl) != RESULT_DECL);
6316
6317           /* We get here with code like `int a (2);' */
6318           init = build_x_compound_expr_from_list (init, ELK_INIT,
6319                                                   tf_warning_or_error);
6320         }
6321
6322       /* If DECL has an array type without a specific bound, deduce the
6323          array size from the initializer.  */
6324       maybe_deduce_size_from_array_init (decl, init);
6325       type = TREE_TYPE (decl);
6326       if (type == error_mark_node)
6327         return NULL_TREE;
6328
6329       if (((type_build_ctor_call (type) || CLASS_TYPE_P (type))
6330            && !(flags & LOOKUP_ALREADY_DIGESTED)
6331            && !(init && BRACE_ENCLOSED_INITIALIZER_P (init)
6332                 && CP_AGGREGATE_TYPE_P (type)
6333                 && (CLASS_TYPE_P (type)
6334                     || !TYPE_NEEDS_CONSTRUCTING (type)
6335                     || type_has_extended_temps (type))))
6336           || (DECL_DECOMPOSITION_P (decl) && TREE_CODE (type) == ARRAY_TYPE))
6337         {
6338           init_code = build_aggr_init_full_exprs (decl, init, flags);
6339
6340           /* A constructor call is a non-trivial initializer even if
6341              it isn't explicitly written.  */
6342           if (TREE_SIDE_EFFECTS (init_code))
6343             DECL_NONTRIVIALLY_INITIALIZED_P (decl) = true;
6344
6345           /* If this is a constexpr initializer, expand_default_init will
6346              have returned an INIT_EXPR rather than a CALL_EXPR.  In that
6347              case, pull the initializer back out and pass it down into
6348              store_init_value.  */
6349           while (TREE_CODE (init_code) == EXPR_STMT
6350                  || TREE_CODE (init_code) == CONVERT_EXPR)
6351             init_code = TREE_OPERAND (init_code, 0);
6352           if (TREE_CODE (init_code) == INIT_EXPR)
6353             {
6354               init = TREE_OPERAND (init_code, 1);
6355               init_code = NULL_TREE;
6356               /* Don't call digest_init; it's unnecessary and will complain
6357                  about aggregate initialization of non-aggregate classes.  */
6358               flags |= LOOKUP_ALREADY_DIGESTED;
6359             }
6360           else if (DECL_DECLARED_CONSTEXPR_P (decl))
6361             {
6362               /* Declared constexpr, but no suitable initializer; massage
6363                  init appropriately so we can pass it into store_init_value
6364                  for the error.  */
6365               if (CLASS_TYPE_P (type)
6366                   && (!init || TREE_CODE (init) == TREE_LIST))
6367                 {
6368                   init = build_functional_cast (type, init, tf_none);
6369                   if (TREE_CODE (init) == TARGET_EXPR)
6370                     TARGET_EXPR_DIRECT_INIT_P (init) = true;
6371                 }
6372               init_code = NULL_TREE;
6373             }
6374           else
6375             init = NULL_TREE;
6376         }
6377
6378       if (init && TREE_CODE (init) != TREE_VEC)
6379         {
6380           /* In aggregate initialization of a variable, each element
6381              initialization is a full-expression because there is no
6382              enclosing expression.  */
6383           gcc_assert (stmts_are_full_exprs_p ());
6384
6385           init_code = store_init_value (decl, init, cleanups, flags);
6386
6387           if (pedantic && TREE_CODE (type) == ARRAY_TYPE
6388               && DECL_INITIAL (decl)
6389               && TREE_CODE (DECL_INITIAL (decl)) == STRING_CST
6390               && PAREN_STRING_LITERAL_P (DECL_INITIAL (decl)))
6391             warning_at (EXPR_LOC_OR_LOC (DECL_INITIAL (decl),
6392                                          DECL_SOURCE_LOCATION (decl)),
6393                         0, "array %qD initialized by parenthesized "
6394                         "string literal %qE",
6395                         decl, DECL_INITIAL (decl));
6396           init = NULL;
6397         }
6398     }
6399   else
6400     {
6401       if (CLASS_TYPE_P (core_type = strip_array_types (type))
6402           && (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type)
6403               || CLASSTYPE_REF_FIELDS_NEED_INIT (core_type)))
6404         diagnose_uninitialized_cst_or_ref_member (core_type, /*using_new=*/false,
6405                                                   /*complain=*/true);
6406
6407       check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
6408                                          tf_warning_or_error);
6409     }
6410
6411   if (init && init != error_mark_node)
6412     init_code = build2 (INIT_EXPR, type, decl, init);
6413
6414   if (init_code)
6415     {
6416       /* We might have set these in cp_finish_decl.  */
6417       DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = false;
6418       TREE_CONSTANT (decl) = false;
6419     }
6420
6421   if (init_code
6422       && (DECL_IN_AGGR_P (decl) && !DECL_VAR_DECLARED_INLINE_P (decl)))
6423     {
6424       static int explained = 0;
6425
6426       if (cxx_dialect < cxx11)
6427         error ("initializer invalid for static member with constructor");
6428       else if (cxx_dialect < cxx17)
6429         error ("non-constant in-class initialization invalid for static "
6430                "member %qD", decl);
6431       else
6432         error ("non-constant in-class initialization invalid for non-inline "
6433                "static member %qD", decl);
6434       if (!explained)
6435         {
6436           inform (input_location,
6437                   "(an out of class initialization is required)");
6438           explained = 1;
6439         }
6440       return NULL_TREE;
6441     }
6442
6443   return init_code;
6444 }
6445
6446 /* If DECL is not a local variable, give it RTL.  */
6447
6448 static void
6449 make_rtl_for_nonlocal_decl (tree decl, tree init, const char* asmspec)
6450 {
6451   int toplev = toplevel_bindings_p ();
6452   int defer_p;
6453
6454   /* Set the DECL_ASSEMBLER_NAME for the object.  */
6455   if (asmspec)
6456     {
6457       /* The `register' keyword, when used together with an
6458          asm-specification, indicates that the variable should be
6459          placed in a particular register.  */
6460       if (VAR_P (decl) && DECL_REGISTER (decl))
6461         {
6462           set_user_assembler_name (decl, asmspec);
6463           DECL_HARD_REGISTER (decl) = 1;
6464         }
6465       else
6466         {
6467           if (TREE_CODE (decl) == FUNCTION_DECL
6468               && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
6469             set_builtin_user_assembler_name (decl, asmspec);
6470           set_user_assembler_name (decl, asmspec);
6471         }
6472     }
6473
6474   /* Handle non-variables up front.  */
6475   if (!VAR_P (decl))
6476     {
6477       rest_of_decl_compilation (decl, toplev, at_eof);
6478       return;
6479     }
6480
6481   /* If we see a class member here, it should be a static data
6482      member.  */
6483   if (DECL_LANG_SPECIFIC (decl) && DECL_IN_AGGR_P (decl))
6484     {
6485       gcc_assert (TREE_STATIC (decl));
6486       /* An in-class declaration of a static data member should be
6487          external; it is only a declaration, and not a definition.  */
6488       if (init == NULL_TREE)
6489         gcc_assert (DECL_EXTERNAL (decl)
6490                     || !TREE_PUBLIC (decl)
6491                     || DECL_INLINE_VAR_P (decl));
6492     }
6493
6494   /* We don't create any RTL for local variables.  */
6495   if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
6496     return;
6497
6498   /* We defer emission of local statics until the corresponding
6499      DECL_EXPR is expanded.  But with constexpr its function might never
6500      be expanded, so go ahead and tell cgraph about the variable now.  */
6501   defer_p = ((DECL_FUNCTION_SCOPE_P (decl)
6502               && !var_in_maybe_constexpr_fn (decl))
6503              || DECL_VIRTUAL_P (decl));
6504
6505   /* Defer template instantiations.  */
6506   if (DECL_LANG_SPECIFIC (decl)
6507       && DECL_IMPLICIT_INSTANTIATION (decl))
6508     defer_p = 1;
6509
6510   /* If we're not deferring, go ahead and assemble the variable.  */
6511   if (!defer_p)
6512     rest_of_decl_compilation (decl, toplev, at_eof);
6513 }
6514
6515 /* walk_tree helper for wrap_temporary_cleanups, below.  */
6516
6517 static tree
6518 wrap_cleanups_r (tree *stmt_p, int *walk_subtrees, void *data)
6519 {
6520   /* Stop at types or full-expression boundaries.  */
6521   if (TYPE_P (*stmt_p)
6522       || TREE_CODE (*stmt_p) == CLEANUP_POINT_EXPR)
6523     {
6524       *walk_subtrees = 0;
6525       return NULL_TREE;
6526     }
6527
6528   if (TREE_CODE (*stmt_p) == TARGET_EXPR)
6529     {
6530       tree guard = (tree)data;
6531       tree tcleanup = TARGET_EXPR_CLEANUP (*stmt_p);
6532
6533       tcleanup = build2 (TRY_CATCH_EXPR, void_type_node, tcleanup, guard);
6534       /* Tell honor_protect_cleanup_actions to handle this as a separate
6535          cleanup.  */
6536       TRY_CATCH_IS_CLEANUP (tcleanup) = 1;
6537  
6538       TARGET_EXPR_CLEANUP (*stmt_p) = tcleanup;
6539     }
6540
6541   return NULL_TREE;
6542 }
6543
6544 /* We're initializing a local variable which has a cleanup GUARD.  If there
6545    are any temporaries used in the initializer INIT of this variable, we
6546    need to wrap their cleanups with TRY_CATCH_EXPR (, GUARD) so that the
6547    variable will be cleaned up properly if one of them throws.
6548
6549    Unfortunately, there's no way to express this properly in terms of
6550    nesting, as the regions for the temporaries overlap the region for the
6551    variable itself; if there are two temporaries, the variable needs to be
6552    the first thing destroyed if either of them throws.  However, we only
6553    want to run the variable's cleanup if it actually got constructed.  So
6554    we need to guard the temporary cleanups with the variable's cleanup if
6555    they are run on the normal path, but not if they are run on the
6556    exceptional path.  We implement this by telling
6557    honor_protect_cleanup_actions to strip the variable cleanup from the
6558    exceptional path.  */
6559
6560 static void
6561 wrap_temporary_cleanups (tree init, tree guard)
6562 {
6563   cp_walk_tree_without_duplicates (&init, wrap_cleanups_r, (void *)guard);
6564 }
6565
6566 /* Generate code to initialize DECL (a local variable).  */
6567
6568 static void
6569 initialize_local_var (tree decl, tree init)
6570 {
6571   tree type = TREE_TYPE (decl);
6572   tree cleanup;
6573   int already_used;
6574
6575   gcc_assert (VAR_P (decl)
6576               || TREE_CODE (decl) == RESULT_DECL);
6577   gcc_assert (!TREE_STATIC (decl));
6578
6579   if (DECL_SIZE (decl) == NULL_TREE)
6580     {
6581       /* If we used it already as memory, it must stay in memory.  */
6582       DECL_INITIAL (decl) = NULL_TREE;
6583       TREE_ADDRESSABLE (decl) = TREE_USED (decl);
6584       return;
6585     }
6586
6587   if (type == error_mark_node)
6588     return;
6589
6590   /* Compute and store the initial value.  */
6591   already_used = TREE_USED (decl) || TREE_USED (type);
6592   if (TREE_USED (type))
6593     DECL_READ_P (decl) = 1;
6594
6595   /* Generate a cleanup, if necessary.  */
6596   cleanup = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
6597
6598   /* Perform the initialization.  */
6599   if (init)
6600     {
6601       tree rinit = (TREE_CODE (init) == INIT_EXPR
6602                     ? TREE_OPERAND (init, 1) : NULL_TREE);
6603       if (rinit && !TREE_SIDE_EFFECTS (rinit))
6604         {
6605           /* Stick simple initializers in DECL_INITIAL so that
6606              -Wno-init-self works (c++/34772).  */
6607           gcc_assert (TREE_OPERAND (init, 0) == decl);
6608           DECL_INITIAL (decl) = rinit;
6609
6610           if (warn_init_self && TREE_CODE (type) == REFERENCE_TYPE)
6611             {
6612               STRIP_NOPS (rinit);
6613               if (rinit == decl)
6614                 warning_at (DECL_SOURCE_LOCATION (decl),
6615                             OPT_Winit_self,
6616                             "reference %qD is initialized with itself", decl);
6617             }
6618         }
6619       else
6620         {
6621           int saved_stmts_are_full_exprs_p;
6622
6623           /* If we're only initializing a single object, guard the
6624              destructors of any temporaries used in its initializer with
6625              its destructor.  This isn't right for arrays because each
6626              element initialization is a full-expression.  */
6627           if (cleanup && TREE_CODE (type) != ARRAY_TYPE)
6628             wrap_temporary_cleanups (init, cleanup);
6629
6630           gcc_assert (building_stmt_list_p ());
6631           saved_stmts_are_full_exprs_p = stmts_are_full_exprs_p ();
6632           current_stmt_tree ()->stmts_are_full_exprs_p = 1;
6633           finish_expr_stmt (init);
6634           current_stmt_tree ()->stmts_are_full_exprs_p =
6635             saved_stmts_are_full_exprs_p;
6636         }
6637     }
6638
6639   /* Set this to 0 so we can tell whether an aggregate which was
6640      initialized was ever used.  Don't do this if it has a
6641      destructor, so we don't complain about the 'resource
6642      allocation is initialization' idiom.  Now set
6643      attribute((unused)) on types so decls of that type will be
6644      marked used. (see TREE_USED, above.)  */
6645   if (TYPE_NEEDS_CONSTRUCTING (type)
6646       && ! already_used
6647       && TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
6648       && DECL_NAME (decl))
6649     TREE_USED (decl) = 0;
6650   else if (already_used)
6651     TREE_USED (decl) = 1;
6652
6653   if (cleanup)
6654     finish_decl_cleanup (decl, cleanup);
6655 }
6656
6657 /* DECL is a VAR_DECL for a compiler-generated variable with static
6658    storage duration (like a virtual table) whose initializer is a
6659    compile-time constant.  Initialize the variable and provide it to the
6660    back end.  */
6661
6662 void
6663 initialize_artificial_var (tree decl, vec<constructor_elt, va_gc> *v)
6664 {
6665   tree init;
6666   gcc_assert (DECL_ARTIFICIAL (decl));
6667   init = build_constructor (TREE_TYPE (decl), v);
6668   gcc_assert (TREE_CODE (init) == CONSTRUCTOR);
6669   DECL_INITIAL (decl) = init;
6670   DECL_INITIALIZED_P (decl) = 1;
6671   determine_visibility (decl);
6672   layout_var_decl (decl);
6673   maybe_commonize_var (decl);
6674   make_rtl_for_nonlocal_decl (decl, init, /*asmspec=*/NULL);
6675 }
6676
6677 /* INIT is the initializer for a variable, as represented by the
6678    parser.  Returns true iff INIT is value-dependent.  */
6679
6680 static bool
6681 value_dependent_init_p (tree init)
6682 {
6683   if (TREE_CODE (init) == TREE_LIST)
6684     /* A parenthesized initializer, e.g.: int i (3, 2); ? */
6685     return any_value_dependent_elements_p (init);
6686   else if (TREE_CODE (init) == CONSTRUCTOR)
6687   /* A brace-enclosed initializer, e.g.: int i = { 3 }; ? */
6688     {
6689       if (dependent_type_p (TREE_TYPE (init)))
6690         return true;
6691
6692       vec<constructor_elt, va_gc> *elts;
6693       size_t nelts;
6694       size_t i;
6695
6696       elts = CONSTRUCTOR_ELTS (init);
6697       nelts = vec_safe_length (elts);
6698       for (i = 0; i < nelts; ++i)
6699         if (value_dependent_init_p ((*elts)[i].value))
6700           return true;
6701     }
6702   else
6703     /* It must be a simple expression, e.g., int i = 3;  */
6704     return value_dependent_expression_p (init);
6705   
6706   return false;
6707 }
6708
6709 // Returns true if a DECL is VAR_DECL with the concept specifier.
6710 static inline bool
6711 is_concept_var (tree decl)
6712 {
6713   return (VAR_P (decl)
6714           // Not all variables have DECL_LANG_SPECIFIC.
6715           && DECL_LANG_SPECIFIC (decl)
6716           && DECL_DECLARED_CONCEPT_P (decl));
6717 }
6718
6719 /* A helper function to be called via walk_tree.  If any label exists
6720    under *TP, it is (going to be) forced.  Set has_forced_label_in_static.  */
6721
6722 static tree
6723 notice_forced_label_r (tree *tp, int *walk_subtrees, void *)
6724 {
6725   if (TYPE_P (*tp))
6726     *walk_subtrees = 0;
6727   if (TREE_CODE (*tp) == LABEL_DECL)
6728     cfun->has_forced_label_in_static = 1;
6729   return NULL_TREE;
6730 }
6731
6732 /* Finish processing of a declaration;
6733    install its line number and initial value.
6734    If the length of an array type is not known before,
6735    it must be determined now, from the initial value, or it is an error.
6736
6737    INIT is the initializer (if any) for DECL.  If INIT_CONST_EXPR_P is
6738    true, then INIT is an integral constant expression.
6739
6740    FLAGS is LOOKUP_ONLYCONVERTING if the = init syntax was used, else 0
6741    if the (init) syntax was used.  */
6742
6743 void
6744 cp_finish_decl (tree decl, tree init, bool init_const_expr_p,
6745                 tree asmspec_tree, int flags)
6746 {
6747   tree type;
6748   vec<tree, va_gc> *cleanups = NULL;
6749   const char *asmspec = NULL;
6750   int was_readonly = 0;
6751   bool var_definition_p = false;
6752   tree auto_node;
6753
6754   if (decl == error_mark_node)
6755     return;
6756   else if (! decl)
6757     {
6758       if (init)
6759         error ("assignment (not initialization) in declaration");
6760       return;
6761     }
6762
6763   gcc_assert (TREE_CODE (decl) != RESULT_DECL);
6764   /* Parameters are handled by store_parm_decls, not cp_finish_decl.  */
6765   gcc_assert (TREE_CODE (decl) != PARM_DECL);
6766
6767   type = TREE_TYPE (decl);
6768   if (type == error_mark_node)
6769     return;
6770
6771   /* Warn about register storage specifiers except when in GNU global
6772      or local register variable extension.  */
6773   if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec_tree == NULL_TREE)
6774     {
6775       if (cxx_dialect >= cxx17)
6776         pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
6777                  "ISO C++17 does not allow %<register%> storage "
6778                  "class specifier");
6779       else
6780         warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
6781                     "%<register%> storage class specifier used");
6782     }
6783
6784   /* If a name was specified, get the string.  */
6785   if (at_namespace_scope_p ())
6786     asmspec_tree = maybe_apply_renaming_pragma (decl, asmspec_tree);
6787   if (asmspec_tree && asmspec_tree != error_mark_node)
6788     asmspec = TREE_STRING_POINTER (asmspec_tree);
6789
6790   if (current_class_type
6791       && CP_DECL_CONTEXT (decl) == current_class_type
6792       && TYPE_BEING_DEFINED (current_class_type)
6793       && !CLASSTYPE_TEMPLATE_INSTANTIATION (current_class_type)
6794       && (DECL_INITIAL (decl) || init))
6795     DECL_INITIALIZED_IN_CLASS_P (decl) = 1;
6796
6797   if (TREE_CODE (decl) != FUNCTION_DECL
6798       && (auto_node = type_uses_auto (type)))
6799     {
6800       tree d_init;
6801       if (init == NULL_TREE)
6802         {
6803           if (DECL_LANG_SPECIFIC (decl)
6804               && DECL_TEMPLATE_INSTANTIATION (decl)
6805               && !DECL_TEMPLATE_INSTANTIATED (decl))
6806             {
6807               /* init is null because we're deferring instantiating the
6808                  initializer until we need it.  Well, we need it now.  */
6809               instantiate_decl (decl, /*defer_ok*/true, /*expl*/false);
6810               return;
6811             }
6812
6813           gcc_assert (CLASS_PLACEHOLDER_TEMPLATE (auto_node));
6814         }
6815       d_init = init;
6816       if (d_init)
6817         {
6818           if (TREE_CODE (d_init) == TREE_LIST
6819               && !CLASS_PLACEHOLDER_TEMPLATE (auto_node))
6820             d_init = build_x_compound_expr_from_list (d_init, ELK_INIT,
6821                                                       tf_warning_or_error);
6822           d_init = resolve_nondeduced_context (d_init, tf_warning_or_error);
6823         }
6824       enum auto_deduction_context adc = adc_variable_type;
6825       if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
6826         adc = adc_decomp_type;
6827       type = TREE_TYPE (decl) = do_auto_deduction (type, d_init, auto_node,
6828                                                    tf_warning_or_error, adc,
6829                                                    NULL_TREE, flags);
6830       if (type == error_mark_node)
6831         return;
6832       if (TREE_CODE (type) == FUNCTION_TYPE)
6833         {
6834           error ("initializer for %<decltype(auto) %D%> has function type "
6835                  "(did you forget the %<()%> ?)", decl);
6836           TREE_TYPE (decl) = error_mark_node;
6837           return;
6838         }
6839       cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
6840     }
6841
6842   if (ensure_literal_type_for_constexpr_object (decl)
6843       == error_mark_node)
6844     {
6845       DECL_DECLARED_CONSTEXPR_P (decl) = 0;
6846       return;
6847     }
6848
6849   if (VAR_P (decl)
6850       && DECL_CLASS_SCOPE_P (decl)
6851       && DECL_INITIALIZED_IN_CLASS_P (decl))
6852     check_static_variable_definition (decl, type);
6853
6854   if (init && TREE_CODE (decl) == FUNCTION_DECL)
6855     {
6856       tree clone;
6857       if (init == ridpointers[(int)RID_DELETE])
6858         {
6859           /* FIXME check this is 1st decl.  */
6860           DECL_DELETED_FN (decl) = 1;
6861           DECL_DECLARED_INLINE_P (decl) = 1;
6862           DECL_INITIAL (decl) = error_mark_node;
6863           FOR_EACH_CLONE (clone, decl)
6864             {
6865               DECL_DELETED_FN (clone) = 1;
6866               DECL_DECLARED_INLINE_P (clone) = 1;
6867               DECL_INITIAL (clone) = error_mark_node;
6868             }
6869           init = NULL_TREE;
6870         }
6871       else if (init == ridpointers[(int)RID_DEFAULT])
6872         {
6873           if (defaultable_fn_check (decl))
6874             DECL_DEFAULTED_FN (decl) = 1;
6875           else
6876             DECL_INITIAL (decl) = NULL_TREE;
6877         }
6878     }
6879
6880   if (init && VAR_P (decl))
6881     {
6882       DECL_NONTRIVIALLY_INITIALIZED_P (decl) = 1;
6883       /* If DECL is a reference, then we want to know whether init is a
6884          reference constant; init_const_expr_p as passed tells us whether
6885          it's an rvalue constant.  */
6886       if (TREE_CODE (type) == REFERENCE_TYPE)
6887         init_const_expr_p = potential_constant_expression (init);
6888       if (init_const_expr_p)
6889         {
6890           /* Set these flags now for templates.  We'll update the flags in
6891              store_init_value for instantiations.  */
6892           DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
6893           if (decl_maybe_constant_var_p (decl)
6894               /* FIXME setting TREE_CONSTANT on refs breaks the back end.  */
6895               && TREE_CODE (type) != REFERENCE_TYPE)
6896             TREE_CONSTANT (decl) = 1;
6897         }
6898     }
6899
6900   if (processing_template_decl)
6901     {
6902       bool type_dependent_p;
6903
6904       /* Add this declaration to the statement-tree.  */
6905       if (at_function_scope_p ())
6906         add_decl_expr (decl);
6907
6908       type_dependent_p = dependent_type_p (type);
6909
6910       if (check_for_bare_parameter_packs (init))
6911         {
6912           init = NULL_TREE;
6913           DECL_INITIAL (decl) = NULL_TREE;
6914         }
6915
6916       /* Generally, initializers in templates are expanded when the
6917          template is instantiated.  But, if DECL is a variable constant
6918          then it can be used in future constant expressions, so its value
6919          must be available. */
6920
6921       bool dep_init = false;
6922
6923       if (!VAR_P (decl) || type_dependent_p)
6924         /* We can't do anything if the decl has dependent type.  */;
6925       else if (!init && is_concept_var (decl))
6926         error ("variable concept has no initializer");
6927       else if (init
6928                && init_const_expr_p
6929                && TREE_CODE (type) != REFERENCE_TYPE
6930                && decl_maybe_constant_var_p (decl)
6931                && !(dep_init = value_dependent_init_p (init)))
6932         {
6933           /* This variable seems to be a non-dependent constant, so process
6934              its initializer.  If check_initializer returns non-null the
6935              initialization wasn't constant after all.  */
6936           tree init_code;
6937           cleanups = make_tree_vector ();
6938           init_code = check_initializer (decl, init, flags, &cleanups);
6939           if (init_code == NULL_TREE)
6940             init = NULL_TREE;
6941           release_tree_vector (cleanups);
6942         }
6943       else if (!DECL_PRETTY_FUNCTION_P (decl))
6944         {
6945           /* Deduce array size even if the initializer is dependent.  */
6946           maybe_deduce_size_from_array_init (decl, init);
6947           /* And complain about multiple initializers.  */
6948           if (init && TREE_CODE (init) == TREE_LIST && TREE_CHAIN (init)
6949               && !MAYBE_CLASS_TYPE_P (type))
6950             init = build_x_compound_expr_from_list (init, ELK_INIT,
6951                                                     tf_warning_or_error);
6952         }
6953
6954       if (init)
6955         DECL_INITIAL (decl) = init;
6956       if (dep_init)
6957         {
6958           retrofit_lang_decl (decl);
6959           SET_DECL_DEPENDENT_INIT_P (decl, true);
6960         }
6961       return;
6962     }
6963
6964   /* Just store non-static data member initializers for later.  */
6965   if (init && TREE_CODE (decl) == FIELD_DECL)
6966     DECL_INITIAL (decl) = init;
6967
6968   /* Take care of TYPE_DECLs up front.  */
6969   if (TREE_CODE (decl) == TYPE_DECL)
6970     {
6971       if (type != error_mark_node
6972           && MAYBE_CLASS_TYPE_P (type) && DECL_NAME (decl))
6973         {
6974           if (TREE_TYPE (DECL_NAME (decl)) && TREE_TYPE (decl) != type)
6975             warning (0, "shadowing previous type declaration of %q#D", decl);
6976           set_identifier_type_value (DECL_NAME (decl), decl);
6977         }
6978
6979       /* If we have installed this as the canonical typedef for this
6980          type, and that type has not been defined yet, delay emitting
6981          the debug information for it, as we will emit it later.  */
6982       if (TYPE_MAIN_DECL (TREE_TYPE (decl)) == decl
6983           && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
6984         TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
6985
6986       rest_of_decl_compilation (decl, DECL_FILE_SCOPE_P (decl),
6987                                 at_eof);
6988       return;
6989     }
6990
6991   /* A reference will be modified here, as it is initialized.  */
6992   if (! DECL_EXTERNAL (decl)
6993       && TREE_READONLY (decl)
6994       && TREE_CODE (type) == REFERENCE_TYPE)
6995     {
6996       was_readonly = 1;
6997       TREE_READONLY (decl) = 0;
6998     }
6999
7000   if (VAR_P (decl))
7001     {
7002       /* If this is a local variable that will need a mangled name,
7003          register it now.  We must do this before processing the
7004          initializer for the variable, since the initialization might
7005          require a guard variable, and since the mangled name of the
7006          guard variable will depend on the mangled name of this
7007          variable.  */
7008       if (DECL_FUNCTION_SCOPE_P (decl)
7009           && TREE_STATIC (decl)
7010           && !DECL_ARTIFICIAL (decl))
7011         {
7012           push_local_name (decl);
7013           /* Normally has_forced_label_in_static is set during GIMPLE
7014              lowering, but [cd]tors are never actually compiled directly.
7015              We need to set this early so we can deal with the label
7016              address extension.  */
7017           if ((DECL_CONSTRUCTOR_P (current_function_decl)
7018                || DECL_DESTRUCTOR_P (current_function_decl))
7019               && init)
7020             {
7021               walk_tree (&init, notice_forced_label_r, NULL, NULL);
7022               add_local_decl (cfun, decl);
7023             }
7024           /* And make sure it's in the symbol table for
7025              c_parse_final_cleanups to find.  */
7026           varpool_node::get_create (decl);
7027         }
7028
7029       /* Convert the initializer to the type of DECL, if we have not
7030          already initialized DECL.  */
7031       if (!DECL_INITIALIZED_P (decl)
7032           /* If !DECL_EXTERNAL then DECL is being defined.  In the
7033              case of a static data member initialized inside the
7034              class-specifier, there can be an initializer even if DECL
7035              is *not* defined.  */
7036           && (!DECL_EXTERNAL (decl) || init))
7037         {
7038           cleanups = make_tree_vector ();
7039           init = check_initializer (decl, init, flags, &cleanups);
7040
7041           /* Handle:
7042
7043              [dcl.init]
7044
7045              The memory occupied by any object of static storage
7046              duration is zero-initialized at program startup before
7047              any other initialization takes place.
7048
7049              We cannot create an appropriate initializer until after
7050              the type of DECL is finalized.  If DECL_INITIAL is set,
7051              then the DECL is statically initialized, and any
7052              necessary zero-initialization has already been performed.  */
7053           if (TREE_STATIC (decl) && !DECL_INITIAL (decl))
7054             DECL_INITIAL (decl) = build_zero_init (TREE_TYPE (decl),
7055                                                    /*nelts=*/NULL_TREE,
7056                                                    /*static_storage_p=*/true);
7057           /* Remember that the initialization for this variable has
7058              taken place.  */
7059           DECL_INITIALIZED_P (decl) = 1;
7060           /* This declaration is the definition of this variable,
7061              unless we are initializing a static data member within
7062              the class specifier.  */
7063           if (!DECL_EXTERNAL (decl))
7064             var_definition_p = true;
7065         }
7066       /* If the variable has an array type, lay out the type, even if
7067          there is no initializer.  It is valid to index through the
7068          array, and we must get TYPE_ALIGN set correctly on the array
7069          type.  */
7070       else if (TREE_CODE (type) == ARRAY_TYPE)
7071         layout_type (type);
7072
7073       if (TREE_STATIC (decl)
7074           && !at_function_scope_p ()
7075           && current_function_decl == NULL)
7076         /* So decl is a global variable or a static member of a
7077            non local class. Record the types it uses
7078            so that we can decide later to emit debug info for them.  */
7079         record_types_used_by_current_var_decl (decl);
7080     }
7081
7082   /* Add this declaration to the statement-tree.  This needs to happen
7083      after the call to check_initializer so that the DECL_EXPR for a
7084      reference temp is added before the DECL_EXPR for the reference itself.  */
7085   if (DECL_FUNCTION_SCOPE_P (decl))
7086     {
7087       /* If we're building a variable sized type, and we might be
7088          reachable other than via the top of the current binding
7089          level, then create a new BIND_EXPR so that we deallocate
7090          the object at the right time.  */
7091       if (VAR_P (decl)
7092           && DECL_SIZE (decl)
7093           && !TREE_CONSTANT (DECL_SIZE (decl))
7094           && STATEMENT_LIST_HAS_LABEL (cur_stmt_list))
7095         {
7096           tree bind;
7097           bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL);
7098           TREE_SIDE_EFFECTS (bind) = 1;
7099           add_stmt (bind);
7100           BIND_EXPR_BODY (bind) = push_stmt_list ();
7101         }
7102       add_decl_expr (decl);
7103     }
7104
7105   /* Let the middle end know about variables and functions -- but not
7106      static data members in uninstantiated class templates.  */
7107   if (VAR_OR_FUNCTION_DECL_P (decl))
7108     {
7109       if (VAR_P (decl))
7110         {
7111           layout_var_decl (decl);
7112           maybe_commonize_var (decl);
7113         }
7114
7115       /* This needs to happen after the linkage is set. */
7116       determine_visibility (decl);
7117
7118       if (var_definition_p && TREE_STATIC (decl))
7119         {
7120           /* If a TREE_READONLY variable needs initialization
7121              at runtime, it is no longer readonly and we need to
7122              avoid MEM_READONLY_P being set on RTL created for it.  */
7123           if (init)
7124             {
7125               if (TREE_READONLY (decl))
7126                 TREE_READONLY (decl) = 0;
7127               was_readonly = 0;
7128             }
7129           else if (was_readonly)
7130             TREE_READONLY (decl) = 1;
7131
7132           /* Likewise if it needs destruction.  */
7133           if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
7134             TREE_READONLY (decl) = 0;
7135         }
7136
7137       make_rtl_for_nonlocal_decl (decl, init, asmspec);
7138
7139       /* Check for abstractness of the type. Notice that there is no
7140          need to strip array types here since the check for those types
7141          is already done within create_array_type_for_decl.  */
7142       abstract_virtuals_error (decl, type);
7143
7144       if (TREE_TYPE (decl) == error_mark_node)
7145         /* No initialization required.  */
7146         ;
7147       else if (TREE_CODE (decl) == FUNCTION_DECL)
7148         {
7149           if (init)
7150             {
7151               if (init == ridpointers[(int)RID_DEFAULT])
7152                 {
7153                   /* An out-of-class default definition is defined at
7154                      the point where it is explicitly defaulted.  */
7155                   if (DECL_DELETED_FN (decl))
7156                     maybe_explain_implicit_delete (decl);
7157                   else if (DECL_INITIAL (decl) == error_mark_node)
7158                     synthesize_method (decl);
7159                 }
7160               else
7161                 error ("function %q#D is initialized like a variable", decl);
7162             }
7163           /* else no initialization required.  */
7164         }
7165       else if (DECL_EXTERNAL (decl)
7166                && ! (DECL_LANG_SPECIFIC (decl)
7167                      && DECL_NOT_REALLY_EXTERN (decl)))
7168         {
7169           if (init)
7170             DECL_INITIAL (decl) = init;
7171         }
7172       /* A variable definition.  */
7173       else if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
7174         /* Initialize the local variable.  */
7175         initialize_local_var (decl, init);
7176
7177       /* If a variable is defined, and then a subsequent
7178          definition with external linkage is encountered, we will
7179          get here twice for the same variable.  We want to avoid
7180          calling expand_static_init more than once.  For variables
7181          that are not static data members, we can call
7182          expand_static_init only when we actually process the
7183          initializer.  It is not legal to redeclare a static data
7184          member, so this issue does not arise in that case.  */
7185       else if (var_definition_p && TREE_STATIC (decl))
7186         expand_static_init (decl, init);
7187     }
7188
7189   /* If a CLEANUP_STMT was created to destroy a temporary bound to a
7190      reference, insert it in the statement-tree now.  */
7191   if (cleanups)
7192     {
7193       unsigned i; tree t;
7194       FOR_EACH_VEC_ELT (*cleanups, i, t)
7195         push_cleanup (decl, t, false);
7196       release_tree_vector (cleanups);
7197     }
7198
7199   if (was_readonly)
7200     TREE_READONLY (decl) = 1;
7201
7202   invoke_plugin_callbacks (PLUGIN_FINISH_DECL, decl);
7203 }
7204
7205 /* For class TYPE return itself or some its bases that contain
7206    any direct non-static data members.  Return error_mark_node if an
7207    error has been diagnosed.  */
7208
7209 static tree
7210 find_decomp_class_base (location_t loc, tree type, tree ret)
7211 {
7212   bool member_seen = false;
7213   for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
7214     if (TREE_CODE (field) != FIELD_DECL
7215         || DECL_ARTIFICIAL (field)
7216         || DECL_UNNAMED_BIT_FIELD (field))
7217       continue;
7218     else if (ret)
7219       return type;
7220     else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
7221       {
7222         if (TREE_CODE (TREE_TYPE (field)) == RECORD_TYPE)
7223           error_at (loc, "cannot decompose class type %qT because it has an "
7224                          "anonymous struct member", type);
7225         else
7226           error_at (loc, "cannot decompose class type %qT because it has an "
7227                          "anonymous union member", type);
7228         inform (DECL_SOURCE_LOCATION (field), "declared here");
7229         return error_mark_node;
7230       }
7231     else if (TREE_PRIVATE (field) || TREE_PROTECTED (field))
7232       {
7233         error_at (loc, "cannot decompose non-public member %qD of %qT",
7234                   field, type);
7235         inform (DECL_SOURCE_LOCATION (field),
7236                 TREE_PRIVATE (field)
7237                 ? G_("declared private here")
7238                 : G_("declared protected here"));
7239         return error_mark_node;
7240       }
7241     else
7242       member_seen = true;
7243
7244   tree base_binfo, binfo;
7245   tree orig_ret = ret;
7246   int i;
7247   if (member_seen)
7248     ret = type;
7249   for (binfo = TYPE_BINFO (type), i = 0;
7250        BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
7251     {
7252       tree t = find_decomp_class_base (loc, TREE_TYPE (base_binfo), ret);
7253       if (t == error_mark_node)
7254         return error_mark_node;
7255       if (t != NULL_TREE && t != ret)
7256         {
7257           if (ret == type)
7258             {
7259               error_at (loc, "cannot decompose class type %qT: both it and "
7260                              "its base class %qT have non-static data members",
7261                         type, t);
7262               return error_mark_node;
7263             }
7264           else if (orig_ret != NULL_TREE)
7265             return t;
7266           else if (ret != NULL_TREE)
7267             {
7268               error_at (loc, "cannot decompose class type %qT: its base "
7269                              "classes %qT and %qT have non-static data "
7270                              "members", type, ret, t);
7271               return error_mark_node;
7272             }
7273           else
7274             ret = t;
7275         }
7276     }
7277   return ret;
7278 }
7279
7280 /* Return std::tuple_size<TYPE>::value.  */
7281
7282 static tree
7283 get_tuple_size (tree type)
7284 {
7285   tree args = make_tree_vec (1);
7286   TREE_VEC_ELT (args, 0) = type;
7287   tree inst = lookup_template_class (get_identifier ("tuple_size"), args,
7288                                      /*in_decl*/NULL_TREE,
7289                                      /*context*/std_node,
7290                                      /*entering_scope*/false, tf_none);
7291   inst = complete_type (inst);
7292   if (inst == error_mark_node || !COMPLETE_TYPE_P (inst))
7293     return NULL_TREE;
7294   tree val = lookup_qualified_name (inst, get_identifier ("value"),
7295                                     /*type*/false, /*complain*/false);
7296   if (TREE_CODE (val) == VAR_DECL || TREE_CODE (val) == CONST_DECL)
7297     val = maybe_constant_value (val);
7298   if (TREE_CODE (val) == INTEGER_CST)
7299     return val;
7300   else
7301     return error_mark_node;
7302 }
7303
7304 /* Return std::tuple_element<I,TYPE>::type.  */
7305
7306 static tree
7307 get_tuple_element_type (tree type, unsigned i)
7308 {
7309   tree args = make_tree_vec (2);
7310   TREE_VEC_ELT (args, 0) = build_int_cst (integer_type_node, i);
7311   TREE_VEC_ELT (args, 1) = type;
7312   tree inst = lookup_template_class (get_identifier ("tuple_element"), args,
7313                                      /*in_decl*/NULL_TREE,
7314                                      /*context*/std_node,
7315                                      /*entering_scope*/false,
7316                                      tf_warning_or_error);
7317   return make_typename_type (inst, get_identifier ("type"),
7318                              none_type, tf_warning_or_error);
7319 }
7320
7321 /* Return e.get<i>() or get<i>(e).  */
7322
7323 static tree
7324 get_tuple_decomp_init (tree decl, unsigned i)
7325 {
7326   tree get_id = get_identifier ("get");
7327   tree targs = make_tree_vec (1);
7328   TREE_VEC_ELT (targs, 0) = build_int_cst (integer_type_node, i);
7329
7330   tree etype = TREE_TYPE (decl);
7331   tree e = convert_from_reference (decl);
7332
7333   /* [The id-expression] e is an lvalue if the type of the entity e is an
7334      lvalue reference and an xvalue otherwise.  */
7335   if (TREE_CODE (etype) != REFERENCE_TYPE
7336       || TYPE_REF_IS_RVALUE (etype))
7337     e = move (e);
7338
7339   tree fns = lookup_qualified_name (TREE_TYPE (e), get_id,
7340                                     /*type*/false, /*complain*/false);
7341   if (fns != error_mark_node)
7342     {
7343       fns = lookup_template_function (fns, targs);
7344       return build_new_method_call (e, fns, /*args*/NULL,
7345                                     /*path*/NULL_TREE, LOOKUP_NORMAL,
7346                                     /*fn_p*/NULL, tf_warning_or_error);
7347     }
7348   else
7349     {
7350       vec<tree,va_gc> *args = make_tree_vector_single (e);
7351       fns = lookup_template_function (get_id, targs);
7352       fns = perform_koenig_lookup (fns, args, tf_warning_or_error);
7353       return finish_call_expr (fns, &args, /*novirt*/false,
7354                                /*koenig*/true, tf_warning_or_error);
7355     }
7356 }
7357
7358 /* It's impossible to recover the decltype of a tuple decomposition variable
7359    based on the actual type of the variable, so store it in a hash table.  */
7360
7361 static GTY((cache)) tree_cache_map *decomp_type_table;
7362 static void
7363 store_decomp_type (tree v, tree t)
7364 {
7365   if (!decomp_type_table)
7366     decomp_type_table = tree_cache_map::create_ggc (13);
7367   decomp_type_table->put (v, t);
7368 }
7369
7370 tree
7371 lookup_decomp_type (tree v)
7372 {
7373   return *decomp_type_table->get (v);
7374 }
7375
7376 /* Mangle a decomposition declaration if needed.  Arguments like
7377    in cp_finish_decomp.  */
7378
7379 void
7380 cp_maybe_mangle_decomp (tree decl, tree first, unsigned int count)
7381 {
7382   if (!processing_template_decl
7383       && !error_operand_p (decl)
7384       && DECL_NAMESPACE_SCOPE_P (decl))
7385     {
7386       auto_vec<tree, 16> v;
7387       v.safe_grow (count);
7388       tree d = first;
7389       for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
7390         v[count - i - 1] = d;
7391       SET_DECL_ASSEMBLER_NAME (decl, mangle_decomp (decl, v));
7392     }
7393 }
7394
7395 /* Finish a decomposition declaration.  DECL is the underlying declaration
7396    "e", FIRST is the head of a chain of decls for the individual identifiers
7397    chained through DECL_CHAIN in reverse order and COUNT is the number of
7398    those decls.  */
7399
7400 void
7401 cp_finish_decomp (tree decl, tree first, unsigned int count)
7402 {
7403   if (error_operand_p (decl))
7404     {
7405      error_out:
7406       while (count--)
7407         {
7408           TREE_TYPE (first) = error_mark_node;
7409           if (DECL_HAS_VALUE_EXPR_P (first))
7410             {
7411               SET_DECL_VALUE_EXPR (first, NULL_TREE);
7412               DECL_HAS_VALUE_EXPR_P (first) = 0;
7413             }
7414           first = DECL_CHAIN (first);
7415         }
7416       if (DECL_P (decl) && DECL_NAMESPACE_SCOPE_P (decl))
7417         SET_DECL_ASSEMBLER_NAME (decl, get_identifier ("<decomp>"));
7418       return;
7419     }
7420
7421   location_t loc = DECL_SOURCE_LOCATION (decl);
7422   if (type_dependent_expression_p (decl)
7423       /* This happens for range for when not in templates.
7424          Still add the DECL_VALUE_EXPRs for later processing.  */
7425       || (!processing_template_decl
7426           && type_uses_auto (TREE_TYPE (decl))))
7427     {
7428       for (unsigned int i = 0; i < count; i++)
7429         {
7430           if (!DECL_HAS_VALUE_EXPR_P (first))
7431             {
7432               tree v = build_nt (ARRAY_REF, decl,
7433                                  size_int (count - i - 1),
7434                                  NULL_TREE, NULL_TREE);
7435               SET_DECL_VALUE_EXPR (first, v);
7436               DECL_HAS_VALUE_EXPR_P (first) = 1;
7437             }
7438           if (processing_template_decl)
7439             fit_decomposition_lang_decl (first, decl);
7440           first = DECL_CHAIN (first);
7441         }
7442       return;
7443     }
7444
7445   auto_vec<tree, 16> v;
7446   v.safe_grow (count);
7447   tree d = first;
7448   for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
7449     {
7450       v[count - i - 1] = d;
7451       fit_decomposition_lang_decl (d, decl);
7452     }
7453
7454   tree type = TREE_TYPE (decl);
7455   tree dexp = decl;
7456
7457   if (TREE_CODE (type) == REFERENCE_TYPE)
7458     {
7459       dexp = convert_from_reference (dexp);
7460       type = complete_type (TREE_TYPE (type));
7461       if (type == error_mark_node)
7462         goto error_out;
7463       if (!COMPLETE_TYPE_P (type))
7464         {
7465           error_at (loc, "structured binding refers to incomplete type %qT",
7466                     type);
7467           goto error_out;
7468         }
7469     }
7470
7471   tree eltype = NULL_TREE;
7472   unsigned HOST_WIDE_INT eltscnt = 0;
7473   if (TREE_CODE (type) == ARRAY_TYPE)
7474     {
7475       tree nelts;
7476       nelts = array_type_nelts_top (type);
7477       if (nelts == error_mark_node)
7478         goto error_out;
7479       if (!tree_fits_uhwi_p (nelts))
7480         {
7481           error_at (loc, "cannot decompose variable length array %qT", type);
7482           goto error_out;
7483         }
7484       eltscnt = tree_to_uhwi (nelts);
7485       if (count != eltscnt)
7486         {
7487        cnt_mismatch:
7488           if (count > eltscnt)
7489             error_n (loc, count,
7490                      "%u name provided for structured binding",
7491                      "%u names provided for structured binding", count);
7492           else
7493             error_n (loc, count,
7494                      "only %u name provided for structured binding",
7495                      "only %u names provided for structured binding", count);
7496           /* Some languages have special plural rules even for large values,
7497              but it is periodic with period of 10, 100, 1000 etc.  */
7498           inform_n (loc, eltscnt > INT_MAX
7499                          ? (eltscnt % 1000000) + 1000000 : eltscnt,
7500                     "while %qT decomposes into %wu element",
7501                     "while %qT decomposes into %wu elements",
7502                     type, eltscnt);
7503           goto error_out;
7504         }
7505       eltype = TREE_TYPE (type);
7506       for (unsigned int i = 0; i < count; i++)
7507         {
7508           TREE_TYPE (v[i]) = eltype;
7509           layout_decl (v[i], 0);
7510           if (processing_template_decl)
7511             continue;
7512           tree t = unshare_expr (dexp);
7513           t = build4_loc (DECL_SOURCE_LOCATION (v[i]), ARRAY_REF,
7514                           eltype, t, size_int (i), NULL_TREE,
7515                           NULL_TREE);
7516           SET_DECL_VALUE_EXPR (v[i], t);
7517           DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
7518         }
7519     }
7520   /* 2 GNU extensions.  */
7521   else if (TREE_CODE (type) == COMPLEX_TYPE)
7522     {
7523       eltscnt = 2;
7524       if (count != eltscnt)
7525         goto cnt_mismatch;
7526       eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
7527       for (unsigned int i = 0; i < count; i++)
7528         {
7529           TREE_TYPE (v[i]) = eltype;
7530           layout_decl (v[i], 0);
7531           if (processing_template_decl)
7532             continue;
7533           tree t = unshare_expr (dexp);
7534           t = build1_loc (DECL_SOURCE_LOCATION (v[i]),
7535                           i ? IMAGPART_EXPR : REALPART_EXPR, eltype,
7536                           t);
7537           SET_DECL_VALUE_EXPR (v[i], t);
7538           DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
7539         }
7540     }
7541   else if (TREE_CODE (type) == VECTOR_TYPE)
7542     {
7543       if (!TYPE_VECTOR_SUBPARTS (type).is_constant (&eltscnt))
7544         {
7545           error_at (loc, "cannot decompose variable length vector %qT", type);
7546           goto error_out;
7547         }
7548       if (count != eltscnt)
7549         goto cnt_mismatch;
7550       eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
7551       for (unsigned int i = 0; i < count; i++)
7552         {
7553           TREE_TYPE (v[i]) = eltype;
7554           layout_decl (v[i], 0);
7555           if (processing_template_decl)
7556             continue;
7557           tree t = unshare_expr (dexp);
7558           convert_vector_to_array_for_subscript (DECL_SOURCE_LOCATION (v[i]),
7559                                                  &t, size_int (i));
7560           t = build4_loc (DECL_SOURCE_LOCATION (v[i]), ARRAY_REF,
7561                           eltype, t, size_int (i), NULL_TREE,
7562                           NULL_TREE);
7563           SET_DECL_VALUE_EXPR (v[i], t);
7564           DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
7565         }
7566     }
7567   else if (tree tsize = get_tuple_size (type))
7568     {
7569       if (tsize == error_mark_node)
7570         {
7571           error_at (loc, "%<std::tuple_size<%T>::value%> is not an integral "
7572                          "constant expression", type);
7573           goto error_out;
7574         }
7575       if (!tree_fits_uhwi_p (tsize))
7576         {
7577           error_n (loc, count,
7578                    "%u name provided for structured binding",
7579                    "%u names provided for structured binding", count);
7580           inform (loc, "while %qT decomposes into %E elements",
7581                   type, tsize);
7582           goto error_out;
7583         }
7584       eltscnt = tree_to_uhwi (tsize);
7585       if (count != eltscnt)
7586         goto cnt_mismatch;
7587       int save_read = DECL_READ_P (decl);       
7588       for (unsigned i = 0; i < count; ++i)
7589         {
7590           location_t sloc = input_location;
7591           location_t dloc = DECL_SOURCE_LOCATION (v[i]);
7592
7593           input_location = dloc;
7594           tree init = get_tuple_decomp_init (decl, i);
7595           tree eltype = (init == error_mark_node ? error_mark_node
7596                          : get_tuple_element_type (type, i));
7597           input_location = sloc;
7598
7599           if (init == error_mark_node || eltype == error_mark_node)
7600             {
7601               inform (dloc, "in initialization of structured binding "
7602                       "variable %qD", v[i]);
7603               goto error_out;
7604             }
7605           /* Save the decltype away before reference collapse.  */
7606           store_decomp_type (v[i], eltype);
7607           eltype = cp_build_reference_type (eltype, !lvalue_p (init));
7608           TREE_TYPE (v[i]) = eltype;
7609           layout_decl (v[i], 0);
7610           if (DECL_HAS_VALUE_EXPR_P (v[i]))
7611             {
7612               /* In this case the names are variables, not just proxies.  */
7613               SET_DECL_VALUE_EXPR (v[i], NULL_TREE);
7614               DECL_HAS_VALUE_EXPR_P (v[i]) = 0;
7615             }
7616           if (!processing_template_decl)
7617             cp_finish_decl (v[i], init, /*constexpr*/false,
7618                             /*asm*/NULL_TREE, LOOKUP_NORMAL);
7619         }
7620       /* Ignore reads from the underlying decl performed during initialization
7621          of the individual variables.  If those will be read, we'll mark
7622          the underlying decl as read at that point.  */
7623       DECL_READ_P (decl) = save_read;
7624     }
7625   else if (TREE_CODE (type) == UNION_TYPE)
7626     {
7627       error_at (loc, "cannot decompose union type %qT", type);
7628       goto error_out;
7629     }
7630   else if (!CLASS_TYPE_P (type))
7631     {
7632       error_at (loc, "cannot decompose non-array non-class type %qT", type);
7633       goto error_out;
7634     }
7635   else if (LAMBDA_TYPE_P (type))
7636     {
7637       error_at (loc, "cannot decompose lambda closure type %qT", type);
7638       goto error_out;
7639     }
7640   else
7641     {
7642       tree btype = find_decomp_class_base (loc, type, NULL_TREE);
7643       if (btype == error_mark_node)
7644         goto error_out;
7645       else if (btype == NULL_TREE)
7646         {
7647           error_at (loc, "cannot decompose class type %qT without non-static "
7648                          "data members", type);
7649           goto error_out;
7650         }
7651       for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
7652         if (TREE_CODE (field) != FIELD_DECL
7653             || DECL_ARTIFICIAL (field)
7654             || DECL_UNNAMED_BIT_FIELD (field))
7655           continue;
7656         else
7657           eltscnt++;
7658       if (count != eltscnt)
7659         goto cnt_mismatch;
7660       tree t = dexp;
7661       if (type != btype)
7662         {
7663           t = convert_to_base (t, btype, /*check_access*/true,
7664                                /*nonnull*/false, tf_warning_or_error);
7665           type = btype;
7666         }
7667       unsigned int i = 0;
7668       for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
7669         if (TREE_CODE (field) != FIELD_DECL
7670             || DECL_ARTIFICIAL (field)
7671             || DECL_UNNAMED_BIT_FIELD (field))
7672           continue;
7673         else
7674           {
7675             tree tt = finish_non_static_data_member (field, unshare_expr (t),
7676                                                      NULL_TREE);
7677             if (REFERENCE_REF_P (tt))
7678               tt = TREE_OPERAND (tt, 0);
7679             TREE_TYPE (v[i]) = TREE_TYPE (tt);
7680             layout_decl (v[i], 0);
7681             if (!processing_template_decl)
7682               {
7683                 SET_DECL_VALUE_EXPR (v[i], tt);
7684                 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
7685               }
7686             i++;
7687           }
7688     }
7689   if (processing_template_decl)
7690     {
7691       for (unsigned int i = 0; i < count; i++)
7692         if (!DECL_HAS_VALUE_EXPR_P (v[i]))
7693           {
7694             tree a = build_nt (ARRAY_REF, decl, size_int (i),
7695                                NULL_TREE, NULL_TREE);
7696             SET_DECL_VALUE_EXPR (v[i], a);
7697             DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
7698           }
7699     }
7700 }
7701
7702 /* Returns a declaration for a VAR_DECL as if:
7703
7704      extern "C" TYPE NAME;
7705
7706    had been seen.  Used to create compiler-generated global
7707    variables.  */
7708
7709 static tree
7710 declare_global_var (tree name, tree type)
7711 {
7712   tree decl;
7713
7714   push_to_top_level ();
7715   decl = build_decl (input_location, VAR_DECL, name, type);
7716   TREE_PUBLIC (decl) = 1;
7717   DECL_EXTERNAL (decl) = 1;
7718   DECL_ARTIFICIAL (decl) = 1;
7719   DECL_CONTEXT (decl) = FROB_CONTEXT (global_namespace);
7720   /* If the user has explicitly declared this variable (perhaps
7721      because the code we are compiling is part of a low-level runtime
7722      library), then it is possible that our declaration will be merged
7723      with theirs by pushdecl.  */
7724   decl = pushdecl (decl);
7725   cp_finish_decl (decl, NULL_TREE, false, NULL_TREE, 0);
7726   pop_from_top_level ();
7727
7728   return decl;
7729 }
7730
7731 /* Returns the type for the argument to "__cxa_atexit" (or "atexit",
7732    if "__cxa_atexit" is not being used) corresponding to the function
7733    to be called when the program exits.  */
7734
7735 static tree
7736 get_atexit_fn_ptr_type (void)
7737 {
7738   tree fn_type;
7739
7740   if (!atexit_fn_ptr_type_node)
7741     {
7742       tree arg_type;
7743       if (flag_use_cxa_atexit 
7744           && !targetm.cxx.use_atexit_for_cxa_atexit ())
7745         /* The parameter to "__cxa_atexit" is "void (*)(void *)".  */
7746         arg_type = ptr_type_node;
7747       else
7748         /* The parameter to "atexit" is "void (*)(void)".  */
7749         arg_type = NULL_TREE;
7750       
7751       fn_type = build_function_type_list (void_type_node,
7752                                           arg_type, NULL_TREE);
7753       atexit_fn_ptr_type_node = build_pointer_type (fn_type);
7754     }
7755
7756   return atexit_fn_ptr_type_node;
7757 }
7758
7759 /* Returns a pointer to the `atexit' function.  Note that if
7760    FLAG_USE_CXA_ATEXIT is nonzero, then this will actually be the new
7761    `__cxa_atexit' function specified in the IA64 C++ ABI.  */
7762
7763 static tree
7764 get_atexit_node (void)
7765 {
7766   tree atexit_fndecl;
7767   tree fn_type;
7768   tree fn_ptr_type;
7769   const char *name;
7770   bool use_aeabi_atexit;
7771
7772   if (atexit_node)
7773     return atexit_node;
7774
7775   if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
7776     {
7777       /* The declaration for `__cxa_atexit' is:
7778
7779            int __cxa_atexit (void (*)(void *), void *, void *)
7780
7781          We build up the argument types and then the function type
7782          itself.  */
7783       tree argtype0, argtype1, argtype2;
7784
7785       use_aeabi_atexit = targetm.cxx.use_aeabi_atexit ();
7786       /* First, build the pointer-to-function type for the first
7787          argument.  */
7788       fn_ptr_type = get_atexit_fn_ptr_type ();
7789       /* Then, build the rest of the argument types.  */
7790       argtype2 = ptr_type_node;
7791       if (use_aeabi_atexit)
7792         {
7793           argtype1 = fn_ptr_type;
7794           argtype0 = ptr_type_node;
7795         }
7796       else
7797         {
7798           argtype1 = ptr_type_node;
7799           argtype0 = fn_ptr_type;
7800         }
7801       /* And the final __cxa_atexit type.  */
7802       fn_type = build_function_type_list (integer_type_node,
7803                                           argtype0, argtype1, argtype2,
7804                                           NULL_TREE);
7805       if (use_aeabi_atexit)
7806         name = "__aeabi_atexit";
7807       else
7808         name = "__cxa_atexit";
7809     }
7810   else
7811     {
7812       /* The declaration for `atexit' is:
7813
7814            int atexit (void (*)());
7815
7816          We build up the argument types and then the function type
7817          itself.  */
7818       fn_ptr_type = get_atexit_fn_ptr_type ();
7819       /* Build the final atexit type.  */
7820       fn_type = build_function_type_list (integer_type_node,
7821                                           fn_ptr_type, NULL_TREE);
7822       name = "atexit";
7823     }
7824
7825   /* Now, build the function declaration.  */
7826   push_lang_context (lang_name_c);
7827   atexit_fndecl = build_library_fn_ptr (name, fn_type, ECF_LEAF | ECF_NOTHROW);
7828   mark_used (atexit_fndecl);
7829   pop_lang_context ();
7830   atexit_node = decay_conversion (atexit_fndecl, tf_warning_or_error);
7831
7832   return atexit_node;
7833 }
7834
7835 /* Like get_atexit_node, but for thread-local cleanups.  */
7836
7837 static tree
7838 get_thread_atexit_node (void)
7839 {
7840   /* The declaration for `__cxa_thread_atexit' is:
7841
7842      int __cxa_thread_atexit (void (*)(void *), void *, void *) */
7843   tree fn_type = build_function_type_list (integer_type_node,
7844                                            get_atexit_fn_ptr_type (),
7845                                            ptr_type_node, ptr_type_node,
7846                                            NULL_TREE);
7847
7848   /* Now, build the function declaration.  */
7849   tree atexit_fndecl = build_library_fn_ptr ("__cxa_thread_atexit", fn_type,
7850                                              ECF_LEAF | ECF_NOTHROW);
7851   return decay_conversion (atexit_fndecl, tf_warning_or_error);
7852 }
7853
7854 /* Returns the __dso_handle VAR_DECL.  */
7855
7856 static tree
7857 get_dso_handle_node (void)
7858 {
7859   if (dso_handle_node)
7860     return dso_handle_node;
7861
7862   /* Declare the variable.  */
7863   dso_handle_node = declare_global_var (get_identifier ("__dso_handle"),
7864                                         ptr_type_node);
7865
7866 #ifdef HAVE_GAS_HIDDEN
7867   if (dso_handle_node != error_mark_node)
7868     {
7869       DECL_VISIBILITY (dso_handle_node) = VISIBILITY_HIDDEN;
7870       DECL_VISIBILITY_SPECIFIED (dso_handle_node) = 1;
7871     }
7872 #endif
7873
7874   return dso_handle_node;
7875 }
7876
7877 /* Begin a new function with internal linkage whose job will be simply
7878    to destroy some particular variable.  */
7879
7880 static GTY(()) int start_cleanup_cnt;
7881
7882 static tree
7883 start_cleanup_fn (void)
7884 {
7885   char name[32];
7886   tree fntype;
7887   tree fndecl;
7888   bool use_cxa_atexit = flag_use_cxa_atexit
7889                         && !targetm.cxx.use_atexit_for_cxa_atexit ();
7890
7891   push_to_top_level ();
7892
7893   /* No need to mangle this.  */
7894   push_lang_context (lang_name_c);
7895
7896   /* Build the name of the function.  */
7897   sprintf (name, "__tcf_%d", start_cleanup_cnt++);
7898   /* Build the function declaration.  */
7899   fntype = TREE_TYPE (get_atexit_fn_ptr_type ());
7900   fndecl = build_lang_decl (FUNCTION_DECL, get_identifier (name), fntype);
7901   /* It's a function with internal linkage, generated by the
7902      compiler.  */
7903   TREE_PUBLIC (fndecl) = 0;
7904   DECL_ARTIFICIAL (fndecl) = 1;
7905   /* Make the function `inline' so that it is only emitted if it is
7906      actually needed.  It is unlikely that it will be inlined, since
7907      it is only called via a function pointer, but we avoid unnecessary
7908      emissions this way.  */
7909   DECL_DECLARED_INLINE_P (fndecl) = 1;
7910   DECL_INTERFACE_KNOWN (fndecl) = 1;
7911   /* Build the parameter.  */
7912   if (use_cxa_atexit)
7913     {
7914       tree parmdecl = cp_build_parm_decl (fndecl, NULL_TREE, ptr_type_node);
7915       TREE_USED (parmdecl) = 1;
7916       DECL_READ_P (parmdecl) = 1;
7917       DECL_ARGUMENTS (fndecl) = parmdecl;
7918     }
7919
7920   pushdecl (fndecl);
7921   start_preparsed_function (fndecl, NULL_TREE, SF_PRE_PARSED);
7922
7923   pop_lang_context ();
7924
7925   return current_function_decl;
7926 }
7927
7928 /* Finish the cleanup function begun by start_cleanup_fn.  */
7929
7930 static void
7931 end_cleanup_fn (void)
7932 {
7933   expand_or_defer_fn (finish_function (/*inline_p=*/false));
7934
7935   pop_from_top_level ();
7936 }
7937
7938 /* Generate code to handle the destruction of DECL, an object with
7939    static storage duration.  */
7940
7941 tree
7942 register_dtor_fn (tree decl)
7943 {
7944   tree cleanup;
7945   tree addr;
7946   tree compound_stmt;
7947   tree fcall;
7948   tree type;
7949   bool ob_parm, dso_parm, use_dtor;
7950   tree arg0, arg1, arg2;
7951   tree atex_node;
7952
7953   type = TREE_TYPE (decl);
7954   if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
7955     return void_node;
7956
7957   /* If we're using "__cxa_atexit" (or "__cxa_thread_atexit" or
7958      "__aeabi_atexit"), and DECL is a class object, we can just pass the
7959      destructor to "__cxa_atexit"; we don't have to build a temporary
7960      function to do the cleanup.  */
7961   dso_parm = (flag_use_cxa_atexit
7962               && !targetm.cxx.use_atexit_for_cxa_atexit ());
7963   ob_parm = (CP_DECL_THREAD_LOCAL_P (decl) || dso_parm);
7964   use_dtor = ob_parm && CLASS_TYPE_P (type);
7965   if (use_dtor)
7966     {
7967       cleanup = get_class_binding (type, complete_dtor_identifier);
7968
7969       /* Make sure it is accessible.  */
7970       perform_or_defer_access_check (TYPE_BINFO (type), cleanup, cleanup,
7971                                      tf_warning_or_error);
7972     }
7973   else
7974     {
7975       /* Call build_cleanup before we enter the anonymous function so
7976          that any access checks will be done relative to the current
7977          scope, rather than the scope of the anonymous function.  */
7978       build_cleanup (decl);
7979   
7980       /* Now start the function.  */
7981       cleanup = start_cleanup_fn ();
7982       
7983       /* Now, recompute the cleanup.  It may contain SAVE_EXPRs that refer
7984          to the original function, rather than the anonymous one.  That
7985          will make the back end think that nested functions are in use,
7986          which causes confusion.  */
7987       push_deferring_access_checks (dk_no_check);
7988       fcall = build_cleanup (decl);
7989       pop_deferring_access_checks ();
7990       
7991       /* Create the body of the anonymous function.  */
7992       compound_stmt = begin_compound_stmt (BCS_FN_BODY);
7993       finish_expr_stmt (fcall);
7994       finish_compound_stmt (compound_stmt);
7995       end_cleanup_fn ();
7996     }
7997
7998   /* Call atexit with the cleanup function.  */
7999   mark_used (cleanup);
8000   cleanup = build_address (cleanup);
8001
8002   if (CP_DECL_THREAD_LOCAL_P (decl))
8003     atex_node = get_thread_atexit_node ();
8004   else
8005     atex_node = get_atexit_node ();
8006
8007   if (use_dtor)
8008     {
8009       /* We must convert CLEANUP to the type that "__cxa_atexit"
8010          expects.  */
8011       cleanup = build_nop (get_atexit_fn_ptr_type (), cleanup);
8012       /* "__cxa_atexit" will pass the address of DECL to the
8013          cleanup function.  */
8014       mark_used (decl);
8015       addr = build_address (decl);
8016       /* The declared type of the parameter to "__cxa_atexit" is
8017          "void *".  For plain "T*", we could just let the
8018          machinery in cp_build_function_call convert it -- but if the
8019          type is "cv-qualified T *", then we need to convert it
8020          before passing it in, to avoid spurious errors.  */
8021       addr = build_nop (ptr_type_node, addr);
8022     }
8023   else
8024     /* Since the cleanup functions we build ignore the address
8025        they're given, there's no reason to pass the actual address
8026        in, and, in general, it's cheaper to pass NULL than any
8027        other value.  */
8028     addr = null_pointer_node;
8029
8030   if (dso_parm)
8031     arg2 = cp_build_addr_expr (get_dso_handle_node (),
8032                                tf_warning_or_error);
8033   else if (ob_parm)
8034     /* Just pass NULL to the dso handle parm if we don't actually
8035        have a DSO handle on this target.  */
8036     arg2 = null_pointer_node;
8037   else
8038     arg2 = NULL_TREE;
8039
8040   if (ob_parm)
8041     {
8042       if (!CP_DECL_THREAD_LOCAL_P (decl)
8043           && targetm.cxx.use_aeabi_atexit ())
8044         {
8045           arg1 = cleanup;
8046           arg0 = addr;
8047         }
8048       else
8049         {
8050           arg1 = addr;
8051           arg0 = cleanup;
8052         }
8053     }
8054   else
8055     {
8056       arg0 = cleanup;
8057       arg1 = NULL_TREE;
8058     }
8059   return cp_build_function_call_nary (atex_node, tf_warning_or_error,
8060                                       arg0, arg1, arg2, NULL_TREE);
8061 }
8062
8063 /* DECL is a VAR_DECL with static storage duration.  INIT, if present,
8064    is its initializer.  Generate code to handle the construction
8065    and destruction of DECL.  */
8066
8067 static void
8068 expand_static_init (tree decl, tree init)
8069 {
8070   gcc_assert (VAR_P (decl));
8071   gcc_assert (TREE_STATIC (decl));
8072
8073   /* Some variables require no dynamic initialization.  */
8074   if (TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
8075     {
8076       /* Make sure the destructor is callable.  */
8077       cxx_maybe_build_cleanup (decl, tf_warning_or_error);
8078       if (!init)
8079         return;
8080     }
8081
8082   if (CP_DECL_THREAD_LOCAL_P (decl) && DECL_GNU_TLS_P (decl)
8083       && !DECL_FUNCTION_SCOPE_P (decl))
8084     {
8085       if (init)
8086         error ("non-local variable %qD declared %<__thread%> "
8087                "needs dynamic initialization", decl);
8088       else
8089         error ("non-local variable %qD declared %<__thread%> "
8090                "has a non-trivial destructor", decl);
8091       static bool informed;
8092       if (!informed)
8093         {
8094           inform (DECL_SOURCE_LOCATION (decl),
8095                   "C++11 %<thread_local%> allows dynamic initialization "
8096                   "and destruction");
8097           informed = true;
8098         }
8099       return;
8100     }
8101
8102   if (DECL_FUNCTION_SCOPE_P (decl))
8103     {
8104       /* Emit code to perform this initialization but once.  */
8105       tree if_stmt = NULL_TREE, inner_if_stmt = NULL_TREE;
8106       tree then_clause = NULL_TREE, inner_then_clause = NULL_TREE;
8107       tree guard, guard_addr;
8108       tree flag, begin;
8109       /* We don't need thread-safety code for thread-local vars.  */
8110       bool thread_guard = (flag_threadsafe_statics
8111                            && !CP_DECL_THREAD_LOCAL_P (decl));
8112
8113       /* Emit code to perform this initialization but once.  This code
8114          looks like:
8115
8116            static <type> guard;
8117            if (!__atomic_load (guard.first_byte)) {
8118              if (__cxa_guard_acquire (&guard)) {
8119                bool flag = false;
8120                try {
8121                  // Do initialization.
8122                  flag = true; __cxa_guard_release (&guard);
8123                  // Register variable for destruction at end of program.
8124                } catch {
8125                  if (!flag) __cxa_guard_abort (&guard);
8126                }
8127              }
8128            }
8129
8130          Note that the `flag' variable is only set to 1 *after* the
8131          initialization is complete.  This ensures that an exception,
8132          thrown during the construction, will cause the variable to
8133          reinitialized when we pass through this code again, as per:
8134
8135            [stmt.dcl]
8136
8137            If the initialization exits by throwing an exception, the
8138            initialization is not complete, so it will be tried again
8139            the next time control enters the declaration.
8140
8141          This process should be thread-safe, too; multiple threads
8142          should not be able to initialize the variable more than
8143          once.  */
8144
8145       /* Create the guard variable.  */
8146       guard = get_guard (decl);
8147
8148       /* Begin the conditional initialization.  */
8149       if_stmt = begin_if_stmt ();
8150
8151       finish_if_stmt_cond (get_guard_cond (guard, thread_guard), if_stmt);
8152       then_clause = begin_compound_stmt (BCS_NO_SCOPE);
8153
8154       if (thread_guard)
8155         {
8156           tree vfntype = NULL_TREE;
8157           tree acquire_name, release_name, abort_name;
8158           tree acquire_fn, release_fn, abort_fn;
8159           guard_addr = build_address (guard);
8160
8161           acquire_name = get_identifier ("__cxa_guard_acquire");
8162           release_name = get_identifier ("__cxa_guard_release");
8163           abort_name = get_identifier ("__cxa_guard_abort");
8164           acquire_fn = get_global_binding (acquire_name);
8165           release_fn = get_global_binding (release_name);
8166           abort_fn = get_global_binding (abort_name);
8167           if (!acquire_fn)
8168             acquire_fn = push_library_fn
8169               (acquire_name, build_function_type_list (integer_type_node,
8170                                                        TREE_TYPE (guard_addr),
8171                                                        NULL_TREE),
8172                NULL_TREE, ECF_NOTHROW | ECF_LEAF);
8173           if (!release_fn || !abort_fn)
8174             vfntype = build_function_type_list (void_type_node,
8175                                                 TREE_TYPE (guard_addr),
8176                                                 NULL_TREE);
8177           if (!release_fn)
8178             release_fn = push_library_fn (release_name, vfntype, NULL_TREE,
8179                                            ECF_NOTHROW | ECF_LEAF);
8180           if (!abort_fn)
8181             abort_fn = push_library_fn (abort_name, vfntype, NULL_TREE,
8182                                         ECF_NOTHROW | ECF_LEAF);
8183
8184           inner_if_stmt = begin_if_stmt ();
8185           finish_if_stmt_cond (build_call_n (acquire_fn, 1, guard_addr),
8186                                inner_if_stmt);
8187
8188           inner_then_clause = begin_compound_stmt (BCS_NO_SCOPE);
8189           begin = get_target_expr (boolean_false_node);
8190           flag = TARGET_EXPR_SLOT (begin);
8191
8192           TARGET_EXPR_CLEANUP (begin)
8193             = build3 (COND_EXPR, void_type_node, flag,
8194                       void_node,
8195                       build_call_n (abort_fn, 1, guard_addr));
8196           CLEANUP_EH_ONLY (begin) = 1;
8197
8198           /* Do the initialization itself.  */
8199           init = add_stmt_to_compound (begin, init);
8200           init = add_stmt_to_compound
8201             (init, build2 (MODIFY_EXPR, void_type_node, flag, boolean_true_node));
8202           init = add_stmt_to_compound
8203             (init, build_call_n (release_fn, 1, guard_addr));
8204         }
8205       else
8206         init = add_stmt_to_compound (init, set_guard (guard));
8207
8208       /* Use atexit to register a function for destroying this static
8209          variable.  */
8210       init = add_stmt_to_compound (init, register_dtor_fn (decl));
8211
8212       finish_expr_stmt (init);
8213
8214       if (thread_guard)
8215         {
8216           finish_compound_stmt (inner_then_clause);
8217           finish_then_clause (inner_if_stmt);
8218           finish_if_stmt (inner_if_stmt);
8219         }
8220
8221       finish_compound_stmt (then_clause);
8222       finish_then_clause (if_stmt);
8223       finish_if_stmt (if_stmt);
8224     }
8225   else if (CP_DECL_THREAD_LOCAL_P (decl))
8226     tls_aggregates = tree_cons (init, decl, tls_aggregates);
8227   else
8228     static_aggregates = tree_cons (init, decl, static_aggregates);
8229 }
8230
8231 \f
8232 /* Make TYPE a complete type based on INITIAL_VALUE.
8233    Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
8234    2 if there was no information (in which case assume 0 if DO_DEFAULT),
8235    3 if the initializer list is empty (in pedantic mode). */
8236
8237 int
8238 cp_complete_array_type (tree *ptype, tree initial_value, bool do_default)
8239 {
8240   int failure;
8241   tree type, elt_type;
8242
8243   /* Don't get confused by a CONSTRUCTOR for some other type.  */
8244   if (initial_value && TREE_CODE (initial_value) == CONSTRUCTOR
8245       && !BRACE_ENCLOSED_INITIALIZER_P (initial_value)
8246       && TREE_CODE (TREE_TYPE (initial_value)) != ARRAY_TYPE)
8247     return 1;
8248
8249   if (initial_value)
8250     {
8251       unsigned HOST_WIDE_INT i;
8252       tree value;
8253
8254       /* An array of character type can be initialized from a
8255          brace-enclosed string constant.
8256
8257          FIXME: this code is duplicated from reshape_init. Probably
8258          we should just call reshape_init here?  */
8259       if (char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (*ptype)))
8260           && TREE_CODE (initial_value) == CONSTRUCTOR
8261           && !vec_safe_is_empty (CONSTRUCTOR_ELTS (initial_value)))
8262         {
8263           vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initial_value);
8264           tree value = (*v)[0].value;
8265
8266           if (TREE_CODE (value) == STRING_CST
8267               && v->length () == 1)
8268             initial_value = value;
8269         }
8270
8271       /* If any of the elements are parameter packs, we can't actually
8272          complete this type now because the array size is dependent.  */
8273       if (TREE_CODE (initial_value) == CONSTRUCTOR)
8274         {
8275           FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (initial_value), 
8276                                       i, value)
8277             {
8278               if (PACK_EXPANSION_P (value))
8279                 return 0;
8280             }
8281         }
8282     }
8283
8284   failure = complete_array_type (ptype, initial_value, do_default);
8285
8286   /* We can create the array before the element type is complete, which
8287      means that we didn't have these two bits set in the original type
8288      either.  In completing the type, we are expected to propagate these
8289      bits.  See also complete_type which does the same thing for arrays
8290      of fixed size.  */
8291   type = *ptype;
8292   if (TYPE_DOMAIN (type))
8293     {
8294       elt_type = TREE_TYPE (type);
8295       TYPE_NEEDS_CONSTRUCTING (type) = TYPE_NEEDS_CONSTRUCTING (elt_type);
8296       TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
8297         = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (elt_type);
8298     }
8299
8300   return failure;
8301 }
8302
8303 /* As above, but either give an error or reject zero-size arrays, depending
8304    on COMPLAIN.  */
8305
8306 int
8307 cp_complete_array_type_or_error (tree *ptype, tree initial_value,
8308                                  bool do_default, tsubst_flags_t complain)
8309 {
8310   int failure;
8311   bool sfinae = !(complain & tf_error);
8312   /* In SFINAE context we can't be lenient about zero-size arrays.  */
8313   if (sfinae)
8314     ++pedantic;
8315   failure = cp_complete_array_type (ptype, initial_value, do_default);
8316   if (sfinae)
8317     --pedantic;
8318   if (failure)
8319     {
8320       if (sfinae)
8321         /* Not an error.  */;
8322       else if (failure == 1)
8323         error ("initializer fails to determine size of %qT", *ptype);
8324       else if (failure == 2)
8325         {
8326           if (do_default)
8327             error ("array size missing in %qT", *ptype);
8328         }
8329       else if (failure == 3)
8330         error ("zero-size array %qT", *ptype);
8331       *ptype = error_mark_node;
8332     }
8333   return failure;
8334 }
8335 \f
8336 /* Return zero if something is declared to be a member of type
8337    CTYPE when in the context of CUR_TYPE.  STRING is the error
8338    message to print in that case.  Otherwise, quietly return 1.  */
8339
8340 static int
8341 member_function_or_else (tree ctype, tree cur_type, enum overload_flags flags)
8342 {
8343   if (ctype && ctype != cur_type)
8344     {
8345       if (flags == DTOR_FLAG)
8346         error ("destructor for alien class %qT cannot be a member", ctype);
8347       else
8348         error ("constructor for alien class %qT cannot be a member", ctype);
8349       return 0;
8350     }
8351   return 1;
8352 }
8353 \f
8354 /* Subroutine of `grokdeclarator'.  */
8355
8356 /* Generate errors possibly applicable for a given set of specifiers.
8357    This is for ARM $7.1.2.  */
8358
8359 static void
8360 bad_specifiers (tree object,
8361                 enum bad_spec_place type,
8362                 int virtualp,
8363                 int quals,
8364                 int inlinep,
8365                 int friendp,
8366                 int raises)
8367 {
8368   switch (type)
8369     {
8370       case BSP_VAR:
8371         if (virtualp)
8372           error ("%qD declared as a %<virtual%> variable", object);
8373         if (quals)
8374           error ("%<const%> and %<volatile%> function specifiers on "
8375                  "%qD invalid in variable declaration", object);
8376         break;
8377       case BSP_PARM:
8378         if (virtualp)
8379           error ("%qD declared as a %<virtual%> parameter", object);
8380         if (inlinep)
8381           error ("%qD declared as an %<inline%> parameter", object);
8382         if (quals)
8383           error ("%<const%> and %<volatile%> function specifiers on "
8384                  "%qD invalid in parameter declaration", object);
8385         break;
8386       case BSP_TYPE:
8387         if (virtualp)
8388           error ("%qD declared as a %<virtual%> type", object);
8389         if (inlinep)
8390           error ("%qD declared as an %<inline%> type", object);
8391         if (quals)
8392           error ("%<const%> and %<volatile%> function specifiers on "
8393                  "%qD invalid in type declaration", object);
8394         break;
8395       case BSP_FIELD:
8396         if (virtualp)
8397           error ("%qD declared as a %<virtual%> field", object);
8398         if (inlinep)
8399           error ("%qD declared as an %<inline%> field", object);
8400         if (quals)
8401           error ("%<const%> and %<volatile%> function specifiers on "
8402                  "%qD invalid in field declaration", object);
8403         break;
8404       default:
8405         gcc_unreachable();
8406     }
8407   if (friendp)
8408     error ("%q+D declared as a friend", object);
8409   if (raises
8410       && !flag_noexcept_type
8411       && (TREE_CODE (object) == TYPE_DECL
8412           || (!TYPE_PTRFN_P (TREE_TYPE (object))
8413               && !TYPE_REFFN_P (TREE_TYPE (object))
8414               && !TYPE_PTRMEMFUNC_P (TREE_TYPE (object)))))
8415     error ("%q+D declared with an exception specification", object);
8416 }
8417
8418 /* DECL is a member function or static data member and is presently
8419    being defined.  Check that the definition is taking place in a
8420    valid namespace.  */
8421
8422 static void
8423 check_class_member_definition_namespace (tree decl)
8424 {
8425   /* These checks only apply to member functions and static data
8426      members.  */
8427   gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
8428   /* We check for problems with specializations in pt.c in
8429      check_specialization_namespace, where we can issue better
8430      diagnostics.  */
8431   if (processing_specialization)
8432     return;
8433   /* We check this in check_explicit_instantiation_namespace.  */
8434   if (processing_explicit_instantiation)
8435     return;
8436   /* [class.mfct]
8437
8438      A member function definition that appears outside of the
8439      class definition shall appear in a namespace scope enclosing
8440      the class definition.
8441
8442      [class.static.data]
8443
8444      The definition for a static data member shall appear in a
8445      namespace scope enclosing the member's class definition.  */
8446   if (!is_ancestor (current_namespace, DECL_CONTEXT (decl)))
8447     permerror (input_location, "definition of %qD is not in namespace enclosing %qT",
8448                decl, DECL_CONTEXT (decl));
8449 }
8450
8451 /* Build a PARM_DECL for the "this" parameter of FN.  TYPE is the
8452    METHOD_TYPE for a non-static member function; QUALS are the
8453    cv-qualifiers that apply to the function.  */
8454
8455 tree
8456 build_this_parm (tree fn, tree type, cp_cv_quals quals)
8457 {
8458   tree this_type;
8459   tree qual_type;
8460   tree parm;
8461   cp_cv_quals this_quals;
8462
8463   if (CLASS_TYPE_P (type))
8464     {
8465       this_type
8466         = cp_build_qualified_type (type, quals & ~TYPE_QUAL_RESTRICT);
8467       this_type = build_pointer_type (this_type);
8468     }
8469   else
8470     this_type = type_of_this_parm (type);
8471   /* The `this' parameter is implicitly `const'; it cannot be
8472      assigned to.  */
8473   this_quals = (quals & TYPE_QUAL_RESTRICT) | TYPE_QUAL_CONST;
8474   qual_type = cp_build_qualified_type (this_type, this_quals);
8475   parm = build_artificial_parm (fn, this_identifier, qual_type);
8476   cp_apply_type_quals_to_decl (this_quals, parm);
8477   return parm;
8478 }
8479
8480 /* DECL is a static member function.  Complain if it was declared
8481    with function-cv-quals.  */
8482
8483 static void
8484 check_static_quals (tree decl, cp_cv_quals quals)
8485 {
8486   if (quals != TYPE_UNQUALIFIED)
8487     error ("static member function %q#D declared with type qualifiers",
8488            decl);
8489 }
8490
8491 // Check that FN takes no arguments and returns bool.
8492 static void
8493 check_concept_fn (tree fn)
8494 {
8495   // A constraint is nullary.
8496   if (DECL_ARGUMENTS (fn))
8497     error ("concept %q#D declared with function parameters", fn);
8498
8499   // The declared return type of the concept shall be bool, and
8500   // it shall not be deduced from it definition.
8501   tree type = TREE_TYPE (TREE_TYPE (fn));
8502   if (is_auto (type))
8503     error ("concept %q#D declared with a deduced return type", fn);
8504   else if (type != boolean_type_node)
8505     error ("concept %q#D with non-%<bool%> return type %qT", fn, type);
8506 }
8507
8508 /* Helper function.  Replace the temporary this parameter injected
8509    during cp_finish_omp_declare_simd with the real this parameter.  */
8510
8511 static tree
8512 declare_simd_adjust_this (tree *tp, int *walk_subtrees, void *data)
8513 {
8514   tree this_parm = (tree) data;
8515   if (TREE_CODE (*tp) == PARM_DECL
8516       && DECL_NAME (*tp) == this_identifier
8517       && *tp != this_parm)
8518     *tp = this_parm;
8519   else if (TYPE_P (*tp))
8520     *walk_subtrees = 0;
8521   return NULL_TREE;
8522 }
8523
8524 /* CTYPE is class type, or null if non-class.
8525    TYPE is type this FUNCTION_DECL should have, either FUNCTION_TYPE
8526    or METHOD_TYPE.
8527    DECLARATOR is the function's name.
8528    PARMS is a chain of PARM_DECLs for the function.
8529    VIRTUALP is truthvalue of whether the function is virtual or not.
8530    FLAGS are to be passed through to `grokclassfn'.
8531    QUALS are qualifiers indicating whether the function is `const'
8532    or `volatile'.
8533    RAISES is a list of exceptions that this function can raise.
8534    CHECK is 1 if we must find this method in CTYPE, 0 if we should
8535    not look, and -1 if we should not call `grokclassfn' at all.
8536
8537    SFK is the kind of special function (if any) for the new function.
8538
8539    Returns `NULL_TREE' if something goes wrong, after issuing
8540    applicable error messages.  */
8541
8542 static tree
8543 grokfndecl (tree ctype,
8544             tree type,
8545             tree declarator,
8546             tree parms,
8547             tree orig_declarator,
8548             tree decl_reqs,
8549             int virtualp,
8550             enum overload_flags flags,
8551             cp_cv_quals quals,
8552             cp_ref_qualifier rqual,
8553             tree raises,
8554             int check,
8555             int friendp,
8556             int publicp,
8557             int inlinep,
8558             bool deletedp,
8559             special_function_kind sfk,
8560             bool funcdef_flag,
8561             int template_count,
8562             tree in_namespace,
8563             tree* attrlist,
8564             location_t location)
8565 {
8566   tree decl;
8567   int staticp = ctype && TREE_CODE (type) == FUNCTION_TYPE;
8568   tree t;
8569
8570   // Was the concept specifier present?
8571   bool concept_p = inlinep & 4;
8572
8573   // Concept declarations must have a corresponding definition.
8574   if (concept_p && !funcdef_flag)
8575     {
8576       error ("concept %qD has no definition", declarator);
8577       return NULL_TREE;
8578     }
8579
8580   if (rqual)
8581     type = build_ref_qualified_type (type, rqual);
8582   if (raises)
8583     type = build_exception_variant (type, raises);
8584
8585   decl = build_lang_decl (FUNCTION_DECL, declarator, type);
8586
8587   /* Set the constraints on the declaration. */
8588   if (flag_concepts)
8589     {
8590       tree tmpl_reqs = NULL_TREE;
8591       if (processing_template_decl > template_class_depth (ctype))
8592         tmpl_reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
8593
8594       /* Adjust the required expression into a constraint. */
8595       if (decl_reqs)
8596         decl_reqs = normalize_expression (decl_reqs);
8597
8598       tree ci = build_constraints (tmpl_reqs, decl_reqs);
8599       set_constraints (decl, ci);
8600     }
8601
8602   /* If we have an explicit location, use it, otherwise use whatever
8603      build_lang_decl used (probably input_location).  */
8604   if (location != UNKNOWN_LOCATION)
8605     DECL_SOURCE_LOCATION (decl) = location;
8606
8607   if (TREE_CODE (type) == METHOD_TYPE)
8608     {
8609       tree parm = build_this_parm (decl, type, quals);
8610       DECL_CHAIN (parm) = parms;
8611       parms = parm;
8612
8613       /* Allocate space to hold the vptr bit if needed.  */
8614       SET_DECL_ALIGN (decl, MINIMUM_METHOD_BOUNDARY);
8615     }
8616
8617   DECL_ARGUMENTS (decl) = parms;
8618   for (t = parms; t; t = DECL_CHAIN (t))
8619     DECL_CONTEXT (t) = decl;
8620
8621   /* Propagate volatile out from type to decl.  */
8622   if (TYPE_VOLATILE (type))
8623     TREE_THIS_VOLATILE (decl) = 1;
8624
8625   /* Setup decl according to sfk.  */
8626   switch (sfk)
8627     {
8628     case sfk_constructor:
8629     case sfk_copy_constructor:
8630     case sfk_move_constructor:
8631       DECL_CXX_CONSTRUCTOR_P (decl) = 1;
8632       DECL_NAME (decl) = ctor_identifier;
8633       break;
8634     case sfk_destructor:
8635       DECL_CXX_DESTRUCTOR_P (decl) = 1;
8636       DECL_NAME (decl) = dtor_identifier;
8637       break;
8638     default:
8639       break;
8640     }
8641
8642   if (friendp && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)
8643     {
8644       if (funcdef_flag)
8645         error ("defining explicit specialization %qD in friend declaration",
8646                orig_declarator);
8647       else
8648         {
8649           tree fns = TREE_OPERAND (orig_declarator, 0);
8650           tree args = TREE_OPERAND (orig_declarator, 1);
8651
8652           if (PROCESSING_REAL_TEMPLATE_DECL_P ())
8653             {
8654               /* Something like `template <class T> friend void f<T>()'.  */
8655               error ("invalid use of template-id %qD in declaration "
8656                      "of primary template",
8657                      orig_declarator);
8658               return NULL_TREE;
8659             }
8660
8661
8662           /* A friend declaration of the form friend void f<>().  Record
8663              the information in the TEMPLATE_ID_EXPR.  */
8664           SET_DECL_IMPLICIT_INSTANTIATION (decl);
8665
8666           gcc_assert (identifier_p (fns) || TREE_CODE (fns) == OVERLOAD);
8667           DECL_TEMPLATE_INFO (decl) = build_template_info (fns, args);
8668
8669           for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
8670             if (TREE_PURPOSE (t)
8671                 && TREE_CODE (TREE_PURPOSE (t)) == DEFAULT_ARG)
8672             {
8673               error ("default arguments are not allowed in declaration "
8674                      "of friend template specialization %qD",
8675                      decl);
8676               return NULL_TREE;
8677             }
8678
8679           if (inlinep & 1)
8680             {
8681               error ("%<inline%> is not allowed in declaration of friend "
8682                      "template specialization %qD",
8683                      decl);
8684               return NULL_TREE;
8685             }
8686         }
8687     }
8688
8689   /* If this decl has namespace scope, set that up.  */
8690   if (in_namespace)
8691     set_decl_namespace (decl, in_namespace, friendp);
8692   else if (!ctype)
8693     DECL_CONTEXT (decl) = FROB_CONTEXT (current_decl_namespace ());
8694
8695   /* `main' and builtins have implicit 'C' linkage.  */
8696   if (ctype == NULL_TREE
8697       && DECL_FILE_SCOPE_P (decl)
8698       && current_lang_name == lang_name_cplusplus
8699       && (MAIN_NAME_P (declarator)
8700           || (IDENTIFIER_LENGTH (declarator) > 10
8701               && IDENTIFIER_POINTER (declarator)[0] == '_'
8702               && IDENTIFIER_POINTER (declarator)[1] == '_'
8703               && strncmp (IDENTIFIER_POINTER (declarator)+2,
8704                           "builtin_", 8) == 0)
8705           || (targetcm.cxx_implicit_extern_c
8706               && (targetcm.cxx_implicit_extern_c
8707                   (IDENTIFIER_POINTER (declarator))))))
8708     SET_DECL_LANGUAGE (decl, lang_c);
8709
8710   /* Should probably propagate const out from type to decl I bet (mrs).  */
8711   if (staticp)
8712     {
8713       DECL_STATIC_FUNCTION_P (decl) = 1;
8714       DECL_CONTEXT (decl) = ctype;
8715     }
8716
8717   if (deletedp)
8718     DECL_DELETED_FN (decl) = 1;
8719
8720   if (ctype)
8721     {
8722       DECL_CONTEXT (decl) = ctype;
8723       if (funcdef_flag)
8724         check_class_member_definition_namespace (decl);
8725     }
8726
8727   if (ctype == NULL_TREE && DECL_MAIN_P (decl))
8728     {
8729       if (PROCESSING_REAL_TEMPLATE_DECL_P())
8730         error ("cannot declare %<::main%> to be a template");
8731       if (inlinep & 1)
8732         error ("cannot declare %<::main%> to be inline");
8733       if (inlinep & 2)
8734         error ("cannot declare %<::main%> to be %<constexpr%>");
8735       if (!publicp)
8736         error ("cannot declare %<::main%> to be static");
8737       inlinep = 0;
8738       publicp = 1;
8739     }
8740
8741   /* Members of anonymous types and local classes have no linkage; make
8742      them internal.  If a typedef is made later, this will be changed.  */
8743   if (ctype && (!TREE_PUBLIC (TYPE_MAIN_DECL (ctype))
8744                 || decl_function_context (TYPE_MAIN_DECL (ctype))))
8745     publicp = 0;
8746
8747   if (publicp && cxx_dialect == cxx98)
8748     {
8749       /* [basic.link]: A name with no linkage (notably, the name of a class
8750          or enumeration declared in a local scope) shall not be used to
8751          declare an entity with linkage.
8752
8753          DR 757 relaxes this restriction for C++0x.  */
8754       no_linkage_error (decl);
8755     }
8756
8757   TREE_PUBLIC (decl) = publicp;
8758   if (! publicp)
8759     {
8760       DECL_INTERFACE_KNOWN (decl) = 1;
8761       DECL_NOT_REALLY_EXTERN (decl) = 1;
8762     }
8763
8764   /* If the declaration was declared inline, mark it as such.  */
8765   if (inlinep)
8766     {
8767       DECL_DECLARED_INLINE_P (decl) = 1;
8768       if (publicp)
8769         DECL_COMDAT (decl) = 1;
8770     }
8771   if (inlinep & 2)
8772     DECL_DECLARED_CONSTEXPR_P (decl) = true;
8773
8774   // If the concept declaration specifier was found, check
8775   // that the declaration satisfies the necessary requirements.
8776   if (concept_p)
8777     {
8778       DECL_DECLARED_CONCEPT_P (decl) = true;
8779       check_concept_fn (decl);
8780     }
8781
8782   DECL_EXTERNAL (decl) = 1;
8783   if (TREE_CODE (type) == FUNCTION_TYPE)
8784     {
8785       if (quals || rqual)
8786         TREE_TYPE (decl) = apply_memfn_quals (TREE_TYPE (decl),
8787                                               TYPE_UNQUALIFIED,
8788                                               REF_QUAL_NONE);
8789
8790       if (quals)
8791         {
8792           error (ctype
8793                  ? G_("static member function %qD cannot have cv-qualifier")
8794                  : G_("non-member function %qD cannot have cv-qualifier"),
8795                  decl);
8796           quals = TYPE_UNQUALIFIED;
8797         }
8798
8799       if (rqual)
8800         {
8801           error (ctype
8802                  ? G_("static member function %qD cannot have ref-qualifier")
8803                  : G_("non-member function %qD cannot have ref-qualifier"),
8804                  decl);
8805           rqual = REF_QUAL_NONE;
8806         }
8807     }
8808
8809   if (deduction_guide_p (decl))
8810     {
8811       if (!DECL_NAMESPACE_SCOPE_P (decl))
8812         {
8813           error_at (location, "deduction guide %qD must be declared at "
8814                     "namespace scope", decl);
8815           return NULL_TREE;
8816         }
8817       if (funcdef_flag)
8818         error_at (location,
8819                   "deduction guide %qD must not have a function body", decl);
8820     }
8821   else if (IDENTIFIER_ANY_OP_P (DECL_NAME (decl))
8822            && !grok_op_properties (decl, /*complain=*/true))
8823     return NULL_TREE;
8824   else if (UDLIT_OPER_P (DECL_NAME (decl)))
8825     {
8826       bool long_long_unsigned_p;
8827       bool long_double_p;
8828       const char *suffix = NULL;
8829       /* [over.literal]/6: Literal operators shall not have C linkage. */
8830       if (DECL_LANGUAGE (decl) == lang_c)
8831         {
8832           error ("literal operator with C linkage");
8833           maybe_show_extern_c_location ();
8834           return NULL_TREE;
8835         }
8836
8837       if (DECL_NAMESPACE_SCOPE_P (decl))
8838         {
8839           if (!check_literal_operator_args (decl, &long_long_unsigned_p,
8840                                             &long_double_p))
8841             {
8842               error ("%qD has invalid argument list", decl);
8843               return NULL_TREE;
8844             }
8845
8846           suffix = UDLIT_OP_SUFFIX (DECL_NAME (decl));
8847           if (long_long_unsigned_p)
8848             {
8849               if (cpp_interpret_int_suffix (parse_in, suffix, strlen (suffix)))
8850                 warning (0, "integer suffix %qs"
8851                             " shadowed by implementation", suffix);
8852             }
8853           else if (long_double_p)
8854             {
8855               if (cpp_interpret_float_suffix (parse_in, suffix, strlen (suffix)))
8856                 warning (0, "floating point suffix %qs"
8857                             " shadowed by implementation", suffix);
8858             }
8859         }
8860       else
8861         {
8862           error ("%qD must be a non-member function", decl);
8863           return NULL_TREE;
8864         }
8865     }
8866
8867   if (funcdef_flag)
8868     /* Make the init_value nonzero so pushdecl knows this is not
8869        tentative.  error_mark_node is replaced later with the BLOCK.  */
8870     DECL_INITIAL (decl) = error_mark_node;
8871
8872   if (TYPE_NOTHROW_P (type) || nothrow_libfn_p (decl))
8873     TREE_NOTHROW (decl) = 1;
8874
8875   if (flag_openmp || flag_openmp_simd)
8876     {
8877       /* Adjust "omp declare simd" attributes.  */
8878       tree ods = lookup_attribute ("omp declare simd", *attrlist);
8879       if (ods)
8880         {
8881           tree attr;
8882           for (attr = ods; attr;
8883                attr = lookup_attribute ("omp declare simd", TREE_CHAIN (attr)))
8884             {
8885               if (TREE_CODE (type) == METHOD_TYPE)
8886                 walk_tree (&TREE_VALUE (attr), declare_simd_adjust_this,
8887                            DECL_ARGUMENTS (decl), NULL);
8888               if (TREE_VALUE (attr) != NULL_TREE)
8889                 {
8890                   tree cl = TREE_VALUE (TREE_VALUE (attr));
8891                   cl = c_omp_declare_simd_clauses_to_numbers
8892                                                 (DECL_ARGUMENTS (decl), cl);
8893                   if (cl)
8894                     TREE_VALUE (TREE_VALUE (attr)) = cl;
8895                   else
8896                     TREE_VALUE (attr) = NULL_TREE;
8897                 }
8898             }
8899         }
8900     }
8901
8902   /* Caller will do the rest of this.  */
8903   if (check < 0)
8904     return decl;
8905
8906   if (ctype != NULL_TREE)
8907     grokclassfn (ctype, decl, flags);
8908
8909   /* 12.4/3  */
8910   if (cxx_dialect >= cxx11
8911       && DECL_DESTRUCTOR_P (decl)
8912       && !TYPE_BEING_DEFINED (DECL_CONTEXT (decl))
8913       && !processing_template_decl)
8914     deduce_noexcept_on_destructor (decl);
8915
8916   decl = check_explicit_specialization (orig_declarator, decl,
8917                                         template_count,
8918                                         2 * funcdef_flag +
8919                                         4 * (friendp != 0) +
8920                                         8 * concept_p);
8921   if (decl == error_mark_node)
8922     return NULL_TREE;
8923
8924   if (DECL_STATIC_FUNCTION_P (decl))
8925     check_static_quals (decl, quals);
8926
8927   if (attrlist)
8928     {
8929       cplus_decl_attributes (&decl, *attrlist, 0);
8930       *attrlist = NULL_TREE;
8931     }
8932
8933   /* Check main's type after attributes have been applied.  */
8934   if (ctype == NULL_TREE && DECL_MAIN_P (decl))
8935     {
8936       if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
8937                         integer_type_node))
8938         {
8939           tree oldtypeargs = TYPE_ARG_TYPES (TREE_TYPE (decl));
8940           tree newtype;
8941           error ("%<::main%> must return %<int%>");
8942           newtype = build_function_type (integer_type_node, oldtypeargs);
8943           TREE_TYPE (decl) = newtype;
8944         }
8945       if (warn_main)
8946         check_main_parameter_types (decl);
8947     }
8948
8949   if (ctype != NULL_TREE && check)
8950     {
8951       tree old_decl = check_classfn (ctype, decl,
8952                                      (processing_template_decl
8953                                       > template_class_depth (ctype))
8954                                      ? current_template_parms
8955                                      : NULL_TREE);
8956
8957       if (old_decl == error_mark_node)
8958         return NULL_TREE;
8959
8960       if (old_decl)
8961         {
8962           tree ok;
8963           tree pushed_scope;
8964
8965           if (TREE_CODE (old_decl) == TEMPLATE_DECL)
8966             /* Because grokfndecl is always supposed to return a
8967                FUNCTION_DECL, we pull out the DECL_TEMPLATE_RESULT
8968                here.  We depend on our callers to figure out that its
8969                really a template that's being returned.  */
8970             old_decl = DECL_TEMPLATE_RESULT (old_decl);
8971
8972           if (DECL_STATIC_FUNCTION_P (old_decl)
8973               && TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
8974             {
8975               /* Remove the `this' parm added by grokclassfn.  */
8976               revert_static_member_fn (decl);
8977               check_static_quals (decl, quals);
8978             }
8979           if (DECL_ARTIFICIAL (old_decl))
8980             {
8981               error ("definition of implicitly-declared %qD", old_decl);
8982               return NULL_TREE;
8983             }
8984           else if (DECL_DEFAULTED_FN (old_decl))
8985             {
8986               error ("definition of explicitly-defaulted %q+D", decl);
8987               inform (DECL_SOURCE_LOCATION (old_decl),
8988                       "%q#D explicitly defaulted here", old_decl);
8989               return NULL_TREE;
8990             }
8991
8992           /* Since we've smashed OLD_DECL to its
8993              DECL_TEMPLATE_RESULT, we must do the same to DECL.  */
8994           if (TREE_CODE (decl) == TEMPLATE_DECL)
8995             decl = DECL_TEMPLATE_RESULT (decl);
8996
8997           /* Attempt to merge the declarations.  This can fail, in
8998              the case of some invalid specialization declarations.  */
8999           pushed_scope = push_scope (ctype);
9000           ok = duplicate_decls (decl, old_decl, friendp);
9001           if (pushed_scope)
9002             pop_scope (pushed_scope);
9003           if (!ok)
9004             {
9005               error ("no %q#D member function declared in class %qT",
9006                      decl, ctype);
9007               return NULL_TREE;
9008             }
9009           if (ok == error_mark_node)
9010             return NULL_TREE;
9011           return old_decl;
9012         }
9013     }
9014
9015   if (DECL_CONSTRUCTOR_P (decl) && !grok_ctor_properties (ctype, decl))
9016     return NULL_TREE;
9017
9018   if (ctype == NULL_TREE || check)
9019     return decl;
9020
9021   if (virtualp)
9022     DECL_VIRTUAL_P (decl) = 1;
9023
9024   return decl;
9025 }
9026
9027 /* decl is a FUNCTION_DECL.
9028    specifiers are the parsed virt-specifiers.
9029
9030    Set flags to reflect the virt-specifiers.
9031
9032    Returns decl.  */
9033
9034 static tree
9035 set_virt_specifiers (tree decl, cp_virt_specifiers specifiers)
9036 {
9037   if (decl == NULL_TREE)
9038     return decl;
9039   if (specifiers & VIRT_SPEC_OVERRIDE)
9040     DECL_OVERRIDE_P (decl) = 1;
9041   if (specifiers & VIRT_SPEC_FINAL)
9042     DECL_FINAL_P (decl) = 1;
9043   return decl;
9044 }
9045
9046 /* DECL is a VAR_DECL for a static data member.  Set flags to reflect
9047    the linkage that DECL will receive in the object file.  */
9048
9049 static void
9050 set_linkage_for_static_data_member (tree decl)
9051 {
9052   /* A static data member always has static storage duration and
9053      external linkage.  Note that static data members are forbidden in
9054      local classes -- the only situation in which a class has
9055      non-external linkage.  */
9056   TREE_PUBLIC (decl) = 1;
9057   TREE_STATIC (decl) = 1;
9058   /* For non-template classes, static data members are always put
9059      out in exactly those files where they are defined, just as
9060      with ordinary namespace-scope variables.  */
9061   if (!processing_template_decl)
9062     DECL_INTERFACE_KNOWN (decl) = 1;
9063 }
9064
9065 /* Create a VAR_DECL named NAME with the indicated TYPE.
9066
9067    If SCOPE is non-NULL, it is the class type or namespace containing
9068    the variable.  If SCOPE is NULL, the variable should is created in
9069    the innermost enclosing scope.  */
9070
9071 static tree
9072 grokvardecl (tree type,
9073              tree name,
9074              tree orig_declarator,
9075              const cp_decl_specifier_seq *declspecs,
9076              int initialized,
9077              int type_quals,
9078              int inlinep,
9079              bool conceptp,
9080              int template_count,
9081              tree scope)
9082 {
9083   tree decl;
9084   tree explicit_scope;
9085
9086   gcc_assert (!name || identifier_p (name));
9087
9088   bool constp = (type_quals & TYPE_QUAL_CONST) != 0;
9089   bool volatilep = (type_quals & TYPE_QUAL_VOLATILE) != 0;
9090
9091   /* Compute the scope in which to place the variable, but remember
9092      whether or not that scope was explicitly specified by the user.   */
9093   explicit_scope = scope;
9094   if (!scope)
9095     {
9096       /* An explicit "extern" specifier indicates a namespace-scope
9097          variable.  */
9098       if (declspecs->storage_class == sc_extern)
9099         scope = current_decl_namespace ();
9100       else if (!at_function_scope_p ())
9101         scope = current_scope ();
9102     }
9103
9104   if (scope
9105       && (/* If the variable is a namespace-scope variable declared in a
9106              template, we need DECL_LANG_SPECIFIC.  */
9107           (TREE_CODE (scope) == NAMESPACE_DECL && processing_template_decl)
9108           /* Similarly for namespace-scope variables with language linkage
9109              other than C++.  */
9110           || (TREE_CODE (scope) == NAMESPACE_DECL
9111               && current_lang_name != lang_name_cplusplus)
9112           /* Similarly for static data members.  */
9113           || TYPE_P (scope)
9114           /* Similarly for explicit specializations.  */
9115           || (orig_declarator
9116               && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)))
9117     decl = build_lang_decl (VAR_DECL, name, type);
9118   else
9119     decl = build_decl (input_location, VAR_DECL, name, type);
9120
9121   if (explicit_scope && TREE_CODE (explicit_scope) == NAMESPACE_DECL)
9122     set_decl_namespace (decl, explicit_scope, 0);
9123   else
9124     DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
9125
9126   if (declspecs->storage_class == sc_extern)
9127     {
9128       DECL_THIS_EXTERN (decl) = 1;
9129       DECL_EXTERNAL (decl) = !initialized;
9130     }
9131
9132   if (DECL_CLASS_SCOPE_P (decl))
9133     {
9134       set_linkage_for_static_data_member (decl);
9135       /* This function is only called with out-of-class definitions.  */
9136       DECL_EXTERNAL (decl) = 0;
9137       check_class_member_definition_namespace (decl);
9138     }
9139   /* At top level, either `static' or no s.c. makes a definition
9140      (perhaps tentative), and absence of `static' makes it public.  */
9141   else if (toplevel_bindings_p ())
9142     {
9143       TREE_PUBLIC (decl) = (declspecs->storage_class != sc_static
9144                             && (DECL_THIS_EXTERN (decl)
9145                                 || ! constp
9146                                 || volatilep
9147                                 || inlinep));
9148       TREE_STATIC (decl) = ! DECL_EXTERNAL (decl);
9149     }
9150   /* Not at top level, only `static' makes a static definition.  */
9151   else
9152     {
9153       TREE_STATIC (decl) = declspecs->storage_class == sc_static;
9154       TREE_PUBLIC (decl) = DECL_EXTERNAL (decl);
9155     }
9156
9157   if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
9158     {
9159       if (DECL_EXTERNAL (decl) || TREE_STATIC (decl))
9160         {
9161           CP_DECL_THREAD_LOCAL_P (decl) = true;
9162           if (!processing_template_decl)
9163             set_decl_tls_model (decl, decl_default_tls_model (decl));
9164         }
9165       if (declspecs->gnu_thread_keyword_p)
9166         SET_DECL_GNU_TLS_P (decl);
9167     }
9168
9169   /* If the type of the decl has no linkage, make sure that we'll
9170      notice that in mark_used.  */
9171   if (cxx_dialect > cxx98
9172       && decl_linkage (decl) != lk_none
9173       && DECL_LANG_SPECIFIC (decl) == NULL
9174       && !DECL_EXTERN_C_P (decl)
9175       && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
9176     retrofit_lang_decl (decl);
9177
9178   if (TREE_PUBLIC (decl))
9179     {
9180       /* [basic.link]: A name with no linkage (notably, the name of a class
9181          or enumeration declared in a local scope) shall not be used to
9182          declare an entity with linkage.
9183
9184          DR 757 relaxes this restriction for C++0x.  */
9185       if (cxx_dialect < cxx11)
9186         no_linkage_error (decl);
9187     }
9188   else
9189     DECL_INTERFACE_KNOWN (decl) = 1;
9190
9191   if (DECL_NAME (decl)
9192       && MAIN_NAME_P (DECL_NAME (decl))
9193       && scope == global_namespace)
9194     error ("cannot declare %<::main%> to be a global variable");
9195
9196   /* Check that the variable can be safely declared as a concept.
9197      Note that this also forbids explicit specializations.  */
9198   if (conceptp)
9199     {
9200       if (!processing_template_decl)
9201         {
9202           error ("a non-template variable cannot be %<concept%>");
9203           return NULL_TREE;
9204         }
9205       else
9206         DECL_DECLARED_CONCEPT_P (decl) = true;
9207       if (!same_type_ignoring_top_level_qualifiers_p (type, boolean_type_node))
9208         error_at (declspecs->locations[ds_type_spec],
9209                   "concept must have type %<bool%>");
9210     }
9211   else if (flag_concepts
9212            && processing_template_decl > template_class_depth (scope))
9213     {
9214       tree reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
9215       tree ci = build_constraints (reqs, NULL_TREE);
9216       set_constraints (decl, ci);
9217     }
9218
9219   // Handle explicit specializations and instantiations of variable templates.
9220   if (orig_declarator)
9221     decl = check_explicit_specialization (orig_declarator, decl,
9222                                           template_count, conceptp * 8);
9223
9224   return decl != error_mark_node ? decl : NULL_TREE;
9225 }
9226
9227 /* Create and return a canonical pointer to member function type, for
9228    TYPE, which is a POINTER_TYPE to a METHOD_TYPE.  */
9229
9230 tree
9231 build_ptrmemfunc_type (tree type)
9232 {
9233   tree field, fields;
9234   tree t;
9235
9236   if (type == error_mark_node)
9237     return type;
9238
9239   /* Make sure that we always have the unqualified pointer-to-member
9240      type first.  */
9241   if (cp_cv_quals quals = cp_type_quals (type))
9242     {
9243       tree unqual = build_ptrmemfunc_type (TYPE_MAIN_VARIANT (type));
9244       return cp_build_qualified_type (unqual, quals);
9245     }
9246
9247   /* If a canonical type already exists for this type, use it.  We use
9248      this method instead of type_hash_canon, because it only does a
9249      simple equality check on the list of field members.  */
9250
9251   t = TYPE_PTRMEMFUNC_TYPE (type);
9252   if (t)
9253     return t;
9254
9255   t = make_node (RECORD_TYPE);
9256
9257   /* Let the front end know this is a pointer to member function.  */
9258   TYPE_PTRMEMFUNC_FLAG (t) = 1;
9259
9260   field = build_decl (input_location, FIELD_DECL, pfn_identifier, type);
9261   fields = field;
9262
9263   field = build_decl (input_location, FIELD_DECL, delta_identifier, 
9264                       delta_type_node);
9265   DECL_CHAIN (field) = fields;
9266   fields = field;
9267
9268   finish_builtin_struct (t, "__ptrmemfunc_type", fields, ptr_type_node);
9269
9270   /* Zap out the name so that the back end will give us the debugging
9271      information for this anonymous RECORD_TYPE.  */
9272   TYPE_NAME (t) = NULL_TREE;
9273
9274   /* Cache this pointer-to-member type so that we can find it again
9275      later.  */
9276   TYPE_PTRMEMFUNC_TYPE (type) = t;
9277
9278   if (TYPE_STRUCTURAL_EQUALITY_P (type))
9279     SET_TYPE_STRUCTURAL_EQUALITY (t);
9280   else if (TYPE_CANONICAL (type) != type)
9281     TYPE_CANONICAL (t) = build_ptrmemfunc_type (TYPE_CANONICAL (type));
9282
9283   return t;
9284 }
9285
9286 /* Create and return a pointer to data member type.  */
9287
9288 tree
9289 build_ptrmem_type (tree class_type, tree member_type)
9290 {
9291   if (TREE_CODE (member_type) == METHOD_TYPE)
9292     {
9293       cp_cv_quals quals = type_memfn_quals (member_type);
9294       cp_ref_qualifier rqual = type_memfn_rqual (member_type);
9295       member_type = build_memfn_type (member_type, class_type, quals, rqual);
9296       return build_ptrmemfunc_type (build_pointer_type (member_type));
9297     }
9298   else
9299     {
9300       gcc_assert (TREE_CODE (member_type) != FUNCTION_TYPE);
9301       return build_offset_type (class_type, member_type);
9302     }
9303 }
9304
9305 /* DECL is a VAR_DECL defined in-class, whose TYPE is also given.
9306    Check to see that the definition is valid.  Issue appropriate error
9307    messages.  Return 1 if the definition is particularly bad, or 0
9308    otherwise.  */
9309
9310 static int
9311 check_static_variable_definition (tree decl, tree type)
9312 {
9313   /* Avoid redundant diagnostics on out-of-class definitions.  */
9314   if (!current_class_type || !TYPE_BEING_DEFINED (current_class_type))
9315     return 0;
9316   /* Can't check yet if we don't know the type.  */
9317   if (dependent_type_p (type))
9318     return 0;
9319   /* If DECL is declared constexpr, we'll do the appropriate checks
9320      in check_initializer.  Similarly for inline static data members.  */
9321   if (DECL_P (decl)
9322       && (DECL_DECLARED_CONSTEXPR_P (decl)
9323           || DECL_VAR_DECLARED_INLINE_P (decl)))
9324     return 0;
9325   else if (cxx_dialect >= cxx11 && !INTEGRAL_OR_ENUMERATION_TYPE_P (type))
9326     {
9327       if (!COMPLETE_TYPE_P (type))
9328         error_at (DECL_SOURCE_LOCATION (decl),
9329                   "in-class initialization of static data member %q#D of "
9330                   "incomplete type", decl);
9331       else if (literal_type_p (type))
9332         permerror (DECL_SOURCE_LOCATION (decl),
9333                    "%<constexpr%> needed for in-class initialization of "
9334                    "static data member %q#D of non-integral type", decl);
9335       else
9336         error_at (DECL_SOURCE_LOCATION (decl),
9337                   "in-class initialization of static data member %q#D of "
9338                   "non-literal type", decl);
9339       return 1;
9340     }
9341
9342   /* Motion 10 at San Diego: If a static const integral data member is
9343      initialized with an integral constant expression, the initializer
9344      may appear either in the declaration (within the class), or in
9345      the definition, but not both.  If it appears in the class, the
9346      member is a member constant.  The file-scope definition is always
9347      required.  */
9348   if (!ARITHMETIC_TYPE_P (type) && TREE_CODE (type) != ENUMERAL_TYPE)
9349     {
9350       error_at (DECL_SOURCE_LOCATION (decl),
9351                 "invalid in-class initialization of static data member "
9352                 "of non-integral type %qT",
9353                 type);
9354       return 1;
9355     }
9356   else if (!CP_TYPE_CONST_P (type))
9357     error_at (DECL_SOURCE_LOCATION (decl),
9358               "ISO C++ forbids in-class initialization of non-const "
9359               "static member %qD",
9360               decl);
9361   else if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type))
9362     pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
9363              "ISO C++ forbids initialization of member constant "
9364              "%qD of non-integral type %qT", decl, type);
9365
9366   return 0;
9367 }
9368
9369 /* *expr_p is part of the TYPE_SIZE of a variably-sized array.  If any
9370    SAVE_EXPRs in *expr_p wrap expressions with side-effects, break those
9371    expressions out into temporary variables so that walk_tree doesn't
9372    step into them (c++/15764).  */
9373
9374 static tree
9375 stabilize_save_expr_r (tree *expr_p, int *walk_subtrees, void *data)
9376 {
9377   hash_set<tree> *pset = (hash_set<tree> *)data;
9378   tree expr = *expr_p;
9379   if (TREE_CODE (expr) == SAVE_EXPR)
9380     {
9381       tree op = TREE_OPERAND (expr, 0);
9382       cp_walk_tree (&op, stabilize_save_expr_r, data, pset);
9383       if (TREE_SIDE_EFFECTS (op))
9384         TREE_OPERAND (expr, 0) = get_temp_regvar (TREE_TYPE (op), op);
9385       *walk_subtrees = 0;
9386     }
9387   else if (!EXPR_P (expr) || !TREE_SIDE_EFFECTS (expr))
9388     *walk_subtrees = 0;
9389   return NULL;
9390 }
9391
9392 /* Entry point for the above.  */
9393
9394 static void
9395 stabilize_vla_size (tree size)
9396 {
9397   hash_set<tree> pset;
9398   /* Break out any function calls into temporary variables.  */
9399   cp_walk_tree (&size, stabilize_save_expr_r, &pset, &pset);
9400 }
9401
9402 /* Reduce a SIZEOF_EXPR to its value.  */
9403
9404 tree
9405 fold_sizeof_expr (tree t)
9406 {
9407   tree r;
9408   if (SIZEOF_EXPR_TYPE_P (t))
9409     r = cxx_sizeof_or_alignof_type (TREE_TYPE (TREE_OPERAND (t, 0)),
9410                                     SIZEOF_EXPR, false);
9411   else if (TYPE_P (TREE_OPERAND (t, 0)))
9412     r = cxx_sizeof_or_alignof_type (TREE_OPERAND (t, 0), SIZEOF_EXPR,
9413                                     false);
9414   else
9415     r = cxx_sizeof_or_alignof_expr (TREE_OPERAND (t, 0), SIZEOF_EXPR,
9416                                     false);
9417   if (r == error_mark_node)
9418     r = size_one_node;
9419   return r;
9420 }
9421
9422 /* Given the SIZE (i.e., number of elements) in an array, compute
9423    an appropriate index type for the array.  If non-NULL, NAME is
9424    the name of the entity being declared.  */
9425
9426 tree
9427 compute_array_index_type (tree name, tree size, tsubst_flags_t complain)
9428 {
9429   tree itype;
9430   tree osize = size;
9431
9432   if (error_operand_p (size))
9433     return error_mark_node;
9434
9435   if (!type_dependent_expression_p (size))
9436     {
9437       tree type = TREE_TYPE (size);
9438
9439       size = mark_rvalue_use (size);
9440
9441       if (cxx_dialect < cxx11 && TREE_CODE (size) == NOP_EXPR
9442           && TREE_SIDE_EFFECTS (size))
9443         /* In C++98, we mark a non-constant array bound with a magic
9444            NOP_EXPR with TREE_SIDE_EFFECTS; don't fold in that case.  */;
9445       else
9446         {
9447           size = instantiate_non_dependent_expr_sfinae (size, complain);
9448
9449           if (CLASS_TYPE_P (type)
9450               && CLASSTYPE_LITERAL_P (type))
9451             {
9452               size = build_expr_type_conversion (WANT_INT, size, true);
9453               if (!size)
9454                 {
9455                   if (!(complain & tf_error))
9456                     return error_mark_node;
9457                   if (name)
9458                     error ("size of array %qD has non-integral type %qT",
9459                            name, type);
9460                   else
9461                     error ("size of array has non-integral type %qT", type);
9462                   size = integer_one_node;
9463                 }
9464               if (size == error_mark_node)
9465                 return error_mark_node;
9466               type = TREE_TYPE (size);
9467             }
9468
9469           if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
9470             size = maybe_constant_value (size);
9471
9472           if (!TREE_CONSTANT (size))
9473             size = osize;
9474         }
9475
9476       if (error_operand_p (size))
9477         return error_mark_node;
9478
9479       /* The array bound must be an integer type.  */
9480       if (!INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
9481         {
9482           if (!(complain & tf_error))
9483             return error_mark_node;
9484           if (name)
9485             error ("size of array %qD has non-integral type %qT", name, type);
9486           else
9487             error ("size of array has non-integral type %qT", type);
9488           size = integer_one_node;
9489           type = TREE_TYPE (size);
9490         }
9491     }
9492
9493   /* A type is dependent if it is...an array type constructed from any
9494      dependent type or whose size is specified by a constant expression
9495      that is value-dependent.  */
9496   /* We can only call value_dependent_expression_p on integral constant
9497      expressions; treat non-constant expressions as dependent, too.  */
9498   if (processing_template_decl
9499       && (type_dependent_expression_p (size)
9500           || !TREE_CONSTANT (size) || value_dependent_expression_p (size)))
9501     {
9502       /* We cannot do any checking for a SIZE that isn't known to be
9503          constant. Just build the index type and mark that it requires
9504          structural equality checks.  */
9505       itype = build_index_type (build_min (MINUS_EXPR, sizetype,
9506                                            size, size_one_node));
9507       TYPE_DEPENDENT_P (itype) = 1;
9508       TYPE_DEPENDENT_P_VALID (itype) = 1;
9509       SET_TYPE_STRUCTURAL_EQUALITY (itype);
9510       return itype;
9511     }
9512
9513   if (TREE_CODE (size) != INTEGER_CST)
9514     {
9515       tree folded = cp_fully_fold (size);
9516       if (TREE_CODE (folded) == INTEGER_CST)
9517         pedwarn (location_of (size), OPT_Wpedantic,
9518                  "size of array is not an integral constant-expression");
9519       /* Use the folded result for VLAs, too; it will have resolved
9520          SIZEOF_EXPR.  */
9521       size = folded;
9522     }
9523
9524   /* Normally, the array-bound will be a constant.  */
9525   if (TREE_CODE (size) == INTEGER_CST)
9526     {
9527       /* Check to see if the array bound overflowed.  Make that an
9528          error, no matter how generous we're being.  */
9529       constant_expression_error (size);
9530
9531       /* An array must have a positive number of elements.  */
9532       if (tree_int_cst_lt (size, integer_zero_node))
9533         {
9534           if (!(complain & tf_error))
9535             return error_mark_node;
9536           if (name)
9537             error ("size of array %qD is negative", name);
9538           else
9539             error ("size of array is negative");
9540           size = integer_one_node;
9541         }
9542       /* As an extension we allow zero-sized arrays.  */
9543       else if (integer_zerop (size))
9544         {
9545           if (!(complain & tf_error))
9546             /* We must fail if performing argument deduction (as
9547                indicated by the state of complain), so that
9548                another substitution can be found.  */
9549             return error_mark_node;
9550           else if (in_system_header_at (input_location))
9551             /* Allow them in system headers because glibc uses them.  */;
9552           else if (name)
9553             pedwarn (input_location, OPT_Wpedantic, "ISO C++ forbids zero-size array %qD", name);
9554           else
9555             pedwarn (input_location, OPT_Wpedantic, "ISO C++ forbids zero-size array");
9556         }
9557     }
9558   else if (TREE_CONSTANT (size)
9559            /* We don't allow VLAs at non-function scopes, or during
9560               tentative template substitution.  */
9561            || !at_function_scope_p ()
9562            || !(complain & tf_error))
9563     {
9564       if (!(complain & tf_error))
9565         return error_mark_node;
9566       /* `(int) &fn' is not a valid array bound.  */
9567       if (name)
9568         error ("size of array %qD is not an integral constant-expression",
9569                name);
9570       else
9571         error ("size of array is not an integral constant-expression");
9572       size = integer_one_node;
9573     }
9574   else if (pedantic && warn_vla != 0)
9575     {
9576       if (name)
9577         pedwarn (input_location, OPT_Wvla, "ISO C++ forbids variable length array %qD", name);
9578       else
9579         pedwarn (input_location, OPT_Wvla, "ISO C++ forbids variable length array");
9580     }
9581   else if (warn_vla > 0)
9582     {
9583       if (name)
9584         warning (OPT_Wvla, 
9585                  "variable length array %qD is used", name);
9586       else
9587         warning (OPT_Wvla, 
9588                  "variable length array is used");
9589     }
9590
9591   if (processing_template_decl && !TREE_CONSTANT (size))
9592     /* A variable sized array.  */
9593     itype = build_min (MINUS_EXPR, sizetype, size, integer_one_node);
9594   else
9595     {
9596       /* Compute the index of the largest element in the array.  It is
9597          one less than the number of elements in the array.  We save
9598          and restore PROCESSING_TEMPLATE_DECL so that computations in
9599          cp_build_binary_op will be appropriately folded.  */
9600       {
9601         processing_template_decl_sentinel s;
9602         itype = cp_build_binary_op (input_location,
9603                                     MINUS_EXPR,
9604                                     cp_convert (ssizetype, size, complain),
9605                                     cp_convert (ssizetype, integer_one_node,
9606                                                 complain),
9607                                     complain);
9608         itype = maybe_constant_value (itype);
9609       }
9610
9611       if (!TREE_CONSTANT (itype))
9612         {
9613           /* A variable sized array.  */
9614           itype = variable_size (itype);
9615
9616           stabilize_vla_size (itype);
9617
9618           if (sanitize_flags_p (SANITIZE_VLA)
9619               && current_function_decl != NULL_TREE)
9620             {
9621               /* We have to add 1 -- in the ubsan routine we generate
9622                  LE_EXPR rather than LT_EXPR.  */
9623               tree t = fold_build2 (PLUS_EXPR, TREE_TYPE (itype), itype,
9624                                     build_one_cst (TREE_TYPE (itype)));
9625               t = ubsan_instrument_vla (input_location, t);
9626               finish_expr_stmt (t);
9627             }
9628         }
9629       /* Make sure that there was no overflow when creating to a signed
9630          index type.  (For example, on a 32-bit machine, an array with
9631          size 2^32 - 1 is too big.)  */
9632       else if (TREE_CODE (itype) == INTEGER_CST
9633                && TREE_OVERFLOW (itype))
9634         {
9635           if (!(complain & tf_error))
9636             return error_mark_node;
9637           error ("overflow in array dimension");
9638           TREE_OVERFLOW (itype) = 0;
9639         }
9640     }
9641
9642   /* Create and return the appropriate index type.  */
9643   itype = build_index_type (itype);
9644
9645   /* If the index type were dependent, we would have returned early, so
9646      remember that it isn't.  */
9647   TYPE_DEPENDENT_P (itype) = 0;
9648   TYPE_DEPENDENT_P_VALID (itype) = 1;
9649   return itype;
9650 }
9651
9652 /* Returns the scope (if any) in which the entity declared by
9653    DECLARATOR will be located.  If the entity was declared with an
9654    unqualified name, NULL_TREE is returned.  */
9655
9656 tree
9657 get_scope_of_declarator (const cp_declarator *declarator)
9658 {
9659   while (declarator && declarator->kind != cdk_id)
9660     declarator = declarator->declarator;
9661
9662   /* If the declarator-id is a SCOPE_REF, the scope in which the
9663      declaration occurs is the first operand.  */
9664   if (declarator
9665       && declarator->u.id.qualifying_scope)
9666     return declarator->u.id.qualifying_scope;
9667
9668   /* Otherwise, the declarator is not a qualified name; the entity will
9669      be declared in the current scope.  */
9670   return NULL_TREE;
9671 }
9672
9673 /* Returns an ARRAY_TYPE for an array with SIZE elements of the
9674    indicated TYPE.  If non-NULL, NAME is the NAME of the declaration
9675    with this type.  */
9676
9677 static tree
9678 create_array_type_for_decl (tree name, tree type, tree size)
9679 {
9680   tree itype = NULL_TREE;
9681
9682   /* If things have already gone awry, bail now.  */
9683   if (type == error_mark_node || size == error_mark_node)
9684     return error_mark_node;
9685
9686   /* 8.3.4/1: If the type of the identifier of D contains the auto
9687      type-specifier, the program is ill-formed.  */
9688   if (type_uses_auto (type))
9689     {
9690       error ("%qD declared as array of %qT", name, type);
9691       return error_mark_node;
9692     }
9693
9694   /* If there are some types which cannot be array elements,
9695      issue an error-message and return.  */
9696   switch (TREE_CODE (type))
9697     {
9698     case VOID_TYPE:
9699       if (name)
9700         error ("declaration of %qD as array of void", name);
9701       else
9702         error ("creating array of void");
9703       return error_mark_node;
9704
9705     case FUNCTION_TYPE:
9706       if (name)
9707         error ("declaration of %qD as array of functions", name);
9708       else
9709         error ("creating array of functions");
9710       return error_mark_node;
9711
9712     case REFERENCE_TYPE:
9713       if (name)
9714         error ("declaration of %qD as array of references", name);
9715       else
9716         error ("creating array of references");
9717       return error_mark_node;
9718
9719     case METHOD_TYPE:
9720       if (name)
9721         error ("declaration of %qD as array of function members", name);
9722       else
9723         error ("creating array of function members");
9724       return error_mark_node;
9725
9726     default:
9727       break;
9728     }
9729
9730   /* [dcl.array]
9731
9732      The constant expressions that specify the bounds of the arrays
9733      can be omitted only for the first member of the sequence.  */
9734   if (TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type))
9735     {
9736       if (name)
9737         error ("declaration of %qD as multidimensional array must "
9738                "have bounds for all dimensions except the first",
9739                name);
9740       else
9741         error ("multidimensional array must have bounds for all "
9742                "dimensions except the first");
9743
9744       return error_mark_node;
9745     }
9746
9747   /* Figure out the index type for the array.  */
9748   if (size)
9749     itype = compute_array_index_type (name, size, tf_warning_or_error);
9750
9751   /* [dcl.array]
9752      T is called the array element type; this type shall not be [...] an
9753      abstract class type.  */
9754   abstract_virtuals_error (name, type);
9755
9756   return build_cplus_array_type (type, itype);
9757 }
9758
9759 /* Returns the smallest location != UNKNOWN_LOCATION among the
9760    three stored in LOCATIONS[ds_const], LOCATIONS[ds_volatile],
9761    and LOCATIONS[ds_restrict].  */
9762
9763 static location_t
9764 smallest_type_quals_location (int type_quals, const location_t* locations)
9765 {
9766   location_t loc = UNKNOWN_LOCATION;
9767
9768   if (type_quals & TYPE_QUAL_CONST)
9769     loc = locations[ds_const];
9770
9771   if ((type_quals & TYPE_QUAL_VOLATILE)
9772       && (loc == UNKNOWN_LOCATION || locations[ds_volatile] < loc))
9773     loc = locations[ds_volatile];
9774
9775   if ((type_quals & TYPE_QUAL_RESTRICT)
9776       && (loc == UNKNOWN_LOCATION || locations[ds_restrict] < loc))
9777     loc = locations[ds_restrict];
9778
9779   return loc;
9780 }
9781
9782 /* Check that it's OK to declare a function with the indicated TYPE
9783    and TYPE_QUALS.  SFK indicates the kind of special function (if any)
9784    that this function is.  OPTYPE is the type given in a conversion
9785    operator declaration, or the class type for a constructor/destructor.
9786    Returns the actual return type of the function; that may be different
9787    than TYPE if an error occurs, or for certain special functions.  */
9788
9789 static tree
9790 check_special_function_return_type (special_function_kind sfk,
9791                                     tree type,
9792                                     tree optype,
9793                                     int type_quals,
9794                                     const location_t* locations)
9795 {
9796   switch (sfk)
9797     {
9798     case sfk_constructor:
9799       if (type)
9800         error ("return type specification for constructor invalid");
9801       else if (type_quals != TYPE_UNQUALIFIED)
9802         error_at (smallest_type_quals_location (type_quals, locations),
9803                   "qualifiers are not allowed on constructor declaration");
9804
9805       if (targetm.cxx.cdtor_returns_this ())
9806         type = build_pointer_type (optype);
9807       else
9808         type = void_type_node;
9809       break;
9810
9811     case sfk_destructor:
9812       if (type)
9813         error ("return type specification for destructor invalid");
9814       else if (type_quals != TYPE_UNQUALIFIED)
9815         error_at (smallest_type_quals_location (type_quals, locations),
9816                   "qualifiers are not allowed on destructor declaration");
9817
9818       /* We can't use the proper return type here because we run into
9819          problems with ambiguous bases and covariant returns.  */
9820       if (targetm.cxx.cdtor_returns_this ())
9821         type = build_pointer_type (void_type_node);
9822       else
9823         type = void_type_node;
9824       break;
9825
9826     case sfk_conversion:
9827       if (type)
9828         error ("return type specified for %<operator %T%>", optype);
9829       else if (type_quals != TYPE_UNQUALIFIED)
9830         error_at (smallest_type_quals_location (type_quals, locations),
9831                   "qualifiers are not allowed on declaration of "
9832                   "%<operator %T%>", optype);
9833
9834       type = optype;
9835       break;
9836
9837     case sfk_deduction_guide:
9838       if (type)
9839         error ("return type specified for deduction guide");
9840       else if (type_quals != TYPE_UNQUALIFIED)
9841         error_at (smallest_type_quals_location (type_quals, locations),
9842                   "qualifiers are not allowed on declaration of "
9843                   "deduction guide");
9844       if (TREE_CODE (optype) == TEMPLATE_TEMPLATE_PARM)
9845         {
9846           error ("template template parameter %qT in declaration of "
9847                  "deduction guide", optype);
9848           type = error_mark_node;
9849         }
9850       else
9851         type = make_template_placeholder (CLASSTYPE_TI_TEMPLATE (optype));
9852       for (int i = 0; i < ds_last; ++i)
9853         if (i != ds_explicit && locations[i])
9854           error_at (locations[i],
9855                     "decl-specifier in declaration of deduction guide");
9856       break;
9857
9858     default:
9859       gcc_unreachable ();
9860     }
9861
9862   return type;
9863 }
9864
9865 /* A variable or data member (whose unqualified name is IDENTIFIER)
9866    has been declared with the indicated TYPE.  If the TYPE is not
9867    acceptable, issue an error message and return a type to use for
9868    error-recovery purposes.  */
9869
9870 tree
9871 check_var_type (tree identifier, tree type)
9872 {
9873   if (VOID_TYPE_P (type))
9874     {
9875       if (!identifier)
9876         error ("unnamed variable or field declared void");
9877       else if (identifier_p (identifier))
9878         {
9879           gcc_assert (!IDENTIFIER_ANY_OP_P (identifier));
9880           error ("variable or field %qE declared void", identifier);
9881         }
9882       else
9883         error ("variable or field declared void");
9884       type = error_mark_node;
9885     }
9886
9887   return type;
9888 }
9889
9890 /* Handle declaring DECL as an inline variable.  */
9891
9892 static void
9893 mark_inline_variable (tree decl)
9894 {
9895   bool inlinep = true;
9896   if (! toplevel_bindings_p ())
9897     {
9898       error ("%<inline%> specifier invalid for variable "
9899              "%qD declared at block scope", decl);
9900       inlinep = false;
9901     }
9902   else if (cxx_dialect < cxx17)
9903     pedwarn (DECL_SOURCE_LOCATION (decl), 0,
9904              "inline variables are only available "
9905              "with -std=c++17 or -std=gnu++17");
9906   if (inlinep)
9907     {
9908       retrofit_lang_decl (decl);
9909       SET_DECL_VAR_DECLARED_INLINE_P (decl);
9910     }
9911 }
9912
9913
9914 /* Assign a typedef-given name to a class or enumeration type declared
9915    as anonymous at first.  This was split out of grokdeclarator
9916    because it is also used in libcc1.  */
9917
9918 void
9919 name_unnamed_type (tree type, tree decl)
9920 {
9921   gcc_assert (TYPE_UNNAMED_P (type));
9922
9923   /* Replace the anonymous name with the real name everywhere.  */
9924   for (tree t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
9925     {
9926       if (anon_aggrname_p (TYPE_IDENTIFIER (t)))
9927         /* We do not rename the debug info representing the
9928            unnamed tagged type because the standard says in
9929            [dcl.typedef] that the naming applies only for
9930            linkage purposes.  */
9931         /*debug_hooks->set_name (t, decl);*/
9932         TYPE_NAME (t) = decl;
9933     }
9934
9935   if (TYPE_LANG_SPECIFIC (type))
9936     TYPE_WAS_UNNAMED (type) = 1;
9937
9938   /* If this is a typedef within a template class, the nested
9939      type is a (non-primary) template.  The name for the
9940      template needs updating as well.  */
9941   if (TYPE_LANG_SPECIFIC (type) && CLASSTYPE_TEMPLATE_INFO (type))
9942     DECL_NAME (CLASSTYPE_TI_TEMPLATE (type))
9943       = TYPE_IDENTIFIER (type);
9944
9945   /* Adjust linkage now that we aren't unnamed anymore.  */
9946   reset_type_linkage (type);
9947
9948   /* FIXME remangle member functions; member functions of a
9949      type with external linkage have external linkage.  */
9950
9951   /* Check that our job is done, and that it would fail if we
9952      attempted to do it again.  */
9953   gcc_assert (!TYPE_UNNAMED_P (type));
9954 }
9955
9956 /* Given declspecs and a declarator (abstract or otherwise), determine
9957    the name and type of the object declared and construct a DECL node
9958    for it.
9959
9960    DECLSPECS points to the representation of declaration-specifier
9961    sequence that precedes declarator.
9962
9963    DECL_CONTEXT says which syntactic context this declaration is in:
9964      NORMAL for most contexts.  Make a VAR_DECL or FUNCTION_DECL or TYPE_DECL.
9965      FUNCDEF for a function definition.  Like NORMAL but a few different
9966       error messages in each case.  Return value may be zero meaning
9967       this definition is too screwy to try to parse.
9968      MEMFUNCDEF for a function definition.  Like FUNCDEF but prepares to
9969       handle member functions (which have FIELD context).
9970       Return value may be zero meaning this definition is too screwy to
9971       try to parse.
9972      PARM for a parameter declaration (either within a function prototype
9973       or before a function body).  Make a PARM_DECL, or return void_type_node.
9974      TPARM for a template parameter declaration.
9975      CATCHPARM for a parameter declaration before a catch clause.
9976      TYPENAME if for a typename (in a cast or sizeof).
9977       Don't make a DECL node; just return the ..._TYPE node.
9978      FIELD for a struct or union field; make a FIELD_DECL.
9979      BITFIELD for a field with specified width.
9980
9981    INITIALIZED is as for start_decl.
9982
9983    ATTRLIST is a pointer to the list of attributes, which may be NULL
9984    if there are none; *ATTRLIST may be modified if attributes from inside
9985    the declarator should be applied to the declaration.
9986
9987    When this function is called, scoping variables (such as
9988    CURRENT_CLASS_TYPE) should reflect the scope in which the
9989    declaration occurs, not the scope in which the new declaration will
9990    be placed.  For example, on:
9991
9992      void S::f() { ... }
9993
9994    when grokdeclarator is called for `S::f', the CURRENT_CLASS_TYPE
9995    should not be `S'.
9996
9997    Returns a DECL (if a declarator is present), a TYPE (if there is no
9998    declarator, in cases like "struct S;"), or the ERROR_MARK_NODE if an
9999    error occurs. */
10000
10001 tree
10002 grokdeclarator (const cp_declarator *declarator,
10003                 cp_decl_specifier_seq *declspecs,
10004                 enum decl_context decl_context,
10005                 int initialized,
10006                 tree* attrlist)
10007 {
10008   tree type = NULL_TREE;
10009   int longlong = 0;
10010   int explicit_intN = 0;
10011   int virtualp, explicitp, friendp, inlinep, staticp;
10012   int explicit_int = 0;
10013   int explicit_char = 0;
10014   int defaulted_int = 0;
10015
10016   tree typedef_decl = NULL_TREE;
10017   const char *name = NULL;
10018   tree typedef_type = NULL_TREE;
10019   /* True if this declarator is a function definition.  */
10020   bool funcdef_flag = false;
10021   cp_declarator_kind innermost_code = cdk_error;
10022   int bitfield = 0;
10023 #if 0
10024   /* See the code below that used this.  */
10025   tree decl_attr = NULL_TREE;
10026 #endif
10027
10028   /* Keep track of what sort of function is being processed
10029      so that we can warn about default return values, or explicit
10030      return values which do not match prescribed defaults.  */
10031   special_function_kind sfk = sfk_none;
10032
10033   tree dname = NULL_TREE;
10034   tree ctor_return_type = NULL_TREE;
10035   enum overload_flags flags = NO_SPECIAL;
10036   /* cv-qualifiers that apply to the declarator, for a declaration of
10037      a member function.  */
10038   cp_cv_quals memfn_quals = TYPE_UNQUALIFIED;
10039   /* virt-specifiers that apply to the declarator, for a declaration of
10040      a member function.  */
10041   cp_virt_specifiers virt_specifiers = VIRT_SPEC_UNSPECIFIED;
10042   /* ref-qualifier that applies to the declarator, for a declaration of
10043      a member function.  */
10044   cp_ref_qualifier rqual = REF_QUAL_NONE;
10045   /* cv-qualifiers that apply to the type specified by the DECLSPECS.  */
10046   int type_quals = TYPE_UNQUALIFIED;
10047   tree raises = NULL_TREE;
10048   int template_count = 0;
10049   tree returned_attrs = NULL_TREE;
10050   tree parms = NULL_TREE;
10051   const cp_declarator *id_declarator;
10052   /* The unqualified name of the declarator; either an
10053      IDENTIFIER_NODE, BIT_NOT_EXPR, or TEMPLATE_ID_EXPR.  */
10054   tree unqualified_id;
10055   /* The class type, if any, in which this entity is located,
10056      or NULL_TREE if none.  Note that this value may be different from
10057      the current class type; for example if an attempt is made to declare
10058      "A::f" inside "B", this value will be "A".  */
10059   tree ctype = current_class_type;
10060   /* The NAMESPACE_DECL for the namespace in which this entity is
10061      located.  If an unqualified name is used to declare the entity,
10062      this value will be NULL_TREE, even if the entity is located at
10063      namespace scope.  */
10064   tree in_namespace = NULL_TREE;
10065   cp_storage_class storage_class;
10066   bool unsigned_p, signed_p, short_p, long_p, thread_p;
10067   bool type_was_error_mark_node = false;
10068   bool parameter_pack_p = declarator ? declarator->parameter_pack_p : false;
10069   bool template_type_arg = false;
10070   bool template_parm_flag = false;
10071   bool typedef_p = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
10072   bool constexpr_p = decl_spec_seq_has_spec_p (declspecs, ds_constexpr);
10073   bool late_return_type_p = false;
10074   bool array_parameter_p = false;
10075   source_location saved_loc = input_location;
10076   tree reqs = NULL_TREE;
10077
10078   signed_p = decl_spec_seq_has_spec_p (declspecs, ds_signed);
10079   unsigned_p = decl_spec_seq_has_spec_p (declspecs, ds_unsigned);
10080   short_p = decl_spec_seq_has_spec_p (declspecs, ds_short);
10081   long_p = decl_spec_seq_has_spec_p (declspecs, ds_long);
10082   longlong = decl_spec_seq_has_spec_p (declspecs, ds_long_long);
10083   explicit_intN = declspecs->explicit_intN_p;
10084   thread_p = decl_spec_seq_has_spec_p (declspecs, ds_thread);
10085
10086   // Was concept_p specified? Note that ds_concept
10087   // implies ds_constexpr!
10088   bool concept_p = decl_spec_seq_has_spec_p (declspecs, ds_concept);
10089   if (concept_p)
10090     constexpr_p = true;
10091
10092   if (decl_spec_seq_has_spec_p (declspecs, ds_const))
10093     type_quals |= TYPE_QUAL_CONST;
10094   if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
10095     type_quals |= TYPE_QUAL_VOLATILE;
10096   if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
10097     type_quals |= TYPE_QUAL_RESTRICT;
10098
10099   if (decl_context == FUNCDEF)
10100     funcdef_flag = true, decl_context = NORMAL;
10101   else if (decl_context == MEMFUNCDEF)
10102     funcdef_flag = true, decl_context = FIELD;
10103   else if (decl_context == BITFIELD)
10104     bitfield = 1, decl_context = FIELD;
10105   else if (decl_context == TEMPLATE_TYPE_ARG)
10106     template_type_arg = true, decl_context = TYPENAME;
10107   else if (decl_context == TPARM)
10108     template_parm_flag = true, decl_context = PARM;
10109
10110   if (initialized > 1)
10111     funcdef_flag = true;
10112
10113   location_t typespec_loc = smallest_type_quals_location (type_quals,
10114                                                       declspecs->locations);
10115   if (typespec_loc == UNKNOWN_LOCATION)
10116     typespec_loc = declspecs->locations[ds_type_spec];
10117   if (typespec_loc == UNKNOWN_LOCATION)
10118     typespec_loc = input_location;
10119
10120   /* Look inside a declarator for the name being declared
10121      and get it as a string, for an error message.  */
10122   for (id_declarator = declarator;
10123        id_declarator;
10124        id_declarator = id_declarator->declarator)
10125     {
10126       if (id_declarator->kind != cdk_id)
10127         innermost_code = id_declarator->kind;
10128
10129       switch (id_declarator->kind)
10130         {
10131         case cdk_function:
10132           if (id_declarator->declarator
10133               && id_declarator->declarator->kind == cdk_id)
10134             {
10135               sfk = id_declarator->declarator->u.id.sfk;
10136               if (sfk == sfk_destructor)
10137                 flags = DTOR_FLAG;
10138             }
10139           break;
10140
10141         case cdk_id:
10142           {
10143             tree qualifying_scope = id_declarator->u.id.qualifying_scope;
10144             tree decl = id_declarator->u.id.unqualified_name;
10145             if (!decl)
10146               break;
10147             if (qualifying_scope)
10148               {
10149                 if (at_function_scope_p ())
10150                   {
10151                     /* [dcl.meaning] 
10152
10153                        A declarator-id shall not be qualified except
10154                        for ... 
10155
10156                        None of the cases are permitted in block
10157                        scope.  */
10158                     if (qualifying_scope == global_namespace)
10159                       error ("invalid use of qualified-name %<::%D%>",
10160                              decl);
10161                     else if (TYPE_P (qualifying_scope))
10162                       error ("invalid use of qualified-name %<%T::%D%>",
10163                              qualifying_scope, decl);
10164                     else 
10165                       error ("invalid use of qualified-name %<%D::%D%>",
10166                              qualifying_scope, decl);
10167                     return error_mark_node;
10168                   }
10169                 else if (TYPE_P (qualifying_scope))
10170                   {
10171                     ctype = qualifying_scope;
10172                     if (!MAYBE_CLASS_TYPE_P (ctype))
10173                       {
10174                         error ("%q#T is not a class or a namespace", ctype);
10175                         ctype = NULL_TREE;
10176                       }
10177                     else if (innermost_code != cdk_function
10178                              && current_class_type
10179                              && !uniquely_derived_from_p (ctype,
10180                                                           current_class_type))
10181                       {
10182                         error ("invalid use of qualified-name %<%T::%D%>",
10183                                qualifying_scope, decl);
10184                         return error_mark_node;
10185                       }
10186                   }
10187                 else if (TREE_CODE (qualifying_scope) == NAMESPACE_DECL)
10188                   in_namespace = qualifying_scope;
10189               }
10190             switch (TREE_CODE (decl))
10191               {
10192               case BIT_NOT_EXPR:
10193                 {
10194                   if (innermost_code != cdk_function)
10195                     {
10196                       error ("declaration of %qD as non-function", decl);
10197                       return error_mark_node;
10198                     }
10199                   else if (!qualifying_scope
10200                            && !(current_class_type && at_class_scope_p ()))
10201                     {
10202                       error ("declaration of %qD as non-member", decl);
10203                       return error_mark_node;
10204                     }
10205
10206                   tree type = TREE_OPERAND (decl, 0);
10207                   if (TYPE_P (type))
10208                     type = constructor_name (type);
10209                   name = identifier_to_locale (IDENTIFIER_POINTER (type));
10210                   dname = decl;
10211                 }
10212                 break;
10213
10214               case TEMPLATE_ID_EXPR:
10215                 {
10216                   tree fns = TREE_OPERAND (decl, 0);
10217
10218                   dname = fns;
10219                   if (!identifier_p (dname))
10220                     dname = OVL_NAME (dname);
10221                 }
10222                 /* Fall through.  */
10223
10224               case IDENTIFIER_NODE:
10225                 if (identifier_p (decl))
10226                   dname = decl;
10227
10228                 if (IDENTIFIER_KEYWORD_P (dname))
10229                   {
10230                     error ("declarator-id missing; using reserved word %qD",
10231                            dname);
10232                     name = identifier_to_locale (IDENTIFIER_POINTER (dname));
10233                   }
10234                 else if (!IDENTIFIER_CONV_OP_P (dname))
10235                   name = identifier_to_locale (IDENTIFIER_POINTER (dname));
10236                 else
10237                   {
10238                     gcc_assert (flags == NO_SPECIAL);
10239                     flags = TYPENAME_FLAG;
10240                     sfk = sfk_conversion;
10241                     tree glob = get_global_binding (dname);
10242                     if (glob && TREE_CODE (glob) == TYPE_DECL)
10243                       name = identifier_to_locale (IDENTIFIER_POINTER (dname));
10244                     else
10245                       name = "<invalid operator>";
10246                   }
10247                 break;
10248
10249               default:
10250                 gcc_unreachable ();
10251               }
10252             break;
10253           }
10254
10255         case cdk_array:
10256         case cdk_pointer:
10257         case cdk_reference:
10258         case cdk_ptrmem:
10259           break;
10260
10261         case cdk_decomp:
10262           name = "structured binding";
10263           break;
10264
10265         case cdk_error:
10266           return error_mark_node;
10267
10268         default:
10269           gcc_unreachable ();
10270         }
10271       if (id_declarator->kind == cdk_id)
10272         break;
10273     }
10274
10275   /* [dcl.fct.edf]
10276
10277      The declarator in a function-definition shall have the form
10278      D1 ( parameter-declaration-clause) ...  */
10279   if (funcdef_flag && innermost_code != cdk_function)
10280     {
10281       error ("function definition does not declare parameters");
10282       return error_mark_node;
10283     }
10284
10285   if (flags == TYPENAME_FLAG
10286       && innermost_code != cdk_function
10287       && ! (ctype && !declspecs->any_specifiers_p))
10288     {
10289       error ("declaration of %qD as non-function", dname);
10290       return error_mark_node;
10291     }
10292
10293   if (dname && identifier_p (dname))
10294     {
10295       if (UDLIT_OPER_P (dname)
10296           && innermost_code != cdk_function)
10297         {
10298           error ("declaration of %qD as non-function", dname);
10299           return error_mark_node;
10300         }
10301
10302       if (IDENTIFIER_ANY_OP_P (dname))
10303         {
10304           if (typedef_p)
10305             {
10306               error ("declaration of %qD as %<typedef%>", dname);
10307               return error_mark_node;
10308             }
10309           else if (decl_context == PARM || decl_context == CATCHPARM)
10310             {
10311               error ("declaration of %qD as parameter", dname);
10312               return error_mark_node;
10313             }
10314         }
10315     }
10316
10317   /* Anything declared one level down from the top level
10318      must be one of the parameters of a function
10319      (because the body is at least two levels down).  */
10320
10321   /* This heuristic cannot be applied to C++ nodes! Fixed, however,
10322      by not allowing C++ class definitions to specify their parameters
10323      with xdecls (must be spec.d in the parmlist).
10324
10325      Since we now wait to push a class scope until we are sure that
10326      we are in a legitimate method context, we must set oldcname
10327      explicitly (since current_class_name is not yet alive).
10328
10329      We also want to avoid calling this a PARM if it is in a namespace.  */
10330
10331   if (decl_context == NORMAL && !toplevel_bindings_p ())
10332     {
10333       cp_binding_level *b = current_binding_level;
10334       current_binding_level = b->level_chain;
10335       if (current_binding_level != 0 && toplevel_bindings_p ())
10336         decl_context = PARM;
10337       current_binding_level = b;
10338     }
10339
10340   if (name == NULL)
10341     name = decl_context == PARM ? "parameter" : "type name";
10342
10343   if (concept_p && typedef_p)
10344     {
10345       error ("%<concept%> cannot appear in a typedef declaration");
10346       return error_mark_node;
10347     }
10348
10349   if (constexpr_p && typedef_p)
10350     {
10351       error ("%<constexpr%> cannot appear in a typedef declaration");
10352       return error_mark_node;
10353     }
10354
10355   /* If there were multiple types specified in the decl-specifier-seq,
10356      issue an error message.  */
10357   if (declspecs->multiple_types_p)
10358     {
10359       error ("two or more data types in declaration of %qs", name);
10360       return error_mark_node;
10361     }
10362
10363   if (declspecs->conflicting_specifiers_p)
10364     {
10365       error ("conflicting specifiers in declaration of %qs", name);
10366       return error_mark_node;
10367     }
10368
10369   /* Extract the basic type from the decl-specifier-seq.  */
10370   type = declspecs->type;
10371   if (type == error_mark_node)
10372     {
10373       type = NULL_TREE;
10374       type_was_error_mark_node = true;
10375     }
10376   /* If the entire declaration is itself tagged as deprecated then
10377      suppress reports of deprecated items.  */
10378   if (type && TREE_DEPRECATED (type)
10379       && deprecated_state != DEPRECATED_SUPPRESS)
10380     warn_deprecated_use (type, NULL_TREE);
10381   if (type && TREE_CODE (type) == TYPE_DECL)
10382     {
10383       typedef_decl = type;
10384       type = TREE_TYPE (typedef_decl);
10385       if (TREE_DEPRECATED (type)
10386           && DECL_ARTIFICIAL (typedef_decl)
10387           && deprecated_state != DEPRECATED_SUPPRESS)
10388         warn_deprecated_use (type, NULL_TREE);
10389     }
10390   /* No type at all: default to `int', and set DEFAULTED_INT
10391      because it was not a user-defined typedef.  */
10392   if (type == NULL_TREE)
10393     {
10394       if (signed_p || unsigned_p || long_p || short_p)
10395         {
10396           /* These imply 'int'.  */
10397           type = integer_type_node;
10398           defaulted_int = 1;
10399         }
10400       /* If we just have "complex", it is equivalent to "complex double".  */
10401       else if (!longlong && !explicit_intN
10402                && decl_spec_seq_has_spec_p (declspecs, ds_complex))
10403         {
10404           type = double_type_node;
10405           pedwarn (declspecs->locations[ds_complex], OPT_Wpedantic,
10406                    "ISO C++ does not support plain %<complex%> meaning "
10407                    "%<double complex%>");
10408         }
10409     }
10410   /* Gather flags.  */
10411   explicit_int = declspecs->explicit_int_p;
10412   explicit_char = declspecs->explicit_char_p;
10413
10414 #if 0
10415   /* See the code below that used this.  */
10416   if (typedef_decl)
10417     decl_attr = DECL_ATTRIBUTES (typedef_decl);
10418 #endif
10419   typedef_type = type;
10420
10421   if (sfk == sfk_conversion || sfk == sfk_deduction_guide)
10422     ctor_return_type = TREE_TYPE (dname);
10423   else
10424     ctor_return_type = ctype;
10425
10426   if (sfk != sfk_none)
10427     {
10428       type = check_special_function_return_type (sfk, type,
10429                                                  ctor_return_type,
10430                                                  type_quals,
10431                                                  declspecs->locations);
10432       type_quals = TYPE_UNQUALIFIED;
10433     }
10434   else if (type == NULL_TREE)
10435     {
10436       int is_main;
10437
10438       explicit_int = -1;
10439
10440       /* We handle `main' specially here, because 'main () { }' is so
10441          common.  With no options, it is allowed.  With -Wreturn-type,
10442          it is a warning.  It is only an error with -pedantic-errors.  */
10443       is_main = (funcdef_flag
10444                  && dname && identifier_p (dname)
10445                  && MAIN_NAME_P (dname)
10446                  && ctype == NULL_TREE
10447                  && in_namespace == NULL_TREE
10448                  && current_namespace == global_namespace);
10449
10450       if (type_was_error_mark_node)
10451         /* We've already issued an error, don't complain more.  */;
10452       else if (in_system_header_at (input_location) || flag_ms_extensions)
10453         /* Allow it, sigh.  */;
10454       else if (! is_main)
10455         permerror (input_location, "ISO C++ forbids declaration of %qs with no type", name);
10456       else if (pedantic)
10457         pedwarn (input_location, OPT_Wpedantic,
10458                  "ISO C++ forbids declaration of %qs with no type", name);
10459       else
10460         warning (OPT_Wreturn_type,
10461                  "ISO C++ forbids declaration of %qs with no type", name);
10462
10463       if (type_was_error_mark_node && template_parm_flag)
10464         /* FIXME we should be able to propagate the error_mark_node as is
10465            for other contexts too.  */
10466         type = error_mark_node;
10467       else
10468         type = integer_type_node;
10469     }
10470
10471   ctype = NULL_TREE;
10472
10473   if (explicit_intN)
10474     {
10475       if (! int_n_enabled_p[declspecs->int_n_idx])
10476         {
10477           error ("%<__int%d%> is not supported by this target",
10478                  int_n_data[declspecs->int_n_idx].bitsize);
10479           explicit_intN = false;
10480         }
10481       else if (pedantic && ! in_system_header_at (input_location))
10482         pedwarn (input_location, OPT_Wpedantic,
10483                  "ISO C++ does not support %<__int%d%> for %qs",
10484                  int_n_data[declspecs->int_n_idx].bitsize, name);
10485     }
10486
10487   /* Now process the modifiers that were specified
10488      and check for invalid combinations.  */
10489
10490   /* Long double is a special combination.  */
10491   if (long_p && !longlong && TYPE_MAIN_VARIANT (type) == double_type_node)
10492     {
10493       long_p = false;
10494       type = cp_build_qualified_type (long_double_type_node,
10495                                       cp_type_quals (type));
10496     }
10497
10498   /* Check all other uses of type modifiers.  */
10499
10500   if (unsigned_p || signed_p || long_p || short_p)
10501     {
10502       int ok = 0;
10503
10504       if ((signed_p || unsigned_p) && TREE_CODE (type) != INTEGER_TYPE)
10505         error ("%<signed%> or %<unsigned%> invalid for %qs", name);
10506       else if (signed_p && unsigned_p)
10507         error ("%<signed%> and %<unsigned%> specified together for %qs", name);
10508       else if (longlong && TREE_CODE (type) != INTEGER_TYPE)
10509         error ("%<long long%> invalid for %qs", name);
10510       else if (long_p && TREE_CODE (type) == REAL_TYPE)
10511         error ("%<long%> invalid for %qs", name);
10512       else if (short_p && TREE_CODE (type) == REAL_TYPE)
10513         error ("%<short%> invalid for %qs", name);
10514       else if ((long_p || short_p) && TREE_CODE (type) != INTEGER_TYPE)
10515         error ("%<long%> or %<short%> invalid for %qs", name);
10516       else if ((long_p || short_p || explicit_char || explicit_int) && explicit_intN)
10517         error ("%<long%>, %<int%>, %<short%>, or %<char%> invalid for %qs", name);
10518       else if ((long_p || short_p) && explicit_char)
10519         error ("%<long%> or %<short%> specified with char for %qs", name);
10520       else if (long_p && short_p)
10521         error ("%<long%> and %<short%> specified together for %qs", name);
10522       else if (type == char16_type_node || type == char32_type_node)
10523         {
10524           if (signed_p || unsigned_p)
10525             error ("%<signed%> or %<unsigned%> invalid for %qs", name);
10526           else if (short_p || long_p)
10527             error ("%<short%> or %<long%> invalid for %qs", name);
10528         }
10529       else
10530         {
10531           ok = 1;
10532           if (!explicit_int && !defaulted_int && !explicit_char && !explicit_intN && pedantic)
10533             {
10534               pedwarn (input_location, OPT_Wpedantic, 
10535                        "long, short, signed or unsigned used invalidly for %qs",
10536                        name);
10537               if (flag_pedantic_errors)
10538                 ok = 0;
10539             }
10540         }
10541
10542       /* Discard the type modifiers if they are invalid.  */
10543       if (! ok)
10544         {
10545           unsigned_p = false;
10546           signed_p = false;
10547           long_p = false;
10548           short_p = false;
10549           longlong = 0;
10550         }
10551     }
10552
10553   /* Decide whether an integer type is signed or not.
10554      Optionally treat bitfields as signed by default.  */
10555   if (unsigned_p
10556       /* [class.bit]
10557
10558          It is implementation-defined whether a plain (neither
10559          explicitly signed or unsigned) char, short, int, or long
10560          bit-field is signed or unsigned.
10561
10562          Naturally, we extend this to long long as well.  Note that
10563          this does not include wchar_t.  */
10564       || (bitfield && !flag_signed_bitfields
10565           && !signed_p
10566           /* A typedef for plain `int' without `signed' can be
10567              controlled just like plain `int', but a typedef for
10568              `signed int' cannot be so controlled.  */
10569           && !(typedef_decl
10570                && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl))
10571           && TREE_CODE (type) == INTEGER_TYPE
10572           && !same_type_p (TYPE_MAIN_VARIANT (type), wchar_type_node)))
10573     {
10574       if (explicit_intN)
10575         type = int_n_trees[declspecs->int_n_idx].unsigned_type;
10576       else if (longlong)
10577         type = long_long_unsigned_type_node;
10578       else if (long_p)
10579         type = long_unsigned_type_node;
10580       else if (short_p)
10581         type = short_unsigned_type_node;
10582       else if (type == char_type_node)
10583         type = unsigned_char_type_node;
10584       else if (typedef_decl)
10585         type = unsigned_type_for (type);
10586       else
10587         type = unsigned_type_node;
10588     }
10589   else if (signed_p && type == char_type_node)
10590     type = signed_char_type_node;
10591   else if (explicit_intN)
10592     type = int_n_trees[declspecs->int_n_idx].signed_type;
10593   else if (longlong)
10594     type = long_long_integer_type_node;
10595   else if (long_p)
10596     type = long_integer_type_node;
10597   else if (short_p)
10598     type = short_integer_type_node;
10599
10600   if (decl_spec_seq_has_spec_p (declspecs, ds_complex))
10601     {
10602       if (TREE_CODE (type) != INTEGER_TYPE && TREE_CODE (type) != REAL_TYPE)
10603         error ("complex invalid for %qs", name);
10604       /* If a modifier is specified, the resulting complex is the complex
10605          form of TYPE.  E.g, "complex short" is "complex short int".  */
10606       else if (type == integer_type_node)
10607         type = complex_integer_type_node;
10608       else if (type == float_type_node)
10609         type = complex_float_type_node;
10610       else if (type == double_type_node)
10611         type = complex_double_type_node;
10612       else if (type == long_double_type_node)
10613         type = complex_long_double_type_node;
10614       else
10615         type = build_complex_type (type);
10616     }
10617
10618   /* If we're using the injected-class-name to form a compound type or a
10619      declaration, replace it with the underlying class so we don't get
10620      redundant typedefs in the debug output.  But if we are returning the
10621      type unchanged, leave it alone so that it's available to
10622      maybe_get_template_decl_from_type_decl.  */
10623   if (CLASS_TYPE_P (type)
10624       && DECL_SELF_REFERENCE_P (TYPE_NAME (type))
10625       && type == TREE_TYPE (TYPE_NAME (type))
10626       && (declarator || type_quals))
10627     type = DECL_ORIGINAL_TYPE (TYPE_NAME (type));
10628
10629   type_quals |= cp_type_quals (type);
10630   type = cp_build_qualified_type_real
10631     (type, type_quals, ((((typedef_decl && !DECL_ARTIFICIAL (typedef_decl))
10632                           || declspecs->decltype_p)
10633                          ? tf_ignore_bad_quals : 0) | tf_warning_or_error));
10634   /* We might have ignored or rejected some of the qualifiers.  */
10635   type_quals = cp_type_quals (type);
10636
10637   if (cxx_dialect >= cxx17 && type && is_auto (type)
10638       && innermost_code != cdk_function
10639       && id_declarator && declarator != id_declarator)
10640     if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (type))
10641     {
10642       error_at (typespec_loc, "template placeholder type %qT must be followed "
10643                 "by a simple declarator-id", type);
10644       inform (DECL_SOURCE_LOCATION (tmpl), "%qD declared here", tmpl);
10645     }
10646
10647   staticp = 0;
10648   inlinep = decl_spec_seq_has_spec_p (declspecs, ds_inline);
10649   virtualp =  decl_spec_seq_has_spec_p (declspecs, ds_virtual);
10650   explicitp = decl_spec_seq_has_spec_p (declspecs, ds_explicit);
10651
10652   storage_class = declspecs->storage_class;
10653   if (storage_class == sc_static)
10654     staticp = 1 + (decl_context == FIELD);
10655
10656   if (virtualp)
10657     {
10658       if (staticp == 2)
10659         {
10660           error ("member %qD cannot be declared both %<virtual%> "
10661                  "and %<static%>", dname);
10662           storage_class = sc_none;
10663           staticp = 0;
10664         }
10665       if (constexpr_p)
10666         error ("member %qD cannot be declared both %<virtual%> "
10667                "and %<constexpr%>", dname);
10668     }
10669   friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
10670
10671   /* Issue errors about use of storage classes for parameters.  */
10672   if (decl_context == PARM)
10673     {
10674       if (typedef_p)
10675         {
10676           error ("typedef declaration invalid in parameter declaration");
10677           return error_mark_node;
10678         }
10679       else if (template_parm_flag && storage_class != sc_none)
10680         {
10681           error ("storage class specified for template parameter %qs", name);
10682           return error_mark_node;
10683         }
10684       else if (storage_class == sc_static
10685                || storage_class == sc_extern
10686                || thread_p)
10687         error ("storage class specifiers invalid in parameter declarations");
10688
10689       /* Function parameters cannot be concept. */
10690       if (concept_p)
10691           error ("a parameter cannot be declared %<concept%>");
10692       /* Function parameters cannot be constexpr.  If we saw one, moan
10693          and pretend it wasn't there.  */
10694       else if (constexpr_p)
10695         {
10696           error ("a parameter cannot be declared %<constexpr%>");
10697           constexpr_p = 0;
10698         }
10699     }
10700
10701   /* Give error if `virtual' is used outside of class declaration.  */
10702   if (virtualp
10703       && (current_class_name == NULL_TREE || decl_context != FIELD))
10704     {
10705       error_at (declspecs->locations[ds_virtual],
10706                 "%<virtual%> outside class declaration");
10707       virtualp = 0;
10708     }
10709
10710   if (innermost_code == cdk_decomp)
10711     {
10712       location_t loc = (declarator->kind == cdk_reference
10713                         ? declarator->declarator->id_loc : declarator->id_loc);
10714       if (inlinep)
10715         error_at (declspecs->locations[ds_inline],
10716                   "structured binding declaration cannot be %<inline%>");
10717       if (typedef_p)
10718         error_at (declspecs->locations[ds_typedef],
10719                   "structured binding declaration cannot be %<typedef%>");
10720       if (constexpr_p)
10721         error_at (declspecs->locations[ds_constexpr], "structured "
10722                   "binding declaration cannot be %<constexpr%>");
10723       if (thread_p)
10724         error_at (declspecs->locations[ds_thread],
10725                   "structured binding declaration cannot be %qs",
10726                   declspecs->gnu_thread_keyword_p
10727                   ? "__thread" : "thread_local");
10728       if (concept_p)
10729         error_at (declspecs->locations[ds_concept],
10730                   "structured binding declaration cannot be %<concept%>");
10731       switch (storage_class)
10732         {
10733         case sc_none:
10734           break;
10735         case sc_register:
10736           error_at (loc, "structured binding declaration cannot be "
10737                     "%<register%>");
10738           break;
10739         case sc_static:
10740           error_at (loc, "structured binding declaration cannot be "
10741                     "%<static%>");
10742           break;
10743         case sc_extern:
10744           error_at (loc, "structured binding declaration cannot be "
10745                     "%<extern%>");
10746           break;
10747         case sc_mutable:
10748           error_at (loc, "structured binding declaration cannot be "
10749                     "%<mutable%>");
10750           break;
10751         case sc_auto:
10752           error_at (loc, "structured binding declaration cannot be "
10753                     "C++98 %<auto%>");
10754           break;
10755         default:
10756           gcc_unreachable ();
10757         }
10758       if (TREE_CODE (type) != TEMPLATE_TYPE_PARM
10759           || TYPE_IDENTIFIER (type) != auto_identifier)
10760         {
10761           if (type != error_mark_node)
10762             {
10763               error_at (loc, "structured binding declaration cannot have "
10764                         "type %qT", type);
10765               inform (loc,
10766                       "type must be cv-qualified %<auto%> or reference to "
10767                       "cv-qualified %<auto%>");
10768             }
10769           type = build_qualified_type (make_auto (), type_quals);
10770           declspecs->type = type;
10771         }
10772       inlinep = 0;
10773       typedef_p = 0;
10774       constexpr_p = 0;
10775       thread_p = 0;
10776       concept_p = 0;
10777       storage_class = sc_none;
10778       staticp = 0;
10779       declspecs->storage_class = sc_none;
10780       declspecs->locations[ds_thread] = UNKNOWN_LOCATION;
10781     }
10782
10783   /* Static anonymous unions are dealt with here.  */
10784   if (staticp && decl_context == TYPENAME
10785       && declspecs->type
10786       && ANON_AGGR_TYPE_P (declspecs->type))
10787     decl_context = FIELD;
10788
10789   /* Warn about storage classes that are invalid for certain
10790      kinds of declarations (parameters, typenames, etc.).  */
10791   if (thread_p
10792       && ((storage_class
10793            && storage_class != sc_extern
10794            && storage_class != sc_static)
10795           || typedef_p))
10796     {
10797       error ("multiple storage classes in declaration of %qs", name);
10798       thread_p = false;
10799     }
10800   if (decl_context != NORMAL
10801       && ((storage_class != sc_none
10802            && storage_class != sc_mutable)
10803           || thread_p))
10804     {
10805       if ((decl_context == PARM || decl_context == CATCHPARM)
10806           && (storage_class == sc_register
10807               || storage_class == sc_auto))
10808         ;
10809       else if (typedef_p)
10810         ;
10811       else if (decl_context == FIELD
10812                /* C++ allows static class elements.  */
10813                && storage_class == sc_static)
10814         /* C++ also allows inlines and signed and unsigned elements,
10815            but in those cases we don't come in here.  */
10816         ;
10817       else
10818         {
10819           if (decl_context == FIELD)
10820             error ("storage class specified for %qs", name);
10821           else
10822             {
10823               if (decl_context == PARM || decl_context == CATCHPARM)
10824                 error ("storage class specified for parameter %qs", name);
10825               else
10826                 error ("storage class specified for typename");
10827             }
10828           if (storage_class == sc_register
10829               || storage_class == sc_auto
10830               || storage_class == sc_extern
10831               || thread_p)
10832             storage_class = sc_none;
10833         }
10834     }
10835   else if (storage_class == sc_extern && funcdef_flag
10836            && ! toplevel_bindings_p ())
10837     error ("nested function %qs declared %<extern%>", name);
10838   else if (toplevel_bindings_p ())
10839     {
10840       if (storage_class == sc_auto)
10841         error ("top-level declaration of %qs specifies %<auto%>", name);
10842     }
10843   else if (thread_p
10844            && storage_class != sc_extern
10845            && storage_class != sc_static)
10846     {
10847       if (declspecs->gnu_thread_keyword_p)
10848         pedwarn (input_location, 0, "function-scope %qs implicitly auto and "
10849                  "declared %<__thread%>", name);
10850
10851       /* When thread_local is applied to a variable of block scope the
10852          storage-class-specifier static is implied if it does not appear
10853          explicitly.  */
10854       storage_class = declspecs->storage_class = sc_static;
10855       staticp = 1;
10856     }
10857
10858   if (storage_class && friendp)
10859     {
10860       error ("storage class specifiers invalid in friend function declarations");
10861       storage_class = sc_none;
10862       staticp = 0;
10863     }
10864
10865   if (!id_declarator)
10866     unqualified_id = NULL_TREE;
10867   else
10868     {
10869       unqualified_id = id_declarator->u.id.unqualified_name;
10870       switch (TREE_CODE (unqualified_id))
10871         {
10872         case BIT_NOT_EXPR:
10873           unqualified_id = TREE_OPERAND (unqualified_id, 0);
10874           if (TYPE_P (unqualified_id))
10875             unqualified_id = constructor_name (unqualified_id);
10876           break;
10877
10878         case IDENTIFIER_NODE:
10879         case TEMPLATE_ID_EXPR:
10880           break;
10881
10882         default:
10883           gcc_unreachable ();
10884         }
10885     }
10886
10887   if (declspecs->std_attributes)
10888     {
10889       /* Apply the c++11 attributes to the type preceding them.  */
10890       input_location = declspecs->locations[ds_std_attribute];
10891       decl_attributes (&type, declspecs->std_attributes, 0);
10892       input_location = saved_loc;
10893     }
10894
10895   /* Determine the type of the entity declared by recurring on the
10896      declarator.  */
10897   for (; declarator; declarator = declarator->declarator)
10898     {
10899       const cp_declarator *inner_declarator;
10900       tree attrs;
10901
10902       if (type == error_mark_node)
10903         return error_mark_node;
10904
10905       attrs = declarator->attributes;
10906       if (attrs)
10907         {
10908           int attr_flags;
10909
10910           attr_flags = 0;
10911           if (declarator == NULL || declarator->kind == cdk_id)
10912             attr_flags |= (int) ATTR_FLAG_DECL_NEXT;
10913           if (declarator->kind == cdk_function)
10914             attr_flags |= (int) ATTR_FLAG_FUNCTION_NEXT;
10915           if (declarator->kind == cdk_array)
10916             attr_flags |= (int) ATTR_FLAG_ARRAY_NEXT;
10917           returned_attrs = decl_attributes (&type,
10918                                             chainon (returned_attrs, attrs),
10919                                             attr_flags);
10920         }
10921
10922       inner_declarator = declarator->declarator;
10923
10924       /* We don't want to warn in parameter context because we don't
10925          yet know if the parse will succeed, and this might turn out
10926          to be a constructor call.  */
10927       if (decl_context != PARM
10928           && decl_context != TYPENAME
10929           && !typedef_p
10930           && declarator->parenthesized != UNKNOWN_LOCATION
10931           /* If the type is class-like and the inner name used a
10932              global namespace qualifier, we need the parens.
10933              Unfortunately all we can tell is whether a qualified name
10934              was used or not.  */
10935           && !(inner_declarator
10936                && inner_declarator->kind == cdk_id
10937                && inner_declarator->u.id.qualifying_scope
10938                && (MAYBE_CLASS_TYPE_P (type)
10939                    || TREE_CODE (type) == ENUMERAL_TYPE)))
10940         warning_at (declarator->parenthesized, OPT_Wparentheses,
10941                     "unnecessary parentheses in declaration of %qs", name);
10942       if (declarator->kind == cdk_id || declarator->kind == cdk_decomp)
10943         break;
10944
10945       switch (declarator->kind)
10946         {
10947         case cdk_array:
10948           type = create_array_type_for_decl (dname, type,
10949                                              declarator->u.array.bounds);
10950           if (!valid_array_size_p (input_location, type, dname))
10951             type = error_mark_node;
10952
10953           if (declarator->std_attributes)
10954             /* [dcl.array]/1:
10955
10956                The optional attribute-specifier-seq appertains to the
10957                array.  */
10958             returned_attrs = chainon (returned_attrs,
10959                                       declarator->std_attributes);
10960           break;
10961
10962         case cdk_function:
10963           {
10964             tree arg_types;
10965             int funcdecl_p;
10966
10967             /* Declaring a function type.  */
10968
10969             input_location = declspecs->locations[ds_type_spec];
10970             abstract_virtuals_error (ACU_RETURN, type);
10971             input_location = saved_loc;
10972
10973             /* Pick up type qualifiers which should be applied to `this'.  */
10974             memfn_quals = declarator->u.function.qualifiers;
10975             /* Pick up virt-specifiers.  */
10976             virt_specifiers = declarator->u.function.virt_specifiers;
10977             /* And ref-qualifier, too */
10978             rqual = declarator->u.function.ref_qualifier;
10979             /* And tx-qualifier.  */
10980             tree tx_qual = declarator->u.function.tx_qualifier;
10981             /* Pick up the exception specifications.  */
10982             raises = declarator->u.function.exception_specification;
10983             /* If the exception-specification is ill-formed, let's pretend
10984                there wasn't one.  */
10985             if (raises == error_mark_node)
10986               raises = NULL_TREE;
10987
10988             if (reqs)
10989               error_at (location_of (reqs), "requires-clause on return type");
10990             reqs = declarator->u.function.requires_clause;
10991
10992             /* Say it's a definition only for the CALL_EXPR
10993                closest to the identifier.  */
10994             funcdecl_p = inner_declarator && inner_declarator->kind == cdk_id;
10995
10996             /* Handle a late-specified return type.  */
10997             tree late_return_type = declarator->u.function.late_return_type;
10998             if (funcdecl_p)
10999               {
11000                 if (tree auto_node = type_uses_auto (type))
11001                   {
11002                     if (!late_return_type)
11003                       {
11004                         if (current_class_type
11005                             && LAMBDA_TYPE_P (current_class_type))
11006                           /* OK for C++11 lambdas.  */;
11007                         else if (cxx_dialect < cxx14)
11008                           {
11009                             error ("%qs function uses "
11010                                    "%<auto%> type specifier without trailing "
11011                                    "return type", name);
11012                             inform (input_location, "deduced return type "
11013                                     "only available with -std=c++14 or "
11014                                     "-std=gnu++14");
11015                           }
11016                         else if (virtualp)
11017                           {
11018                             error ("virtual function cannot "
11019                                    "have deduced return type");
11020                             virtualp = false;
11021                           }
11022                       }
11023                     else if (!is_auto (type) && sfk != sfk_conversion)
11024                       {
11025                         error ("%qs function with trailing return type has"
11026                                " %qT as its type rather than plain %<auto%>",
11027                                name, type);
11028                         return error_mark_node;
11029                       }
11030                     if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
11031                       {
11032                         if (!late_return_type)
11033                           {
11034                             if (dguide_name_p (unqualified_id))
11035                               error_at (declarator->id_loc, "deduction guide "
11036                                         "for %qT must have trailing return "
11037                                         "type", TREE_TYPE (tmpl));
11038                             else
11039                               error_at (declarator->id_loc, "deduced class "
11040                                         "type %qT in function return type",
11041                                         type);
11042                             inform (DECL_SOURCE_LOCATION (tmpl),
11043                                     "%qD declared here", tmpl);
11044                           }
11045                         else if (CLASS_TYPE_P (late_return_type)
11046                                  && CLASSTYPE_TEMPLATE_INFO (late_return_type)
11047                                  && (CLASSTYPE_TI_TEMPLATE (late_return_type)
11048                                      == tmpl))
11049                           /* OK */;
11050                         else
11051                           error ("trailing return type %qT of deduction guide "
11052                                  "is not a specialization of %qT",
11053                                  late_return_type, TREE_TYPE (tmpl));
11054                       }
11055                   }
11056                 else if (late_return_type
11057                          && sfk != sfk_conversion)
11058                   {
11059                     if (cxx_dialect < cxx11)
11060                       /* Not using maybe_warn_cpp0x because this should
11061                          always be an error.  */
11062                       error ("trailing return type only available with "
11063                              "-std=c++11 or -std=gnu++11");
11064                     else
11065                       error ("%qs function with trailing return type not "
11066                              "declared with %<auto%> type specifier", name);
11067                     return error_mark_node;
11068                   }
11069               }
11070             type = splice_late_return_type (type, late_return_type);
11071             if (type == error_mark_node)
11072               return error_mark_node;
11073
11074             if (late_return_type)
11075               {
11076                 late_return_type_p = true;
11077                 type_quals = cp_type_quals (type);
11078               }
11079
11080             if (type_quals != TYPE_UNQUALIFIED)
11081               {
11082                 if (SCALAR_TYPE_P (type) || VOID_TYPE_P (type))
11083                   warning_at (typespec_loc, OPT_Wignored_qualifiers, "type "
11084                               "qualifiers ignored on function return type");
11085                 /* We now know that the TYPE_QUALS don't apply to the
11086                    decl, but to its return type.  */
11087                 type_quals = TYPE_UNQUALIFIED;
11088               }
11089
11090             /* Error about some types functions can't return.  */
11091
11092             if (TREE_CODE (type) == FUNCTION_TYPE)
11093               {
11094                 error_at (typespec_loc, "%qs declared as function returning "
11095                           "a function", name);
11096                 return error_mark_node;
11097               }
11098             if (TREE_CODE (type) == ARRAY_TYPE)
11099               {
11100                 error_at (typespec_loc, "%qs declared as function returning "
11101                           "an array", name);
11102                 return error_mark_node;
11103               }
11104
11105             if (ctype == NULL_TREE
11106                 && decl_context == FIELD
11107                 && funcdecl_p
11108                 && friendp == 0)
11109               ctype = current_class_type;
11110
11111             if (ctype && (sfk == sfk_constructor
11112                           || sfk == sfk_destructor))
11113               {
11114                 /* We are within a class's scope. If our declarator name
11115                    is the same as the class name, and we are defining
11116                    a function, then it is a constructor/destructor, and
11117                    therefore returns a void type.  */
11118
11119                 /* ISO C++ 12.4/2.  A destructor may not be declared
11120                    const or volatile.  A destructor may not be static.
11121                    A destructor may not be declared with ref-qualifier.
11122
11123                    ISO C++ 12.1.  A constructor may not be declared
11124                    const or volatile.  A constructor may not be
11125                    virtual.  A constructor may not be static.
11126                    A constructor may not be declared with ref-qualifier. */
11127                 if (staticp == 2)
11128                   error ((flags == DTOR_FLAG)
11129                          ? G_("destructor cannot be static member function")
11130                          : G_("constructor cannot be static member function"));
11131                 if (memfn_quals)
11132                   {
11133                     error ((flags == DTOR_FLAG)
11134                            ? G_("destructors may not be cv-qualified")
11135                            : G_("constructors may not be cv-qualified"));
11136                     memfn_quals = TYPE_UNQUALIFIED;
11137                   }
11138
11139                 if (rqual)
11140                   {
11141                     maybe_warn_cpp0x (CPP0X_REF_QUALIFIER);
11142                     error ((flags == DTOR_FLAG)
11143                            ? G_("destructors may not be ref-qualified")
11144                            : G_("constructors may not be ref-qualified"));
11145                     rqual = REF_QUAL_NONE;
11146                   }
11147
11148                 if (decl_context == FIELD
11149                     && !member_function_or_else (ctype,
11150                                                  current_class_type,
11151                                                  flags))
11152                   return error_mark_node;
11153
11154                 if (flags != DTOR_FLAG)
11155                   {
11156                     /* It's a constructor.  */
11157                     if (explicitp == 1)
11158                       explicitp = 2;
11159                     if (virtualp)
11160                       {
11161                         permerror (input_location,
11162                                    "constructors cannot be declared %<virtual%>");
11163                         virtualp = 0;
11164                       }
11165                     if (decl_context == FIELD
11166                         && sfk != sfk_constructor)
11167                       return error_mark_node;
11168                   }
11169                 if (decl_context == FIELD)
11170                   staticp = 0;
11171               }
11172             else if (friendp)
11173               {
11174                 if (virtualp)
11175                   {
11176                     /* Cannot be both friend and virtual.  */
11177                     error ("virtual functions cannot be friends");
11178                     friendp = 0;
11179                   }
11180                 if (decl_context == NORMAL)
11181                   error ("friend declaration not in class definition");
11182                 if (current_function_decl && funcdef_flag)
11183                   error ("can%'t define friend function %qs in a local "
11184                          "class definition",
11185                          name);
11186               }
11187             else if (ctype && sfk == sfk_conversion)
11188               {
11189                 if (explicitp == 1)
11190                   {
11191                     maybe_warn_cpp0x (CPP0X_EXPLICIT_CONVERSION);
11192                     explicitp = 2;
11193                   }
11194                 if (late_return_type_p)
11195                   error ("a conversion function cannot have a trailing return type");
11196               }
11197             else if (sfk == sfk_deduction_guide)
11198               {
11199                 if (explicitp == 1)
11200                   explicitp = 2;
11201               }
11202
11203             arg_types = grokparms (declarator->u.function.parameters,
11204                                    &parms);
11205
11206             if (inner_declarator
11207                 && inner_declarator->kind == cdk_id
11208                 && inner_declarator->u.id.sfk == sfk_destructor
11209                 && arg_types != void_list_node)
11210               {
11211                 error ("destructors may not have parameters");
11212                 arg_types = void_list_node;
11213                 parms = NULL_TREE;
11214               }
11215
11216             type = build_function_type (type, arg_types);
11217
11218             tree attrs = declarator->std_attributes;
11219             if (tx_qual)
11220               {
11221                 tree att = build_tree_list (tx_qual, NULL_TREE);
11222                 /* transaction_safe applies to the type, but
11223                    transaction_safe_dynamic applies to the function.  */
11224                 if (is_attribute_p ("transaction_safe", tx_qual))
11225                   attrs = chainon (attrs, att);
11226                 else
11227                   returned_attrs = chainon (returned_attrs, att);
11228               }
11229             if (attrs)
11230               /* [dcl.fct]/2:
11231
11232                  The optional attribute-specifier-seq appertains to
11233                  the function type.  */
11234               decl_attributes (&type, attrs, 0);
11235
11236             if (raises)
11237               type = build_exception_variant (type, raises);
11238           }
11239           break;
11240
11241         case cdk_pointer:
11242         case cdk_reference:
11243         case cdk_ptrmem:
11244           /* Filter out pointers-to-references and references-to-references.
11245              We can get these if a TYPE_DECL is used.  */
11246
11247           if (TREE_CODE (type) == REFERENCE_TYPE)
11248             {
11249               if (declarator->kind != cdk_reference)
11250                 {
11251                   error ("cannot declare pointer to %q#T", type);
11252                   type = TREE_TYPE (type);
11253                 }
11254
11255               /* In C++0x, we allow reference to reference declarations
11256                  that occur indirectly through typedefs [7.1.3/8 dcl.typedef]
11257                  and template type arguments [14.3.1/4 temp.arg.type]. The
11258                  check for direct reference to reference declarations, which
11259                  are still forbidden, occurs below. Reasoning behind the change
11260                  can be found in DR106, DR540, and the rvalue reference
11261                  proposals. */
11262               else if (cxx_dialect == cxx98)
11263                 {
11264                   error ("cannot declare reference to %q#T", type);
11265                   type = TREE_TYPE (type);
11266                 }
11267             }
11268           else if (VOID_TYPE_P (type))
11269             {
11270               if (declarator->kind == cdk_reference)
11271                 error ("cannot declare reference to %q#T", type);
11272               else if (declarator->kind == cdk_ptrmem)
11273                 error ("cannot declare pointer to %q#T member", type);
11274             }
11275
11276           /* We now know that the TYPE_QUALS don't apply to the decl,
11277              but to the target of the pointer.  */
11278           type_quals = TYPE_UNQUALIFIED;
11279
11280           /* This code used to handle METHOD_TYPE, but I don't think it's
11281              possible to get it here anymore.  */
11282           gcc_assert (TREE_CODE (type) != METHOD_TYPE);
11283           if (declarator->kind == cdk_ptrmem
11284               && TREE_CODE (type) == FUNCTION_TYPE)
11285             {
11286               memfn_quals |= type_memfn_quals (type);
11287               type = build_memfn_type (type,
11288                                        declarator->u.pointer.class_type,
11289                                        memfn_quals,
11290                                        rqual);
11291               if (type == error_mark_node)
11292                 return error_mark_node;
11293
11294               rqual = REF_QUAL_NONE;
11295               memfn_quals = TYPE_UNQUALIFIED;
11296             }
11297
11298           if (TREE_CODE (type) == FUNCTION_TYPE
11299               && (type_memfn_quals (type) != TYPE_UNQUALIFIED
11300                   || type_memfn_rqual (type) != REF_QUAL_NONE))
11301             error (declarator->kind == cdk_reference
11302                    ? G_("cannot declare reference to qualified function type %qT")
11303                    : G_("cannot declare pointer to qualified function type %qT"),
11304                    type);
11305
11306           /* When the pointed-to type involves components of variable size,
11307              care must be taken to ensure that the size evaluation code is
11308              emitted early enough to dominate all the possible later uses
11309              and late enough for the variables on which it depends to have
11310              been assigned.
11311
11312              This is expected to happen automatically when the pointed-to
11313              type has a name/declaration of it's own, but special attention
11314              is required if the type is anonymous.
11315
11316              We handle the NORMAL and FIELD contexts here by inserting a
11317              dummy statement that just evaluates the size at a safe point
11318              and ensures it is not deferred until e.g. within a deeper
11319              conditional context (c++/43555).
11320
11321              We expect nothing to be needed here for PARM or TYPENAME.
11322              Evaluating the size at this point for TYPENAME would
11323              actually be incorrect, as we might be in the middle of an
11324              expression with side effects on the pointed-to type size
11325              "arguments" prior to the pointer declaration point and the
11326              size evaluation could end up prior to the side effects.  */
11327
11328           if (!TYPE_NAME (type)
11329               && (decl_context == NORMAL || decl_context == FIELD)
11330               && at_function_scope_p ()
11331               && variably_modified_type_p (type, NULL_TREE))
11332             {
11333               TYPE_NAME (type) = build_decl (UNKNOWN_LOCATION, TYPE_DECL,
11334                                              NULL_TREE, type);
11335               add_decl_expr (TYPE_NAME (type));
11336             }
11337
11338           if (declarator->kind == cdk_reference)
11339             {
11340               /* In C++0x, the type we are creating a reference to might be
11341                  a typedef which is itself a reference type. In that case,
11342                  we follow the reference collapsing rules in
11343                  [7.1.3/8 dcl.typedef] to create the final reference type:
11344
11345                  "If a typedef TD names a type that is a reference to a type
11346                  T, an attempt to create the type 'lvalue reference to cv TD'
11347                  creates the type 'lvalue reference to T,' while an attempt
11348                  to create the type "rvalue reference to cv TD' creates the
11349                  type TD."
11350               */
11351               if (VOID_TYPE_P (type))
11352                 /* We already gave an error.  */;
11353               else if (TREE_CODE (type) == REFERENCE_TYPE)
11354                 {
11355                   if (declarator->u.reference.rvalue_ref)
11356                     /* Leave type alone.  */;
11357                   else
11358                     type = cp_build_reference_type (TREE_TYPE (type), false);
11359                 }
11360               else
11361                 type = cp_build_reference_type
11362                   (type, declarator->u.reference.rvalue_ref);
11363
11364               /* In C++0x, we need this check for direct reference to
11365                  reference declarations, which are forbidden by
11366                  [8.3.2/5 dcl.ref]. Reference to reference declarations
11367                  are only allowed indirectly through typedefs and template
11368                  type arguments. Example:
11369
11370                    void foo(int & &);      // invalid ref-to-ref decl
11371
11372                    typedef int & int_ref;
11373                    void foo(int_ref &);    // valid ref-to-ref decl
11374               */
11375               if (inner_declarator && inner_declarator->kind == cdk_reference)
11376                 error ("cannot declare reference to %q#T, which is not "
11377                        "a typedef or a template type argument", type);
11378             }
11379           else if (TREE_CODE (type) == METHOD_TYPE)
11380             type = build_ptrmemfunc_type (build_pointer_type (type));
11381           else if (declarator->kind == cdk_ptrmem)
11382             {
11383               gcc_assert (TREE_CODE (declarator->u.pointer.class_type)
11384                           != NAMESPACE_DECL);
11385               if (declarator->u.pointer.class_type == error_mark_node)
11386                 /* We will already have complained.  */
11387                 type = error_mark_node;
11388               else
11389                 type = build_ptrmem_type (declarator->u.pointer.class_type,
11390                                           type);
11391             }
11392           else
11393             type = build_pointer_type (type);
11394
11395           /* Process a list of type modifier keywords (such as
11396              const or volatile) that were given inside the `*' or `&'.  */
11397
11398           if (declarator->u.pointer.qualifiers)
11399             {
11400               type
11401                 = cp_build_qualified_type (type,
11402                                            declarator->u.pointer.qualifiers);
11403               type_quals = cp_type_quals (type);
11404             }
11405
11406           /* Apply C++11 attributes to the pointer, and not to the
11407              type pointed to.  This is unlike what is done for GNU
11408              attributes above.  It is to comply with [dcl.ptr]/1:
11409
11410                  [the optional attribute-specifier-seq (7.6.1) appertains
11411                   to the pointer and not to the object pointed to].  */
11412           if (declarator->std_attributes)
11413             decl_attributes (&type, declarator->std_attributes,
11414                              0);
11415
11416           ctype = NULL_TREE;
11417           break;
11418
11419         case cdk_error:
11420           break;
11421
11422         default:
11423           gcc_unreachable ();
11424         }
11425     }
11426
11427   /* A `constexpr' specifier used in an object declaration declares
11428      the object as `const'.  */
11429   if (constexpr_p && innermost_code != cdk_function)
11430     {
11431       /* DR1688 says that a `constexpr' specifier in combination with
11432          `volatile' is valid.  */
11433
11434       if (TREE_CODE (type) != REFERENCE_TYPE)
11435         {
11436           type_quals |= TYPE_QUAL_CONST;
11437           type = cp_build_qualified_type (type, type_quals);
11438         }
11439     }
11440
11441   if (unqualified_id && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR
11442       && TREE_CODE (type) != FUNCTION_TYPE
11443       && TREE_CODE (type) != METHOD_TYPE
11444       && !variable_template_p (TREE_OPERAND (unqualified_id, 0)))
11445     {
11446       error ("template-id %qD used as a declarator",
11447              unqualified_id);
11448       unqualified_id = dname;
11449     }
11450
11451   /* If TYPE is a FUNCTION_TYPE, but the function name was explicitly
11452      qualified with a class-name, turn it into a METHOD_TYPE, unless
11453      we know that the function is static.  We take advantage of this
11454      opportunity to do other processing that pertains to entities
11455      explicitly declared to be class members.  Note that if DECLARATOR
11456      is non-NULL, we know it is a cdk_id declarator; otherwise, we
11457      would not have exited the loop above.  */
11458   if (declarator
11459       && declarator->kind == cdk_id
11460       && declarator->u.id.qualifying_scope
11461       && MAYBE_CLASS_TYPE_P (declarator->u.id.qualifying_scope))
11462     {
11463       ctype = declarator->u.id.qualifying_scope;
11464       ctype = TYPE_MAIN_VARIANT (ctype);
11465       template_count = num_template_headers_for_class (ctype);
11466
11467       if (ctype == current_class_type)
11468         {
11469           if (friendp)
11470             {
11471               permerror (input_location, "member functions are implicitly "
11472                                          "friends of their class");
11473               friendp = 0;
11474             }
11475           else
11476             permerror (declarator->id_loc, 
11477                        "extra qualification %<%T::%> on member %qs",
11478                        ctype, name);
11479         }
11480       else if (/* If the qualifying type is already complete, then we
11481                   can skip the following checks.  */
11482                !COMPLETE_TYPE_P (ctype)
11483                && (/* If the function is being defined, then
11484                       qualifying type must certainly be complete.  */
11485                    funcdef_flag
11486                    /* A friend declaration of "T::f" is OK, even if
11487                       "T" is a template parameter.  But, if this
11488                       function is not a friend, the qualifying type
11489                       must be a class.  */
11490                    || (!friendp && !CLASS_TYPE_P (ctype))
11491                    /* For a declaration, the type need not be
11492                       complete, if either it is dependent (since there
11493                       is no meaningful definition of complete in that
11494                       case) or the qualifying class is currently being
11495                       defined.  */
11496                    || !(dependent_type_p (ctype)
11497                         || currently_open_class (ctype)))
11498                /* Check that the qualifying type is complete.  */
11499                && !complete_type_or_else (ctype, NULL_TREE))
11500         return error_mark_node;
11501       else if (TREE_CODE (type) == FUNCTION_TYPE)
11502         {
11503           if (current_class_type
11504               && (!friendp || funcdef_flag || initialized))
11505             {
11506               error (funcdef_flag || initialized
11507                      ? G_("cannot define member function %<%T::%s%> "
11508                           "within %qT")
11509                      : G_("cannot declare member function %<%T::%s%> "
11510                           "within %qT"),
11511                      ctype, name, current_class_type);
11512               return error_mark_node;
11513             }
11514         }
11515       else if (typedef_p && current_class_type)
11516         {
11517           error ("cannot declare member %<%T::%s%> within %qT",
11518                  ctype, name, current_class_type);
11519           return error_mark_node;
11520         }
11521     }
11522
11523   if (ctype == NULL_TREE && decl_context == FIELD && friendp == 0)
11524     ctype = current_class_type;
11525
11526   /* Now TYPE has the actual type.  */
11527
11528   if (returned_attrs)
11529     {
11530       if (attrlist)
11531         *attrlist = chainon (returned_attrs, *attrlist);
11532       else
11533         attrlist = &returned_attrs;
11534     }
11535
11536   if (declarator
11537       && declarator->kind == cdk_id
11538       && declarator->std_attributes
11539       && attrlist != NULL)
11540     {
11541       /* [dcl.meaning]/1: The optional attribute-specifier-seq following
11542          a declarator-id appertains to the entity that is declared.  */
11543       if (declarator->std_attributes != error_mark_node)
11544         *attrlist = chainon (*attrlist, declarator->std_attributes);
11545       else
11546         /* We should have already diagnosed the issue (c++/78344).  */
11547         gcc_assert (seen_error ());
11548     }
11549
11550   /* Handle parameter packs. */
11551   if (parameter_pack_p)
11552     {
11553       if (decl_context == PARM)
11554         /* Turn the type into a pack expansion.*/
11555         type = make_pack_expansion (type);
11556       else
11557         error ("non-parameter %qs cannot be a parameter pack", name);
11558     }
11559
11560   if ((decl_context == FIELD || decl_context == PARM)
11561       && !processing_template_decl
11562       && variably_modified_type_p (type, NULL_TREE))
11563     {
11564       if (decl_context == FIELD)
11565         error ("data member may not have variably modified type %qT", type);
11566       else
11567         error ("parameter may not have variably modified type %qT", type);
11568       type = error_mark_node;
11569     }
11570
11571   if (explicitp == 1 || (explicitp && friendp))
11572     {
11573       /* [dcl.fct.spec] (C++11) The explicit specifier shall be used only
11574          in the declaration of a constructor or conversion function within
11575          a class definition.  */
11576       if (!current_class_type)
11577         error_at (declspecs->locations[ds_explicit],
11578                   "%<explicit%> outside class declaration");
11579       else if (friendp)
11580         error_at (declspecs->locations[ds_explicit],
11581                   "%<explicit%> in friend declaration");
11582       else
11583         error_at (declspecs->locations[ds_explicit],
11584                   "only declarations of constructors and conversion operators "
11585                   "can be %<explicit%>");
11586       explicitp = 0;
11587     }
11588
11589   if (storage_class == sc_mutable)
11590     {
11591       if (decl_context != FIELD || friendp)
11592         {
11593           error ("non-member %qs cannot be declared %<mutable%>", name);
11594           storage_class = sc_none;
11595         }
11596       else if (decl_context == TYPENAME || typedef_p)
11597         {
11598           error ("non-object member %qs cannot be declared %<mutable%>", name);
11599           storage_class = sc_none;
11600         }
11601       else if (TREE_CODE (type) == FUNCTION_TYPE
11602                || TREE_CODE (type) == METHOD_TYPE)
11603         {
11604           error ("function %qs cannot be declared %<mutable%>", name);
11605           storage_class = sc_none;
11606         }
11607       else if (staticp)
11608         {
11609           error ("static %qs cannot be declared %<mutable%>", name);
11610           storage_class = sc_none;
11611         }
11612       else if (type_quals & TYPE_QUAL_CONST)
11613         {
11614           error ("const %qs cannot be declared %<mutable%>", name);
11615           storage_class = sc_none;
11616         }
11617       else if (TREE_CODE (type) == REFERENCE_TYPE)
11618         {
11619           permerror (input_location, "reference %qs cannot be declared "
11620                      "%<mutable%>", name);
11621           storage_class = sc_none;
11622         }
11623     }
11624
11625   /* If this is declaring a typedef name, return a TYPE_DECL.  */
11626   if (typedef_p && decl_context != TYPENAME)
11627     {
11628       tree decl;
11629
11630       /* This declaration:
11631
11632            typedef void f(int) const;
11633
11634          declares a function type which is not a member of any
11635          particular class, but which is cv-qualified; for
11636          example "f S::*" declares a pointer to a const-qualified
11637          member function of S.  We record the cv-qualification in the
11638          function type.  */
11639       if ((rqual || memfn_quals) && TREE_CODE (type) == FUNCTION_TYPE)
11640         {
11641           type = apply_memfn_quals (type, memfn_quals, rqual);
11642           
11643           /* We have now dealt with these qualifiers.  */
11644           memfn_quals = TYPE_UNQUALIFIED;
11645           rqual = REF_QUAL_NONE;
11646         }
11647
11648       if (type_uses_auto (type))
11649         {
11650           error ("typedef declared %<auto%>");
11651           type = error_mark_node;
11652         }
11653
11654       if (reqs)
11655         error_at (location_of (reqs), "requires-clause on typedef");
11656
11657       if (decl_context == FIELD)
11658         decl = build_lang_decl (TYPE_DECL, unqualified_id, type);
11659       else
11660         decl = build_decl (input_location, TYPE_DECL, unqualified_id, type);
11661       if (id_declarator && declarator->u.id.qualifying_scope) {
11662         error_at (DECL_SOURCE_LOCATION (decl), 
11663                   "typedef name may not be a nested-name-specifier");
11664         TREE_TYPE (decl) = error_mark_node;
11665       }
11666
11667       if (decl_context != FIELD)
11668         {
11669           if (!current_function_decl)
11670             DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
11671           else if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (current_function_decl)
11672                    || (DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P
11673                        (current_function_decl)))
11674             /* The TYPE_DECL is "abstract" because there will be
11675                clones of this constructor/destructor, and there will
11676                be copies of this TYPE_DECL generated in those
11677                clones.  The decloning optimization (for space) may
11678                revert this subsequently if it determines that
11679                the clones should share a common implementation.  */
11680             DECL_ABSTRACT_P (decl) = true;
11681         }
11682       else if (current_class_type
11683                && constructor_name_p (unqualified_id, current_class_type))
11684         permerror (input_location, "ISO C++ forbids nested type %qD with same name "
11685                    "as enclosing class",
11686                    unqualified_id);
11687
11688       /* If the user declares "typedef struct {...} foo" then the
11689          struct will have an anonymous name.  Fill that name in now.
11690          Nothing can refer to it, so nothing needs know about the name
11691          change.  */
11692       if (type != error_mark_node
11693           && unqualified_id
11694           && TYPE_NAME (type)
11695           && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL
11696           && TYPE_UNNAMED_P (type)
11697           && declspecs->type_definition_p
11698           && attributes_naming_typedef_ok (*attrlist)
11699           && cp_type_quals (type) == TYPE_UNQUALIFIED)
11700         name_unnamed_type (type, decl);
11701
11702       if (signed_p
11703           || (typedef_decl && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl)))
11704         C_TYPEDEF_EXPLICITLY_SIGNED (decl) = 1;
11705
11706       bad_specifiers (decl, BSP_TYPE, virtualp,
11707                       memfn_quals != TYPE_UNQUALIFIED,
11708                       inlinep, friendp, raises != NULL_TREE);
11709
11710       if (decl_spec_seq_has_spec_p (declspecs, ds_alias))
11711         /* Acknowledge that this was written:
11712              `using analias = atype;'.  */
11713         TYPE_DECL_ALIAS_P (decl) = 1;
11714
11715       return decl;
11716     }
11717
11718   /* Detect the case of an array type of unspecified size
11719      which came, as such, direct from a typedef name.
11720      We must copy the type, so that the array's domain can be
11721      individually set by the object's initializer.  */
11722
11723   if (type && typedef_type
11724       && TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type)
11725       && TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (typedef_type))
11726     type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
11727
11728   /* Detect where we're using a typedef of function type to declare a
11729      function. PARMS will not be set, so we must create it now.  */
11730
11731   if (type == typedef_type && TREE_CODE (type) == FUNCTION_TYPE)
11732     {
11733       tree decls = NULL_TREE;
11734       tree args;
11735
11736       for (args = TYPE_ARG_TYPES (type);
11737            args && args != void_list_node;
11738            args = TREE_CHAIN (args))
11739         {
11740           tree decl = cp_build_parm_decl (NULL_TREE, NULL_TREE,
11741                                           TREE_VALUE (args));
11742
11743           DECL_CHAIN (decl) = decls;
11744           decls = decl;
11745         }
11746
11747       parms = nreverse (decls);
11748
11749       if (decl_context != TYPENAME)
11750         {
11751           /* The qualifiers on the function type become the qualifiers on
11752              the non-static member function. */
11753           memfn_quals |= type_memfn_quals (type);
11754           rqual = type_memfn_rqual (type);
11755           type_quals = TYPE_UNQUALIFIED;
11756         }
11757     }
11758
11759   /* If this is a type name (such as, in a cast or sizeof),
11760      compute the type and return it now.  */
11761
11762   if (decl_context == TYPENAME)
11763     {
11764       /* Note that here we don't care about type_quals.  */
11765
11766       /* Special case: "friend class foo" looks like a TYPENAME context.  */
11767       if (friendp)
11768         {
11769           if (inlinep)
11770             {
11771               error ("%<inline%> specified for friend class declaration");
11772               inlinep = 0;
11773             }
11774
11775           if (!current_aggr)
11776             {
11777               /* Don't allow friend declaration without a class-key.  */
11778               if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
11779                 permerror (input_location, "template parameters cannot be friends");
11780               else if (TREE_CODE (type) == TYPENAME_TYPE)
11781                 permerror (input_location, "friend declaration requires class-key, "
11782                            "i.e. %<friend class %T::%D%>",
11783                            TYPE_CONTEXT (type), TYPENAME_TYPE_FULLNAME (type));
11784               else
11785                 permerror (input_location, "friend declaration requires class-key, "
11786                            "i.e. %<friend %#T%>",
11787                            type);
11788             }
11789
11790           /* Only try to do this stuff if we didn't already give up.  */
11791           if (type != integer_type_node)
11792             {
11793               /* A friendly class?  */
11794               if (current_class_type)
11795                 make_friend_class (current_class_type, TYPE_MAIN_VARIANT (type),
11796                                    /*complain=*/true);
11797               else
11798                 error ("trying to make class %qT a friend of global scope",
11799                        type);
11800
11801               type = void_type_node;
11802             }
11803         }
11804       else if (memfn_quals || rqual)
11805         {
11806           if (ctype == NULL_TREE
11807               && TREE_CODE (type) == METHOD_TYPE)
11808             ctype = TYPE_METHOD_BASETYPE (type);
11809
11810           if (ctype)
11811             type = build_memfn_type (type, ctype, memfn_quals, rqual);
11812           /* Core issue #547: need to allow this in template type args.
11813              Allow it in general in C++11 for alias-declarations.  */
11814           else if ((template_type_arg || cxx_dialect >= cxx11)
11815                    && TREE_CODE (type) == FUNCTION_TYPE)
11816             type = apply_memfn_quals (type, memfn_quals, rqual);
11817           else
11818             error ("invalid qualifiers on non-member function type");
11819         }
11820
11821       if (reqs)
11822         error_at (location_of (reqs), "requires-clause on type-id");
11823
11824       return type;
11825     }
11826   else if (unqualified_id == NULL_TREE && decl_context != PARM
11827            && decl_context != CATCHPARM
11828            && TREE_CODE (type) != UNION_TYPE
11829            && ! bitfield
11830            && innermost_code != cdk_decomp)
11831     {
11832       error ("abstract declarator %qT used as declaration", type);
11833       return error_mark_node;
11834     }
11835
11836   if (!FUNC_OR_METHOD_TYPE_P (type))
11837     {
11838       /* Only functions may be declared using an operator-function-id.  */
11839       if (dname && IDENTIFIER_ANY_OP_P (dname))
11840         {
11841           error ("declaration of %qD as non-function", dname);
11842           return error_mark_node;
11843         }
11844
11845       if (reqs)
11846         error_at (location_of (reqs),
11847                   "requires-clause on declaration of non-function type %qT",
11848                   type);
11849     }
11850
11851   /* We don't check parameter types here because we can emit a better
11852      error message later.  */
11853   if (decl_context != PARM)
11854     {
11855       type = check_var_type (unqualified_id, type);
11856       if (type == error_mark_node)
11857         return error_mark_node;
11858     }
11859
11860   /* Now create the decl, which may be a VAR_DECL, a PARM_DECL
11861      or a FUNCTION_DECL, depending on DECL_CONTEXT and TYPE.  */
11862
11863   if (decl_context == PARM || decl_context == CATCHPARM)
11864     {
11865       if (ctype || in_namespace)
11866         error ("cannot use %<::%> in parameter declaration");
11867
11868       if (type_uses_auto (type)
11869           && !(cxx_dialect >= cxx17 && template_parm_flag))
11870         {
11871           if (cxx_dialect >= cxx14)
11872             error ("%<auto%> parameter not permitted in this context");
11873           else
11874             error ("parameter declared %<auto%>");
11875           type = error_mark_node;
11876         }
11877
11878       /* A parameter declared as an array of T is really a pointer to T.
11879          One declared as a function is really a pointer to a function.
11880          One declared as a member is really a pointer to member.  */
11881
11882       if (TREE_CODE (type) == ARRAY_TYPE)
11883         {
11884           /* Transfer const-ness of array into that of type pointed to.  */
11885           type = build_pointer_type (TREE_TYPE (type));
11886           type_quals = TYPE_UNQUALIFIED;
11887           array_parameter_p = true;
11888         }
11889       else if (TREE_CODE (type) == FUNCTION_TYPE)
11890         type = build_pointer_type (type);
11891     }
11892
11893   if (ctype && TREE_CODE (type) == FUNCTION_TYPE && staticp < 2
11894       && !(identifier_p (unqualified_id)
11895            && IDENTIFIER_NEWDEL_OP_P (unqualified_id)))
11896     {
11897       cp_cv_quals real_quals = memfn_quals;
11898       if (cxx_dialect < cxx14 && constexpr_p
11899           && sfk != sfk_constructor && sfk != sfk_destructor)
11900         real_quals |= TYPE_QUAL_CONST;
11901       type = build_memfn_type (type, ctype, real_quals, rqual);
11902     }
11903
11904   {
11905     tree decl = NULL_TREE;
11906
11907     if (decl_context == PARM)
11908       {
11909         decl = cp_build_parm_decl (NULL_TREE, unqualified_id, type);
11910         DECL_ARRAY_PARAMETER_P (decl) = array_parameter_p;
11911
11912         bad_specifiers (decl, BSP_PARM, virtualp,
11913                         memfn_quals != TYPE_UNQUALIFIED,
11914                         inlinep, friendp, raises != NULL_TREE);
11915       }
11916     else if (decl_context == FIELD)
11917       {
11918         if (!staticp && !friendp && TREE_CODE (type) != METHOD_TYPE)
11919           if (tree auto_node = type_uses_auto (type))
11920             {
11921               location_t loc = declspecs->locations[ds_type_spec];
11922               if (CLASS_PLACEHOLDER_TEMPLATE (auto_node))
11923                 error_at (loc, "invalid use of template-name %qE without an "
11924                           "argument list",
11925                           CLASS_PLACEHOLDER_TEMPLATE (auto_node));
11926               else
11927                 error_at (loc, "non-static data member declared with "
11928                           "placeholder %qT", auto_node);
11929               type = error_mark_node;
11930             }
11931
11932         /* The C99 flexible array extension.  */
11933         if (!staticp && TREE_CODE (type) == ARRAY_TYPE
11934             && TYPE_DOMAIN (type) == NULL_TREE)
11935           {
11936             if (ctype
11937                 && (TREE_CODE (ctype) == UNION_TYPE
11938                     || TREE_CODE (ctype) == QUAL_UNION_TYPE))
11939               {
11940                 error ("flexible array member in union");
11941                 type = error_mark_node;
11942               }
11943             else
11944               {
11945                 /* Array is a flexible member.  */
11946                 if (in_system_header_at (input_location))
11947                   /* Do not warn on flexible array members in system
11948                      headers because glibc uses them.  */;
11949                 else if (name)
11950                   pedwarn (input_location, OPT_Wpedantic,
11951                            "ISO C++ forbids flexible array member %qs", name);
11952                 else
11953                   pedwarn (input_location, OPT_Wpedantic,
11954                            "ISO C++ forbids flexible array members");
11955
11956                 /* Flexible array member has a null domain.  */
11957                 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
11958               }
11959           }
11960
11961         if (type == error_mark_node)
11962           {
11963             /* Happens when declaring arrays of sizes which
11964                are error_mark_node, for example.  */
11965             decl = NULL_TREE;
11966           }
11967         else if (in_namespace && !friendp)
11968           {
11969             /* Something like struct S { int N::j; };  */
11970             error ("invalid use of %<::%>");
11971             return error_mark_node;
11972           }
11973         else if (TREE_CODE (type) == FUNCTION_TYPE
11974                  || TREE_CODE (type) == METHOD_TYPE)
11975           {
11976             int publicp = 0;
11977             tree function_context;
11978
11979             if (friendp == 0)
11980               {
11981                 /* This should never happen in pure C++ (the check
11982                    could be an assert).  It could happen in
11983                    Objective-C++ if someone writes invalid code that
11984                    uses a function declaration for an instance
11985                    variable or property (instance variables and
11986                    properties are parsed as FIELD_DECLs, but they are
11987                    part of an Objective-C class, not a C++ class).
11988                    That code is invalid and is caught by this
11989                    check.  */
11990                 if (!ctype)
11991                   {
11992                     error ("declaration of function %qD in invalid context",
11993                            unqualified_id);
11994                     return error_mark_node;
11995                   }
11996
11997                 /* ``A union may [ ... ] not [ have ] virtual functions.''
11998                    ARM 9.5 */
11999                 if (virtualp && TREE_CODE (ctype) == UNION_TYPE)
12000                   {
12001                     error ("function %qD declared %<virtual%> inside a union",
12002                            unqualified_id);
12003                     return error_mark_node;
12004                   }
12005
12006                 if (virtualp
12007                     && identifier_p (unqualified_id)
12008                     && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
12009                   {
12010                     error ("%qD cannot be declared %<virtual%>, since it "
12011                            "is always static", unqualified_id);
12012                     virtualp = 0;
12013                   }
12014               }
12015
12016             /* Check that the name used for a destructor makes sense.  */
12017             if (sfk == sfk_destructor)
12018               {
12019                 tree uqname = id_declarator->u.id.unqualified_name;
12020
12021                 if (!ctype)
12022                   {
12023                     gcc_assert (friendp);
12024                     error ("expected qualified name in friend declaration "
12025                            "for destructor %qD", uqname);
12026                     return error_mark_node;
12027                   }
12028
12029                 if (!check_dtor_name (ctype, TREE_OPERAND (uqname, 0)))
12030                   {
12031                     error ("declaration of %qD as member of %qT",
12032                            uqname, ctype);
12033                     return error_mark_node;
12034                   }
12035                 if (concept_p)
12036                   {
12037                     error ("a destructor cannot be %<concept%>");
12038                     return error_mark_node;
12039                   }
12040                 if (constexpr_p)
12041                   {
12042                     error ("a destructor cannot be %<constexpr%>");
12043                     return error_mark_node;
12044                   }
12045               }
12046             else if (sfk == sfk_constructor && friendp && !ctype)
12047               {
12048                 error ("expected qualified name in friend declaration "
12049                        "for constructor %qD",
12050                        id_declarator->u.id.unqualified_name);
12051                 return error_mark_node;
12052               }
12053             if (sfk == sfk_constructor)
12054               if (concept_p)
12055                 {
12056                   error ("a constructor cannot be %<concept%>");
12057                   return error_mark_node;
12058                 }
12059             if (concept_p)
12060               {
12061                 error ("a concept cannot be a member function");
12062                 concept_p = false;
12063               }
12064
12065             if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
12066               {
12067                 tree tmpl = TREE_OPERAND (unqualified_id, 0);
12068                 if (variable_template_p (tmpl))
12069                   {
12070                     error ("specialization of variable template %qD "
12071                            "declared as function", tmpl);
12072                     inform (DECL_SOURCE_LOCATION (tmpl),
12073                             "variable template declared here");
12074                     return error_mark_node;
12075                   }
12076               }
12077
12078             /* Tell grokfndecl if it needs to set TREE_PUBLIC on the node.  */
12079             function_context = (ctype != NULL_TREE) ?
12080               decl_function_context (TYPE_MAIN_DECL (ctype)) : NULL_TREE;
12081             publicp = (! friendp || ! staticp)
12082               && function_context == NULL_TREE;
12083
12084             if (late_return_type_p)
12085               TYPE_HAS_LATE_RETURN_TYPE (type) = 1;
12086
12087             decl = grokfndecl (ctype, type,
12088                                TREE_CODE (unqualified_id) != TEMPLATE_ID_EXPR
12089                                ? unqualified_id : dname,
12090                                parms,
12091                                unqualified_id,
12092                                reqs,
12093                                virtualp, flags, memfn_quals, rqual, raises,
12094                                friendp ? -1 : 0, friendp, publicp,
12095                                inlinep | (2 * constexpr_p) | (4 * concept_p),
12096                                initialized == SD_DELETED, sfk,
12097                                funcdef_flag, template_count, in_namespace,
12098                                attrlist, declarator->id_loc);
12099             decl = set_virt_specifiers (decl, virt_specifiers);
12100             if (decl == NULL_TREE)
12101               return error_mark_node;
12102 #if 0
12103             /* This clobbers the attrs stored in `decl' from `attrlist'.  */
12104             /* The decl and setting of decl_attr is also turned off.  */
12105             decl = build_decl_attribute_variant (decl, decl_attr);
12106 #endif
12107
12108             /* [class.conv.ctor]
12109
12110                A constructor declared without the function-specifier
12111                explicit that can be called with a single parameter
12112                specifies a conversion from the type of its first
12113                parameter to the type of its class.  Such a constructor
12114                is called a converting constructor.  */
12115             if (explicitp == 2)
12116               DECL_NONCONVERTING_P (decl) = 1;
12117           }
12118         else if (!staticp && !dependent_type_p (type)
12119                  && !COMPLETE_TYPE_P (complete_type (type))
12120                  && (!complete_or_array_type_p (type)
12121                      || initialized == 0))
12122           {
12123             if (TREE_CODE (type) != ARRAY_TYPE
12124                 || !COMPLETE_TYPE_P (TREE_TYPE (type)))
12125               {
12126                 if (unqualified_id)
12127                   {
12128                     error ("field %qD has incomplete type %qT",
12129                            unqualified_id, type);
12130                     cxx_incomplete_type_inform (strip_array_types (type));
12131                   }
12132                 else
12133                   error ("name %qT has incomplete type", type);
12134
12135                 type = error_mark_node;
12136                 decl = NULL_TREE;
12137               }
12138           }
12139         else
12140           {
12141             if (friendp)
12142               {
12143                 error ("%qE is neither function nor member function; "
12144                        "cannot be declared friend", unqualified_id);
12145                 return error_mark_node;
12146               }
12147             decl = NULL_TREE;
12148           }
12149
12150         if (friendp)
12151           {
12152             /* Friends are treated specially.  */
12153             if (ctype == current_class_type)
12154               ;  /* We already issued a permerror.  */
12155             else if (decl && DECL_NAME (decl))
12156               {
12157                 if (template_class_depth (current_class_type) == 0)
12158                   {
12159                     decl = check_explicit_specialization
12160                       (unqualified_id, decl, template_count,
12161                        2 * funcdef_flag + 4);
12162                     if (decl == error_mark_node)
12163                       return error_mark_node;
12164                   }
12165
12166                 decl = do_friend (ctype, unqualified_id, decl,
12167                                   *attrlist, flags,
12168                                   funcdef_flag);
12169                 return decl;
12170               }
12171             else
12172               return error_mark_node;
12173           }
12174
12175         /* Structure field.  It may not be a function, except for C++.  */
12176
12177         if (decl == NULL_TREE)
12178           {
12179             if (staticp)
12180               {
12181                 /* C++ allows static class members.  All other work
12182                    for this is done by grokfield.  */
12183                 decl = build_lang_decl_loc (declarator
12184                                             ? declarator->id_loc
12185                                             : input_location,
12186                                             VAR_DECL, unqualified_id, type);
12187                 set_linkage_for_static_data_member (decl);
12188                 if (concept_p)
12189                     error ("static data member %qE declared %<concept%>",
12190                            unqualified_id);
12191                 else if (constexpr_p && !initialized)
12192                   {
12193                     error ("%<constexpr%> static data member %qD must have an "
12194                            "initializer", decl);
12195                     constexpr_p = false;
12196                   }
12197
12198                 if (inlinep)
12199                   mark_inline_variable (decl);
12200
12201                 if (!DECL_VAR_DECLARED_INLINE_P (decl)
12202                     && !(cxx_dialect >= cxx17 && constexpr_p))
12203                   /* Even if there is an in-class initialization, DECL
12204                      is considered undefined until an out-of-class
12205                      definition is provided, unless this is an inline
12206                      variable.  */
12207                   DECL_EXTERNAL (decl) = 1;
12208
12209                 if (thread_p)
12210                   {
12211                     CP_DECL_THREAD_LOCAL_P (decl) = true;
12212                     if (!processing_template_decl)
12213                       set_decl_tls_model (decl, decl_default_tls_model (decl));
12214                     if (declspecs->gnu_thread_keyword_p)
12215                       SET_DECL_GNU_TLS_P (decl);
12216                   }
12217               }
12218             else
12219               {
12220                 if (concept_p)
12221                   error ("non-static data member %qE declared %<concept%>",
12222                          unqualified_id);
12223                 else if (constexpr_p)
12224                   {
12225                     error ("non-static data member %qE declared %<constexpr%>",
12226                            unqualified_id);
12227                     constexpr_p = false;
12228                   }
12229                 decl = build_decl (input_location,
12230                                    FIELD_DECL, unqualified_id, type);
12231                 DECL_NONADDRESSABLE_P (decl) = bitfield;
12232                 if (bitfield && !unqualified_id)
12233                   {
12234                     TREE_NO_WARNING (decl) = 1;
12235                     DECL_PADDING_P (decl) = 1;
12236                   }
12237
12238                 if (storage_class == sc_mutable)
12239                   {
12240                     DECL_MUTABLE_P (decl) = 1;
12241                     storage_class = sc_none;
12242                   }
12243
12244                 if (initialized)
12245                   {
12246                     /* An attempt is being made to initialize a non-static
12247                        member.  This is new in C++11.  */
12248                     maybe_warn_cpp0x (CPP0X_NSDMI);
12249
12250                     /* If this has been parsed with static storage class, but
12251                        errors forced staticp to be cleared, ensure NSDMI is
12252                        not present.  */
12253                     if (declspecs->storage_class == sc_static)
12254                       DECL_INITIAL (decl) = error_mark_node;
12255                   }
12256               }
12257
12258             bad_specifiers (decl, BSP_FIELD, virtualp,
12259                             memfn_quals != TYPE_UNQUALIFIED,
12260                             staticp ? false : inlinep, friendp,
12261                             raises != NULL_TREE);
12262           }
12263       }
12264     else if (TREE_CODE (type) == FUNCTION_TYPE
12265              || TREE_CODE (type) == METHOD_TYPE)
12266       {
12267         tree original_name;
12268         int publicp = 0;
12269
12270         if (!unqualified_id)
12271           return error_mark_node;
12272
12273         if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
12274           original_name = dname;
12275         else
12276           original_name = unqualified_id;
12277         // FIXME:gcc_assert (original_name == dname);
12278
12279         if (storage_class == sc_auto)
12280           error ("storage class %<auto%> invalid for function %qs", name);
12281         else if (storage_class == sc_register)
12282           error ("storage class %<register%> invalid for function %qs", name);
12283         else if (thread_p)
12284           {
12285             if (declspecs->gnu_thread_keyword_p)
12286               error ("storage class %<__thread%> invalid for function %qs",
12287                      name);
12288             else
12289               error ("storage class %<thread_local%> invalid for function %qs",
12290                      name);
12291           }
12292
12293         if (virt_specifiers)
12294           error ("virt-specifiers in %qs not allowed outside a class definition", name);
12295         /* Function declaration not at top level.
12296            Storage classes other than `extern' are not allowed
12297            and `extern' makes no difference.  */
12298         if (! toplevel_bindings_p ()
12299             && (storage_class == sc_static
12300                 || decl_spec_seq_has_spec_p (declspecs, ds_inline))
12301             && pedantic)
12302           {
12303             if (storage_class == sc_static)
12304               pedwarn (input_location, OPT_Wpedantic, 
12305                        "%<static%> specifier invalid for function %qs "
12306                        "declared out of global scope", name);
12307             else
12308               pedwarn (input_location, OPT_Wpedantic, 
12309                        "%<inline%> specifier invalid for function %qs "
12310                        "declared out of global scope", name);
12311           }
12312
12313         if (ctype == NULL_TREE)
12314           {
12315             if (virtualp)
12316               {
12317                 error ("virtual non-class function %qs", name);
12318                 virtualp = 0;
12319               }
12320             else if (sfk == sfk_constructor
12321                      || sfk == sfk_destructor)
12322               {
12323                 error (funcdef_flag
12324                        ? G_("%qs defined in a non-class scope")
12325                        : G_("%qs declared in a non-class scope"), name);
12326                 sfk = sfk_none;
12327               }
12328           }
12329
12330         /* Record whether the function is public.  */
12331         publicp = (ctype != NULL_TREE
12332                    || storage_class != sc_static);
12333
12334         if (late_return_type_p)
12335           TYPE_HAS_LATE_RETURN_TYPE (type) = 1;
12336
12337         decl = grokfndecl (ctype, type, original_name, parms, unqualified_id,
12338                            reqs, virtualp, flags, memfn_quals, rqual, raises,
12339                            1, friendp,
12340                            publicp,
12341                            inlinep | (2 * constexpr_p) | (4 * concept_p),
12342                            initialized == SD_DELETED,
12343                            sfk,
12344                            funcdef_flag,
12345                            template_count, in_namespace, attrlist,
12346                            declarator->id_loc);
12347         if (decl == NULL_TREE)
12348           return error_mark_node;
12349
12350         if (explicitp == 2)
12351           DECL_NONCONVERTING_P (decl) = 1;
12352         if (staticp == 1)
12353           {
12354             int invalid_static = 0;
12355
12356             /* Don't allow a static member function in a class, and forbid
12357                declaring main to be static.  */
12358             if (TREE_CODE (type) == METHOD_TYPE)
12359               {
12360                 permerror (input_location, "cannot declare member function %qD to have "
12361                            "static linkage", decl);
12362                 invalid_static = 1;
12363               }
12364             else if (current_function_decl)
12365               {
12366                 /* 7.1.1: There can be no static function declarations within a
12367                    block.  */
12368                 error ("cannot declare static function inside another function");
12369                 invalid_static = 1;
12370               }
12371
12372             if (invalid_static)
12373               {
12374                 staticp = 0;
12375                 storage_class = sc_none;
12376               }
12377           }
12378       }
12379     else
12380       {
12381         /* It's a variable.  */
12382
12383         /* An uninitialized decl with `extern' is a reference.  */
12384         decl = grokvardecl (type, dname, unqualified_id,
12385                             declspecs,
12386                             initialized,
12387                             type_quals,
12388                             inlinep,
12389                             concept_p,
12390                             template_count,
12391                             ctype ? ctype : in_namespace);
12392         if (decl == NULL_TREE)
12393           return error_mark_node;
12394
12395         bad_specifiers (decl, BSP_VAR, virtualp,
12396                         memfn_quals != TYPE_UNQUALIFIED,
12397                         inlinep, friendp, raises != NULL_TREE);
12398
12399         if (ctype)
12400           {
12401             DECL_CONTEXT (decl) = ctype;
12402             if (staticp == 1)
12403               {
12404                 permerror (input_location, "%<static%> may not be used when defining "
12405                            "(as opposed to declaring) a static data member");
12406                 staticp = 0;
12407                 storage_class = sc_none;
12408               }
12409             if (storage_class == sc_register && TREE_STATIC (decl))
12410               {
12411                 error ("static member %qD declared %<register%>", decl);
12412                 storage_class = sc_none;
12413               }
12414             if (storage_class == sc_extern && pedantic)
12415               {
12416                 pedwarn (input_location, OPT_Wpedantic, 
12417                          "cannot explicitly declare member %q#D to have "
12418                          "extern linkage", decl);
12419                 storage_class = sc_none;
12420               }
12421           }
12422         else if (constexpr_p && DECL_EXTERNAL (decl))
12423           {
12424             error ("declaration of %<constexpr%> variable %qD "
12425                    "is not a definition", decl);
12426             constexpr_p = false;
12427           }
12428
12429         if (inlinep)
12430           mark_inline_variable (decl);
12431         if (innermost_code == cdk_decomp)
12432           {
12433             gcc_assert (declarator && declarator->kind == cdk_decomp);
12434             DECL_SOURCE_LOCATION (decl) = declarator->id_loc;
12435             DECL_ARTIFICIAL (decl) = 1;
12436             fit_decomposition_lang_decl (decl, NULL_TREE);
12437           }
12438       }
12439
12440     if (VAR_P (decl) && !initialized)
12441       if (tree auto_node = type_uses_auto (type))
12442         if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
12443           {
12444             location_t loc = declspecs->locations[ds_type_spec];
12445             error_at (loc, "declaration of %q#D has no initializer", decl);
12446             TREE_TYPE (decl) = error_mark_node;
12447           }
12448
12449     if (storage_class == sc_extern && initialized && !funcdef_flag)
12450       {
12451         if (toplevel_bindings_p ())
12452           {
12453             /* It's common practice (and completely valid) to have a const
12454                be initialized and declared extern.  */
12455             if (!(type_quals & TYPE_QUAL_CONST))
12456               warning (0, "%qs initialized and declared %<extern%>", name);
12457           }
12458         else
12459           {
12460             error ("%qs has both %<extern%> and initializer", name);
12461             return error_mark_node;
12462           }
12463       }
12464
12465     /* Record `register' declaration for warnings on &
12466        and in case doing stupid register allocation.  */
12467
12468     if (storage_class == sc_register)
12469       {
12470         DECL_REGISTER (decl) = 1;
12471         /* Warn about register storage specifiers on PARM_DECLs.  */
12472         if (TREE_CODE (decl) == PARM_DECL)
12473           {
12474             if (cxx_dialect >= cxx17)
12475               pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
12476                        "ISO C++17 does not allow %<register%> storage "
12477                        "class specifier");
12478             else
12479               warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
12480                           "%<register%> storage class specifier used");
12481           }
12482       }
12483     else if (storage_class == sc_extern)
12484       DECL_THIS_EXTERN (decl) = 1;
12485     else if (storage_class == sc_static)
12486       DECL_THIS_STATIC (decl) = 1;
12487
12488     /* Set constexpr flag on vars (functions got it in grokfndecl).  */
12489     if (constexpr_p && VAR_P (decl))
12490       DECL_DECLARED_CONSTEXPR_P (decl) = true;
12491
12492     /* Record constancy and volatility on the DECL itself .  There's
12493        no need to do this when processing a template; we'll do this
12494        for the instantiated declaration based on the type of DECL.  */
12495     if (!processing_template_decl)
12496       cp_apply_type_quals_to_decl (type_quals, decl);
12497
12498     return decl;
12499   }
12500 }
12501 \f
12502 /* Subroutine of start_function.  Ensure that each of the parameter
12503    types (as listed in PARMS) is complete, as is required for a
12504    function definition.  */
12505
12506 static void
12507 require_complete_types_for_parms (tree parms)
12508 {
12509   for (; parms; parms = DECL_CHAIN (parms))
12510     {
12511       if (dependent_type_p (TREE_TYPE (parms)))
12512         continue;
12513       if (!VOID_TYPE_P (TREE_TYPE (parms))
12514           && complete_type_or_else (TREE_TYPE (parms), parms))
12515         {
12516           relayout_decl (parms);
12517           DECL_ARG_TYPE (parms) = type_passed_as (TREE_TYPE (parms));
12518
12519           maybe_warn_parm_abi (TREE_TYPE (parms),
12520                                DECL_SOURCE_LOCATION (parms));
12521         }
12522       else
12523         /* grokparms or complete_type_or_else will have already issued
12524            an error.  */
12525         TREE_TYPE (parms) = error_mark_node;
12526     }
12527 }
12528
12529 /* Returns nonzero if T is a local variable.  */
12530
12531 int
12532 local_variable_p (const_tree t)
12533 {
12534   if ((VAR_P (t)
12535        /* A VAR_DECL with a context that is a _TYPE is a static data
12536           member.  */
12537        && !TYPE_P (CP_DECL_CONTEXT (t))
12538        /* Any other non-local variable must be at namespace scope.  */
12539        && !DECL_NAMESPACE_SCOPE_P (t))
12540       || (TREE_CODE (t) == PARM_DECL))
12541     return 1;
12542
12543   return 0;
12544 }
12545
12546 /* Like local_variable_p, but suitable for use as a tree-walking
12547    function.  */
12548
12549 static tree
12550 local_variable_p_walkfn (tree *tp, int *walk_subtrees,
12551                          void * /*data*/)
12552 {
12553   if (local_variable_p (*tp)
12554       && (!DECL_ARTIFICIAL (*tp) || DECL_NAME (*tp) == this_identifier))
12555     return *tp;
12556   else if (TYPE_P (*tp))
12557     *walk_subtrees = 0;
12558
12559   return NULL_TREE;
12560 }
12561
12562 /* Check that ARG, which is a default-argument expression for a
12563    parameter DECL, is valid.  Returns ARG, or ERROR_MARK_NODE, if
12564    something goes wrong.  DECL may also be a _TYPE node, rather than a
12565    DECL, if there is no DECL available.  */
12566
12567 tree
12568 check_default_argument (tree decl, tree arg, tsubst_flags_t complain)
12569 {
12570   tree var;
12571   tree decl_type;
12572
12573   if (TREE_CODE (arg) == DEFAULT_ARG)
12574     /* We get a DEFAULT_ARG when looking at an in-class declaration
12575        with a default argument.  Ignore the argument for now; we'll
12576        deal with it after the class is complete.  */
12577     return arg;
12578
12579   if (TYPE_P (decl))
12580     {
12581       decl_type = decl;
12582       decl = NULL_TREE;
12583     }
12584   else
12585     decl_type = TREE_TYPE (decl);
12586
12587   if (arg == error_mark_node
12588       || decl == error_mark_node
12589       || TREE_TYPE (arg) == error_mark_node
12590       || decl_type == error_mark_node)
12591     /* Something already went wrong.  There's no need to check
12592        further.  */
12593     return error_mark_node;
12594
12595   /* [dcl.fct.default]
12596
12597      A default argument expression is implicitly converted to the
12598      parameter type.  */
12599   ++cp_unevaluated_operand;
12600   perform_implicit_conversion_flags (decl_type, arg, complain,
12601                                      LOOKUP_IMPLICIT);
12602   --cp_unevaluated_operand;
12603
12604   /* Avoid redundant -Wzero-as-null-pointer-constant warnings at
12605      the call sites.  */
12606   if (TYPE_PTR_OR_PTRMEM_P (decl_type)
12607       && null_ptr_cst_p (arg))
12608     return nullptr_node;
12609
12610   /* [dcl.fct.default]
12611
12612      Local variables shall not be used in default argument
12613      expressions.
12614
12615      The keyword `this' shall not be used in a default argument of a
12616      member function.  */
12617   var = cp_walk_tree_without_duplicates (&arg, local_variable_p_walkfn, NULL);
12618   if (var)
12619     {
12620       if (complain & tf_warning_or_error)
12621         {
12622           if (DECL_NAME (var) == this_identifier)
12623             permerror (input_location, "default argument %qE uses %qD",
12624                        arg, var);
12625           else
12626             error ("default argument %qE uses local variable %qD", arg, var);
12627         }
12628       return error_mark_node;
12629     }
12630
12631   /* All is well.  */
12632   return arg;
12633 }
12634
12635 /* Returns a deprecated type used within TYPE, or NULL_TREE if none.  */
12636
12637 static tree
12638 type_is_deprecated (tree type)
12639 {
12640   enum tree_code code;
12641   if (TREE_DEPRECATED (type))
12642     return type;
12643   if (TYPE_NAME (type))
12644     {
12645       if (TREE_DEPRECATED (TYPE_NAME (type)))
12646         return type;
12647       else
12648         return NULL_TREE;
12649     }
12650
12651   /* Do warn about using typedefs to a deprecated class.  */
12652   if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
12653     return type_is_deprecated (TYPE_MAIN_VARIANT (type));
12654
12655   code = TREE_CODE (type);
12656
12657   if (code == POINTER_TYPE || code == REFERENCE_TYPE
12658       || code == OFFSET_TYPE || code == FUNCTION_TYPE
12659       || code == METHOD_TYPE || code == ARRAY_TYPE)
12660     return type_is_deprecated (TREE_TYPE (type));
12661
12662   if (TYPE_PTRMEMFUNC_P (type))
12663     return type_is_deprecated
12664       (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
12665
12666   return NULL_TREE;
12667 }
12668
12669 /* Decode the list of parameter types for a function type.
12670    Given the list of things declared inside the parens,
12671    return a list of types.
12672
12673    If this parameter does not end with an ellipsis, we append
12674    void_list_node.
12675
12676    *PARMS is set to the chain of PARM_DECLs created.  */
12677
12678 tree
12679 grokparms (tree parmlist, tree *parms)
12680 {
12681   tree result = NULL_TREE;
12682   tree decls = NULL_TREE;
12683   tree parm;
12684   int any_error = 0;
12685
12686   for (parm = parmlist; parm != NULL_TREE; parm = TREE_CHAIN (parm))
12687     {
12688       tree type = NULL_TREE;
12689       tree init = TREE_PURPOSE (parm);
12690       tree decl = TREE_VALUE (parm);
12691
12692       if (parm == void_list_node)
12693         break;
12694
12695       if (! decl || TREE_TYPE (decl) == error_mark_node)
12696         continue;
12697
12698       type = TREE_TYPE (decl);
12699       if (VOID_TYPE_P (type))
12700         {
12701           if (same_type_p (type, void_type_node)
12702               && !init
12703               && !DECL_NAME (decl) && !result
12704               && TREE_CHAIN (parm) == void_list_node)
12705             /* DR 577: A parameter list consisting of a single
12706                unnamed parameter of non-dependent type 'void'.  */
12707             break;
12708           else if (cv_qualified_p (type))
12709             error_at (DECL_SOURCE_LOCATION (decl),
12710                       "invalid use of cv-qualified type %qT in "
12711                       "parameter declaration", type);
12712           else
12713             error_at (DECL_SOURCE_LOCATION (decl),
12714                       "invalid use of type %<void%> in parameter "
12715                       "declaration");
12716           /* It's not a good idea to actually create parameters of
12717              type `void'; other parts of the compiler assume that a
12718              void type terminates the parameter list.  */
12719           type = error_mark_node;
12720           TREE_TYPE (decl) = error_mark_node;
12721         }
12722
12723       if (type != error_mark_node)
12724         {
12725           if (deprecated_state != DEPRECATED_SUPPRESS)
12726             {
12727               tree deptype = type_is_deprecated (type);
12728               if (deptype)
12729                 warn_deprecated_use (deptype, NULL_TREE);
12730             }
12731
12732           /* Top-level qualifiers on the parameters are
12733              ignored for function types.  */
12734           type = cp_build_qualified_type (type, 0);
12735           if (TREE_CODE (type) == METHOD_TYPE)
12736             {
12737               error ("parameter %qD invalidly declared method type", decl);
12738               type = build_pointer_type (type);
12739               TREE_TYPE (decl) = type;
12740             }
12741           else if (abstract_virtuals_error (decl, type))
12742             any_error = 1;  /* Seems like a good idea.  */
12743           else if (cxx_dialect < cxx17 && POINTER_TYPE_P (type))
12744             {
12745               /* Before C++17 DR 393:
12746                  [dcl.fct]/6, parameter types cannot contain pointers
12747                  (references) to arrays of unknown bound.  */
12748               tree t = TREE_TYPE (type);
12749               int ptr = TYPE_PTR_P (type);
12750
12751               while (1)
12752                 {
12753                   if (TYPE_PTR_P (t))
12754                     ptr = 1;
12755                   else if (TREE_CODE (t) != ARRAY_TYPE)
12756                     break;
12757                   else if (!TYPE_DOMAIN (t))
12758                     break;
12759                   t = TREE_TYPE (t);
12760                 }
12761               if (TREE_CODE (t) == ARRAY_TYPE)
12762                 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
12763                          ptr
12764                          ? G_("parameter %qD includes pointer to array of "
12765                               "unknown bound %qT")
12766                          : G_("parameter %qD includes reference to array of "
12767                               "unknown bound %qT"),
12768                          decl, t);
12769             }
12770
12771           if (any_error)
12772             init = NULL_TREE;
12773           else if (init && !processing_template_decl)
12774             init = check_default_argument (decl, init, tf_warning_or_error);
12775         }
12776
12777       DECL_CHAIN (decl) = decls;
12778       decls = decl;
12779       result = tree_cons (init, type, result);
12780     }
12781   decls = nreverse (decls);
12782   result = nreverse (result);
12783   if (parm)
12784     result = chainon (result, void_list_node);
12785   *parms = decls;
12786
12787   return result;
12788 }
12789
12790 \f
12791 /* D is a constructor or overloaded `operator='.
12792
12793    Let T be the class in which D is declared. Then, this function
12794    returns:
12795
12796    -1 if D's is an ill-formed constructor or copy assignment operator
12797       whose first parameter is of type `T'.
12798    0  if D is not a copy constructor or copy assignment
12799       operator.
12800    1  if D is a copy constructor or copy assignment operator whose
12801       first parameter is a reference to non-const qualified T.
12802    2  if D is a copy constructor or copy assignment operator whose
12803       first parameter is a reference to const qualified T.
12804
12805    This function can be used as a predicate. Positive values indicate
12806    a copy constructor and nonzero values indicate a copy assignment
12807    operator.  */
12808
12809 int
12810 copy_fn_p (const_tree d)
12811 {
12812   tree args;
12813   tree arg_type;
12814   int result = 1;
12815
12816   gcc_assert (DECL_FUNCTION_MEMBER_P (d));
12817
12818   if (TREE_CODE (d) == TEMPLATE_DECL
12819       || (DECL_TEMPLATE_INFO (d)
12820           && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
12821     /* Instantiations of template member functions are never copy
12822        functions.  Note that member functions of templated classes are
12823        represented as template functions internally, and we must
12824        accept those as copy functions.  */
12825     return 0;
12826
12827   args = FUNCTION_FIRST_USER_PARMTYPE (d);
12828   if (!args)
12829     return 0;
12830
12831   arg_type = TREE_VALUE (args);
12832   if (arg_type == error_mark_node)
12833     return 0;
12834
12835   if (TYPE_MAIN_VARIANT (arg_type) == DECL_CONTEXT (d))
12836     {
12837       /* Pass by value copy assignment operator.  */
12838       result = -1;
12839     }
12840   else if (TREE_CODE (arg_type) == REFERENCE_TYPE
12841            && !TYPE_REF_IS_RVALUE (arg_type)
12842            && TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)) == DECL_CONTEXT (d))
12843     {
12844       if (CP_TYPE_CONST_P (TREE_TYPE (arg_type)))
12845         result = 2;
12846     }
12847   else
12848     return 0;
12849
12850   args = TREE_CHAIN (args);
12851
12852   if (args && args != void_list_node && !TREE_PURPOSE (args))
12853     /* There are more non-optional args.  */
12854     return 0;
12855
12856   return result;
12857 }
12858
12859 /* D is a constructor or overloaded `operator='.
12860
12861    Let T be the class in which D is declared. Then, this function
12862    returns true when D is a move constructor or move assignment
12863    operator, false otherwise.  */
12864
12865 bool
12866 move_fn_p (const_tree d)
12867 {
12868   gcc_assert (DECL_FUNCTION_MEMBER_P (d));
12869
12870   if (cxx_dialect == cxx98)
12871     /* There are no move constructors if we are in C++98 mode.  */
12872     return false;
12873
12874   if (TREE_CODE (d) == TEMPLATE_DECL
12875       || (DECL_TEMPLATE_INFO (d)
12876          && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
12877     /* Instantiations of template member functions are never move
12878        functions.  Note that member functions of templated classes are
12879        represented as template functions internally, and we must
12880        accept those as move functions.  */
12881     return 0;
12882
12883   return move_signature_fn_p (d);
12884 }
12885
12886 /* D is a constructor or overloaded `operator='.
12887
12888    Then, this function returns true when D has the same signature as a move
12889    constructor or move assignment operator (because either it is such a
12890    ctor/op= or it is a template specialization with the same signature),
12891    false otherwise.  */
12892
12893 bool
12894 move_signature_fn_p (const_tree d)
12895 {
12896   tree args;
12897   tree arg_type;
12898   bool result = false;
12899
12900   args = FUNCTION_FIRST_USER_PARMTYPE (d);
12901   if (!args)
12902     return 0;
12903
12904   arg_type = TREE_VALUE (args);
12905   if (arg_type == error_mark_node)
12906     return 0;
12907
12908   if (TREE_CODE (arg_type) == REFERENCE_TYPE
12909       && TYPE_REF_IS_RVALUE (arg_type)
12910       && same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)),
12911                       DECL_CONTEXT (d)))
12912     result = true;
12913
12914   args = TREE_CHAIN (args);
12915
12916   if (args && args != void_list_node && !TREE_PURPOSE (args))
12917     /* There are more non-optional args.  */
12918     return false;
12919
12920   return result;
12921 }
12922
12923 /* Remember any special properties of member function DECL.  */
12924
12925 void
12926 grok_special_member_properties (tree decl)
12927 {
12928   tree class_type;
12929
12930   if (!DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
12931     return;
12932
12933   class_type = DECL_CONTEXT (decl);
12934   if (IDENTIFIER_CTOR_P (DECL_NAME (decl)))
12935     {
12936       int ctor = copy_fn_p (decl);
12937
12938       if (!DECL_ARTIFICIAL (decl))
12939         TYPE_HAS_USER_CONSTRUCTOR (class_type) = 1;
12940
12941       if (ctor > 0)
12942         {
12943           /* [class.copy]
12944
12945              A non-template constructor for class X is a copy
12946              constructor if its first parameter is of type X&, const
12947              X&, volatile X& or const volatile X&, and either there
12948              are no other parameters or else all other parameters have
12949              default arguments.  */
12950           TYPE_HAS_COPY_CTOR (class_type) = 1;
12951           if (user_provided_p (decl))
12952             TYPE_HAS_COMPLEX_COPY_CTOR (class_type) = 1;
12953           if (ctor > 1)
12954             TYPE_HAS_CONST_COPY_CTOR (class_type) = 1;
12955         }
12956       else if (sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (decl)))
12957         TYPE_HAS_DEFAULT_CONSTRUCTOR (class_type) = 1;
12958       else if (move_fn_p (decl) && user_provided_p (decl))
12959         TYPE_HAS_COMPLEX_MOVE_CTOR (class_type) = 1;
12960       else if (is_list_ctor (decl))
12961         TYPE_HAS_LIST_CTOR (class_type) = 1;
12962
12963       if (DECL_DECLARED_CONSTEXPR_P (decl)
12964           && !ctor && !move_fn_p (decl))
12965         TYPE_HAS_CONSTEXPR_CTOR (class_type) = 1;
12966     }
12967   else if (DECL_NAME (decl) == assign_op_identifier)
12968     {
12969       /* [class.copy]
12970
12971          A non-template assignment operator for class X is a copy
12972          assignment operator if its parameter is of type X, X&, const
12973          X&, volatile X& or const volatile X&.  */
12974
12975       int assop = copy_fn_p (decl);
12976
12977       if (assop)
12978         {
12979           TYPE_HAS_COPY_ASSIGN (class_type) = 1;
12980           if (user_provided_p (decl))
12981             TYPE_HAS_COMPLEX_COPY_ASSIGN (class_type) = 1;
12982           if (assop != 1)
12983             TYPE_HAS_CONST_COPY_ASSIGN (class_type) = 1;
12984         }
12985       else if (move_fn_p (decl) && user_provided_p (decl))
12986         TYPE_HAS_COMPLEX_MOVE_ASSIGN (class_type) = 1;
12987     }
12988   else if (IDENTIFIER_CONV_OP_P (DECL_NAME (decl)))
12989     TYPE_HAS_CONVERSION (class_type) = true;
12990   
12991   /* Destructors are handled in check_methods.  */
12992 }
12993
12994 /* Check a constructor DECL has the correct form.  Complains
12995    if the class has a constructor of the form X(X).  */
12996
12997 bool
12998 grok_ctor_properties (const_tree ctype, const_tree decl)
12999 {
13000   int ctor_parm = copy_fn_p (decl);
13001
13002   if (ctor_parm < 0)
13003     {
13004       /* [class.copy]
13005
13006          A declaration of a constructor for a class X is ill-formed if
13007          its first parameter is of type (optionally cv-qualified) X
13008          and either there are no other parameters or else all other
13009          parameters have default arguments.
13010
13011          We *don't* complain about member template instantiations that
13012          have this form, though; they can occur as we try to decide
13013          what constructor to use during overload resolution.  Since
13014          overload resolution will never prefer such a constructor to
13015          the non-template copy constructor (which is either explicitly
13016          or implicitly defined), there's no need to worry about their
13017          existence.  Theoretically, they should never even be
13018          instantiated, but that's hard to forestall.  */
13019       error ("invalid constructor; you probably meant %<%T (const %T&)%>",
13020                 ctype, ctype);
13021       return false;
13022     }
13023
13024   return true;
13025 }
13026
13027 /* DECL is a declaration for an overloaded or conversion operator.  If
13028    COMPLAIN is true, errors are issued for invalid declarations.  */
13029
13030 bool
13031 grok_op_properties (tree decl, bool complain)
13032 {
13033   tree argtypes = TYPE_ARG_TYPES (TREE_TYPE (decl));
13034   bool methodp = TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE;
13035   tree name = DECL_NAME (decl);
13036
13037   tree class_type = DECL_CONTEXT (decl);
13038   if (class_type && !CLASS_TYPE_P (class_type))
13039     class_type = NULL_TREE;
13040
13041   tree_code operator_code;
13042   unsigned op_flags;
13043   if (IDENTIFIER_CONV_OP_P (name))
13044     {
13045       /* Conversion operators are TYPE_EXPR for the purposes of this
13046          function.  */
13047       operator_code = TYPE_EXPR;
13048       op_flags = OVL_OP_FLAG_UNARY;
13049     }
13050   else
13051     {
13052       const ovl_op_info_t *ovl_op = IDENTIFIER_OVL_OP_INFO (name);
13053
13054       operator_code = ovl_op->tree_code;
13055       op_flags = ovl_op->flags;
13056       gcc_checking_assert (operator_code != ERROR_MARK);
13057       DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
13058     }
13059
13060   if (op_flags & OVL_OP_FLAG_ALLOC)
13061     {
13062       /* operator new and operator delete are quite special.  */
13063       if (class_type)
13064         switch (op_flags)
13065           {
13066           case OVL_OP_FLAG_ALLOC:
13067             TYPE_HAS_NEW_OPERATOR (class_type) = 1;
13068             break;
13069
13070           case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE:
13071             TYPE_GETS_DELETE (class_type) |= 1;
13072             break;
13073
13074           case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_VEC:
13075             TYPE_HAS_ARRAY_NEW_OPERATOR (class_type) = 1;
13076             break;
13077
13078           case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE | OVL_OP_FLAG_VEC:
13079             TYPE_GETS_DELETE (class_type) |= 2;
13080             break;
13081
13082           default:
13083             gcc_unreachable ();
13084           }
13085
13086       /* [basic.std.dynamic.allocation]/1:
13087
13088          A program is ill-formed if an allocation function is declared
13089          in a namespace scope other than global scope or declared
13090          static in global scope.
13091
13092          The same also holds true for deallocation functions.  */
13093       if (DECL_NAMESPACE_SCOPE_P (decl))
13094         {
13095           if (CP_DECL_CONTEXT (decl) != global_namespace)
13096             {
13097               error ("%qD may not be declared within a namespace", decl);
13098               return false;
13099             }
13100
13101           if (!TREE_PUBLIC (decl))
13102             {
13103               error ("%qD may not be declared as static", decl);
13104               return false;
13105             }
13106         }
13107
13108       if (op_flags & OVL_OP_FLAG_DELETE)
13109         TREE_TYPE (decl) = coerce_delete_type (TREE_TYPE (decl));
13110       else
13111         {
13112           DECL_IS_OPERATOR_NEW (decl) = 1;
13113           TREE_TYPE (decl) = coerce_new_type (TREE_TYPE (decl));
13114         }
13115
13116       return true;
13117     }
13118
13119   /* An operator function must either be a non-static member function
13120      or have at least one parameter of a class, a reference to a class,
13121      an enumeration, or a reference to an enumeration.  13.4.0.6 */
13122   if (! methodp || DECL_STATIC_FUNCTION_P (decl))
13123     {
13124       if (operator_code == TYPE_EXPR
13125           || operator_code == CALL_EXPR
13126           || operator_code == COMPONENT_REF
13127           || operator_code == ARRAY_REF
13128           || operator_code == NOP_EXPR)
13129         {
13130           error ("%qD must be a nonstatic member function", decl);
13131           return false;
13132         }
13133
13134       if (DECL_STATIC_FUNCTION_P (decl))
13135         {
13136           error ("%qD must be either a non-static member "
13137                  "function or a non-member function", decl);
13138           return false;
13139         }
13140
13141       for (tree arg = argtypes; ; arg = TREE_CHAIN (arg))
13142         {
13143           if (!arg || arg == void_list_node)
13144             {
13145               if (complain)
13146                 error ("%qD must have an argument of class or "
13147                        "enumerated type", decl);
13148               return false;
13149             }
13150       
13151           tree type = non_reference (TREE_VALUE (arg));
13152           if (type == error_mark_node)
13153             return false;
13154           
13155           /* MAYBE_CLASS_TYPE_P, rather than CLASS_TYPE_P, is used
13156              because these checks are performed even on template
13157              functions.  */
13158           if (MAYBE_CLASS_TYPE_P (type)
13159               || TREE_CODE (type) == ENUMERAL_TYPE)
13160             break;
13161         }
13162     }
13163
13164   if (operator_code == CALL_EXPR)
13165     /* There are no further restrictions on the arguments to an overloaded
13166        "operator ()".  */
13167     return true;
13168
13169   if (operator_code == COND_EXPR)
13170     {
13171       /* 13.4.0.3 */
13172       error ("ISO C++ prohibits overloading operator ?:");
13173       return false;
13174     }
13175
13176   /* Count the number of arguments and check for ellipsis.  */
13177   int arity = 0;
13178   for (tree arg = argtypes; arg != void_list_node; arg = TREE_CHAIN (arg))
13179     {
13180       if (!arg)
13181         {
13182           /* Variadic.  */
13183           error ("%qD must not have variable number of arguments", decl);
13184           return false;
13185         }
13186       ++arity;
13187     }
13188
13189   /* Verify correct number of arguments.  */
13190   switch (op_flags)
13191     {
13192     case OVL_OP_FLAG_AMBIARY:
13193       if (arity == 1)
13194         {
13195           /* We have a unary instance of an ambi-ary op.  Remap to the
13196              unary one.  */
13197           unsigned alt = ovl_op_alternate[ovl_op_mapping [operator_code]];
13198           const ovl_op_info_t *ovl_op = &ovl_op_info[false][alt];
13199           gcc_checking_assert (ovl_op->flags == OVL_OP_FLAG_UNARY);
13200           operator_code = ovl_op->tree_code;
13201           DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
13202         }
13203       else if (arity != 2)
13204         {
13205           /* This was an ambiguous operator but is invalid. */
13206           error (methodp
13207                  ? G_("%qD must have either zero or one argument")
13208                  : G_("%qD must have either one or two arguments"), decl);
13209           return false;
13210         }
13211       else if ((operator_code == POSTINCREMENT_EXPR
13212                 || operator_code == POSTDECREMENT_EXPR)
13213                && ! processing_template_decl
13214                /* x++ and x--'s second argument must be an int.  */
13215                && ! same_type_p (TREE_VALUE (TREE_CHAIN (argtypes)),
13216                                  integer_type_node))
13217         {
13218           error (methodp
13219                  ? G_("postfix %qD must have %<int%> as its argument")
13220                  : G_("postfix %qD must have %<int%> as its second argument"),
13221                  decl);
13222           return false;
13223         }
13224       break;
13225
13226     case OVL_OP_FLAG_UNARY:
13227       if (arity != 1)
13228         {
13229           error (methodp
13230                  ? G_("%qD must have no arguments")
13231                  : G_("%qD must have exactly one argument"), decl);
13232           return false;
13233         }
13234       break;
13235
13236     case OVL_OP_FLAG_BINARY:
13237       if (arity != 2)
13238         {
13239           error (methodp
13240                  ? G_("%qD must have exactly one argument")
13241                  : G_("%qD must have exactly two arguments"), decl);
13242           return false;
13243         }
13244       break;
13245
13246     default:
13247       gcc_unreachable ();
13248     }
13249
13250   /* There can be no default arguments.  */
13251   for (tree arg = argtypes; arg != void_list_node; arg = TREE_CHAIN (arg))
13252     if (TREE_PURPOSE (arg))
13253       {
13254         TREE_PURPOSE (arg) = NULL_TREE;
13255         if (operator_code == POSTINCREMENT_EXPR
13256             || operator_code == POSTDECREMENT_EXPR)
13257           pedwarn (input_location, OPT_Wpedantic,
13258                    "%qD cannot have default arguments", decl);
13259         else
13260           {
13261             error ("%qD cannot have default arguments", decl);
13262             return false;
13263           }
13264       }
13265
13266   /* At this point the declaration is well-formed.  It may not be
13267      sensible though.  */
13268
13269   /* Check member function warnings only on the in-class declaration.
13270      There's no point warning on an out-of-class definition.  */
13271   if (class_type && class_type != current_class_type)
13272     return true;
13273
13274   /* Warn about conversion operators that will never be used.  */
13275   if (IDENTIFIER_CONV_OP_P (name)
13276       && ! DECL_TEMPLATE_INFO (decl)
13277       && warn_conversion)
13278     {
13279       tree t = TREE_TYPE (name);
13280       int ref = (TREE_CODE (t) == REFERENCE_TYPE);
13281
13282       if (ref)
13283         t = TYPE_MAIN_VARIANT (TREE_TYPE (t));
13284
13285       if (VOID_TYPE_P (t))
13286         warning (OPT_Wconversion,
13287                  ref
13288                  ? G_("conversion to a reference to void "
13289                       "will never use a type conversion operator")
13290                  : G_("conversion to void "
13291                       "will never use a type conversion operator"));
13292       else if (class_type)
13293         {
13294           if (t == class_type)
13295             warning (OPT_Wconversion,
13296                      ref
13297                      ? G_("conversion to a reference to the same type "
13298                           "will never use a type conversion operator")
13299                      : G_("conversion to the same type "
13300                           "will never use a type conversion operator"));
13301           /* Don't force t to be complete here.  */
13302           else if (MAYBE_CLASS_TYPE_P (t)
13303                    && COMPLETE_TYPE_P (t)
13304                    && DERIVED_FROM_P (t, class_type))
13305             warning (OPT_Wconversion,
13306                      ref
13307                      ? G_("conversion to a reference to a base class "
13308                           "will never use a type conversion operator")
13309                      : G_("conversion to a base class "
13310                           "will never use a type conversion operator"));
13311         }
13312     }
13313
13314   if (!warn_ecpp)
13315     return true;
13316
13317   /* Effective C++ rules below.  */
13318
13319   /* More Effective C++ rule 7.  */
13320   if (operator_code == TRUTH_ANDIF_EXPR
13321       || operator_code == TRUTH_ORIF_EXPR
13322       || operator_code == COMPOUND_EXPR)
13323     warning (OPT_Weffc__,
13324              "user-defined %qD always evaluates both arguments", decl);
13325   
13326   /* More Effective C++ rule 6.  */
13327   if (operator_code == POSTINCREMENT_EXPR
13328       || operator_code == POSTDECREMENT_EXPR
13329       || operator_code == PREINCREMENT_EXPR
13330       || operator_code == PREDECREMENT_EXPR)
13331     {
13332       tree arg = TREE_VALUE (argtypes);
13333       tree ret = TREE_TYPE (TREE_TYPE (decl));
13334       if (methodp || TREE_CODE (arg) == REFERENCE_TYPE)
13335         arg = TREE_TYPE (arg);
13336       arg = TYPE_MAIN_VARIANT (arg);
13337
13338       if (operator_code == PREINCREMENT_EXPR
13339           || operator_code == PREDECREMENT_EXPR)
13340         {
13341           if (TREE_CODE (ret) != REFERENCE_TYPE
13342               || !same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (ret)), arg))
13343             warning (OPT_Weffc__, "prefix %qD should return %qT", decl,
13344                      build_reference_type (arg));
13345         }
13346       else
13347         {
13348           if (!same_type_p (TYPE_MAIN_VARIANT (ret), arg))
13349             warning (OPT_Weffc__, "postfix %qD should return %qT", decl, arg);
13350         }
13351     }
13352
13353   /* Effective C++ rule 23.  */
13354   if (!DECL_ASSIGNMENT_OPERATOR_P (decl)
13355       && (operator_code == PLUS_EXPR
13356           || operator_code == MINUS_EXPR
13357           || operator_code == TRUNC_DIV_EXPR
13358           || operator_code == MULT_EXPR
13359           || operator_code == TRUNC_MOD_EXPR)
13360       && TREE_CODE (TREE_TYPE (TREE_TYPE (decl))) == REFERENCE_TYPE)
13361     warning (OPT_Weffc__, "%qD should return by value", decl);
13362
13363   return true;
13364 }
13365 \f
13366 /* Return a string giving the keyword associate with CODE.  */
13367
13368 static const char *
13369 tag_name (enum tag_types code)
13370 {
13371   switch (code)
13372     {
13373     case record_type:
13374       return "struct";
13375     case class_type:
13376       return "class";
13377     case union_type:
13378       return "union";
13379     case enum_type:
13380       return "enum";
13381     case typename_type:
13382       return "typename";
13383     default:
13384       gcc_unreachable ();
13385     }
13386 }
13387
13388 /* Name lookup in an elaborated-type-specifier (after the keyword
13389    indicated by TAG_CODE) has found the TYPE_DECL DECL.  If the
13390    elaborated-type-specifier is invalid, issue a diagnostic and return
13391    error_mark_node; otherwise, return the *_TYPE to which it referred.
13392    If ALLOW_TEMPLATE_P is true, TYPE may be a class template.  */
13393
13394 tree
13395 check_elaborated_type_specifier (enum tag_types tag_code,
13396                                  tree decl,
13397                                  bool allow_template_p)
13398 {
13399   tree type;
13400
13401   /* In the case of:
13402
13403        struct S { struct S *p; };
13404
13405      name lookup will find the TYPE_DECL for the implicit "S::S"
13406      typedef.  Adjust for that here.  */
13407   if (DECL_SELF_REFERENCE_P (decl))
13408     decl = TYPE_NAME (TREE_TYPE (decl));
13409
13410   type = TREE_TYPE (decl);
13411
13412   /* Check TEMPLATE_TYPE_PARM first because DECL_IMPLICIT_TYPEDEF_P
13413      is false for this case as well.  */
13414   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
13415     {
13416       error ("using template type parameter %qT after %qs",
13417              type, tag_name (tag_code));
13418       return error_mark_node;
13419     }
13420   /* Accept template template parameters.  */
13421   else if (allow_template_p
13422            && (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
13423                || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM))
13424     ;
13425   /*   [dcl.type.elab]
13426
13427        If the identifier resolves to a typedef-name or the
13428        simple-template-id resolves to an alias template
13429        specialization, the elaborated-type-specifier is ill-formed.
13430
13431      In other words, the only legitimate declaration to use in the
13432      elaborated type specifier is the implicit typedef created when
13433      the type is declared.  */
13434   else if (!DECL_IMPLICIT_TYPEDEF_P (decl)
13435            && !DECL_SELF_REFERENCE_P (decl)
13436            && tag_code != typename_type)
13437     {
13438       if (alias_template_specialization_p (type))
13439         error ("using alias template specialization %qT after %qs",
13440                type, tag_name (tag_code));
13441       else
13442         error ("using typedef-name %qD after %qs", decl, tag_name (tag_code));
13443       inform (DECL_SOURCE_LOCATION (decl),
13444               "%qD has a previous declaration here", decl);
13445       return error_mark_node;
13446     }
13447   else if (TREE_CODE (type) != RECORD_TYPE
13448            && TREE_CODE (type) != UNION_TYPE
13449            && tag_code != enum_type
13450            && tag_code != typename_type)
13451     {
13452       error ("%qT referred to as %qs", type, tag_name (tag_code));
13453       inform (location_of (type), "%qT has a previous declaration here", type);
13454       return error_mark_node;
13455     }
13456   else if (TREE_CODE (type) != ENUMERAL_TYPE
13457            && tag_code == enum_type)
13458     {
13459       error ("%qT referred to as enum", type);
13460       inform (location_of (type), "%qT has a previous declaration here", type);
13461       return error_mark_node;
13462     }
13463   else if (!allow_template_p
13464            && TREE_CODE (type) == RECORD_TYPE
13465            && CLASSTYPE_IS_TEMPLATE (type))
13466     {
13467       /* If a class template appears as elaborated type specifier
13468          without a template header such as:
13469
13470            template <class T> class C {};
13471            void f(class C);             // No template header here
13472
13473          then the required template argument is missing.  */
13474       error ("template argument required for %<%s %T%>",
13475              tag_name (tag_code),
13476              DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)));
13477       return error_mark_node;
13478     }
13479
13480   return type;
13481 }
13482
13483 /* Lookup NAME in elaborate type specifier in scope according to
13484    SCOPE and issue diagnostics if necessary.
13485    Return *_TYPE node upon success, NULL_TREE when the NAME is not
13486    found, and ERROR_MARK_NODE for type error.  */
13487
13488 static tree
13489 lookup_and_check_tag (enum tag_types tag_code, tree name,
13490                       tag_scope scope, bool template_header_p)
13491 {
13492   tree t;
13493   tree decl;
13494   if (scope == ts_global)
13495     {
13496       /* First try ordinary name lookup, ignoring hidden class name
13497          injected via friend declaration.  */
13498       decl = lookup_name_prefer_type (name, 2);
13499       decl = strip_using_decl (decl);
13500       /* If that fails, the name will be placed in the smallest
13501          non-class, non-function-prototype scope according to 3.3.1/5.
13502          We may already have a hidden name declared as friend in this
13503          scope.  So lookup again but not ignoring hidden names.
13504          If we find one, that name will be made visible rather than
13505          creating a new tag.  */
13506       if (!decl)
13507         decl = lookup_type_scope (name, ts_within_enclosing_non_class);
13508     }
13509   else
13510     decl = lookup_type_scope (name, scope);
13511
13512   if (decl
13513       && (DECL_CLASS_TEMPLATE_P (decl)
13514           /* If scope is ts_current we're defining a class, so ignore a
13515              template template parameter.  */
13516           || (scope != ts_current
13517               && DECL_TEMPLATE_TEMPLATE_PARM_P (decl))))
13518     decl = DECL_TEMPLATE_RESULT (decl);
13519
13520   if (decl && TREE_CODE (decl) == TYPE_DECL)
13521     {
13522       /* Look for invalid nested type:
13523            class C {
13524              class C {};
13525            };  */
13526       if (scope == ts_current && DECL_SELF_REFERENCE_P (decl))
13527         {
13528           error ("%qD has the same name as the class in which it is "
13529                  "declared",
13530                  decl);
13531           return error_mark_node;
13532         }
13533
13534       /* Two cases we need to consider when deciding if a class
13535          template is allowed as an elaborated type specifier:
13536          1. It is a self reference to its own class.
13537          2. It comes with a template header.
13538
13539          For example:
13540
13541            template <class T> class C {
13542              class C *c1;               // DECL_SELF_REFERENCE_P is true
13543              class D;
13544            };
13545            template <class U> class C; // template_header_p is true
13546            template <class T> class C<T>::D {
13547              class C *c2;               // DECL_SELF_REFERENCE_P is true
13548            };  */
13549
13550       t = check_elaborated_type_specifier (tag_code,
13551                                            decl,
13552                                            template_header_p
13553                                            | DECL_SELF_REFERENCE_P (decl));
13554       if (template_header_p && t && CLASS_TYPE_P (t)
13555           && (!CLASSTYPE_TEMPLATE_INFO (t)
13556               || (!PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))))
13557         {
13558           error ("%qT is not a template", t);
13559           inform (location_of (t), "previous declaration here");
13560           if (TYPE_CLASS_SCOPE_P (t)
13561               && CLASSTYPE_TEMPLATE_INFO (TYPE_CONTEXT (t)))
13562             inform (input_location,
13563                     "perhaps you want to explicitly add %<%T::%>",
13564                     TYPE_CONTEXT (t));
13565           t = error_mark_node;
13566         }
13567
13568       return t;
13569     }
13570   else if (decl && TREE_CODE (decl) == TREE_LIST)
13571     {
13572       error ("reference to %qD is ambiguous", name);
13573       print_candidates (decl);
13574       return error_mark_node;
13575     }
13576   else
13577     return NULL_TREE;
13578 }
13579
13580 /* Get the struct, enum or union (TAG_CODE says which) with tag NAME.
13581    Define the tag as a forward-reference if it is not defined.
13582
13583    If a declaration is given, process it here, and report an error if
13584    multiple declarations are not identical.
13585
13586    SCOPE is TS_CURRENT when this is also a definition.  Only look in
13587    the current frame for the name (since C++ allows new names in any
13588    scope.)  It is TS_WITHIN_ENCLOSING_NON_CLASS if this is a friend
13589    declaration.  Only look beginning from the current scope outward up
13590    till the nearest non-class scope.  Otherwise it is TS_GLOBAL.
13591
13592    TEMPLATE_HEADER_P is true when this declaration is preceded by
13593    a set of template parameters.  */
13594
13595 static tree
13596 xref_tag_1 (enum tag_types tag_code, tree name,
13597             tag_scope scope, bool template_header_p)
13598 {
13599   enum tree_code code;
13600   tree context = NULL_TREE;
13601
13602   gcc_assert (identifier_p (name));
13603
13604   switch (tag_code)
13605     {
13606     case record_type:
13607     case class_type:
13608       code = RECORD_TYPE;
13609       break;
13610     case union_type:
13611       code = UNION_TYPE;
13612       break;
13613     case enum_type:
13614       code = ENUMERAL_TYPE;
13615       break;
13616     default:
13617       gcc_unreachable ();
13618     }
13619
13620   /* In case of anonymous name, xref_tag is only called to
13621      make type node and push name.  Name lookup is not required.  */
13622   tree t = NULL_TREE;
13623   if (scope != ts_lambda && !anon_aggrname_p (name))
13624     t = lookup_and_check_tag  (tag_code, name, scope, template_header_p);
13625   
13626   if (t == error_mark_node)
13627     return error_mark_node;
13628
13629   if (scope != ts_current && t && current_class_type
13630       && template_class_depth (current_class_type)
13631       && template_header_p)
13632     {
13633       if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
13634         return t;
13635
13636       /* Since SCOPE is not TS_CURRENT, we are not looking at a
13637          definition of this tag.  Since, in addition, we are currently
13638          processing a (member) template declaration of a template
13639          class, we must be very careful; consider:
13640
13641            template <class X> struct S1
13642
13643            template <class U> struct S2
13644            {
13645              template <class V> friend struct S1;
13646            };
13647
13648          Here, the S2::S1 declaration should not be confused with the
13649          outer declaration.  In particular, the inner version should
13650          have a template parameter of level 2, not level 1.
13651
13652          On the other hand, when presented with:
13653
13654            template <class T> struct S1
13655            {
13656              template <class U> struct S2 {};
13657              template <class U> friend struct S2;
13658            };
13659
13660          the friend must find S1::S2 eventually.  We accomplish this
13661          by making sure that the new type we create to represent this
13662          declaration has the right TYPE_CONTEXT.  */
13663       context = TYPE_CONTEXT (t);
13664       t = NULL_TREE;
13665     }
13666
13667   if (! t)
13668     {
13669       /* If no such tag is yet defined, create a forward-reference node
13670          and record it as the "definition".
13671          When a real declaration of this type is found,
13672          the forward-reference will be altered into a real type.  */
13673       if (code == ENUMERAL_TYPE)
13674         {
13675           error ("use of enum %q#D without previous declaration", name);
13676           return error_mark_node;
13677         }
13678       else
13679         {
13680           t = make_class_type (code);
13681           TYPE_CONTEXT (t) = context;
13682           if (scope == ts_lambda)
13683             {
13684               /* Mark it as a lambda type.  */
13685               CLASSTYPE_LAMBDA_EXPR (t) = error_mark_node;
13686               /* And push it into current scope.  */
13687               scope = ts_current;
13688             }
13689           t = pushtag (name, t, scope);
13690         }
13691     }
13692   else
13693     {
13694       if (template_header_p && MAYBE_CLASS_TYPE_P (t))
13695         {
13696           /* Check that we aren't trying to overload a class with different
13697              constraints.  */
13698           tree constr = NULL_TREE;
13699           if (current_template_parms)
13700             {
13701               tree reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
13702               constr = build_constraints (reqs, NULL_TREE);
13703             }
13704           if (!redeclare_class_template (t, current_template_parms, constr))
13705             return error_mark_node;
13706         }
13707       else if (!processing_template_decl
13708                && CLASS_TYPE_P (t)
13709                && CLASSTYPE_IS_TEMPLATE (t))
13710         {
13711           error ("redeclaration of %qT as a non-template", t);
13712           inform (location_of (t), "previous declaration %qD", t);
13713           return error_mark_node;
13714         }
13715
13716       if (scope != ts_within_enclosing_non_class && TYPE_HIDDEN_P (t))
13717         {
13718           /* This is no longer an invisible friend.  Make it
13719              visible.  */
13720           tree decl = TYPE_NAME (t);
13721
13722           DECL_ANTICIPATED (decl) = false;
13723           DECL_FRIEND_P (decl) = false;
13724
13725           if (TYPE_TEMPLATE_INFO (t))
13726             {
13727               tree tmpl = TYPE_TI_TEMPLATE (t);
13728               DECL_ANTICIPATED (tmpl) = false;
13729               DECL_FRIEND_P (tmpl) = false;
13730             }
13731         }
13732     }
13733
13734   return t;
13735 }
13736
13737 /* Wrapper for xref_tag_1.  */
13738
13739 tree
13740 xref_tag (enum tag_types tag_code, tree name,
13741           tag_scope scope, bool template_header_p)
13742 {
13743   tree ret;
13744   bool subtime;
13745   subtime = timevar_cond_start (TV_NAME_LOOKUP);
13746   ret = xref_tag_1 (tag_code, name, scope, template_header_p);
13747   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
13748   return ret;
13749 }
13750
13751
13752 tree
13753 xref_tag_from_type (tree old, tree id, tag_scope scope)
13754 {
13755   enum tag_types tag_kind;
13756
13757   if (TREE_CODE (old) == RECORD_TYPE)
13758     tag_kind = (CLASSTYPE_DECLARED_CLASS (old) ? class_type : record_type);
13759   else
13760     tag_kind  = union_type;
13761
13762   if (id == NULL_TREE)
13763     id = TYPE_IDENTIFIER (old);
13764
13765   return xref_tag (tag_kind, id, scope, false);
13766 }
13767
13768 /* Create the binfo hierarchy for REF with (possibly NULL) base list
13769    BASE_LIST.  For each element on BASE_LIST the TREE_PURPOSE is an
13770    access_* node, and the TREE_VALUE is the type of the base-class.
13771    Non-NULL TREE_TYPE indicates virtual inheritance.  */
13772
13773 void
13774 xref_basetypes (tree ref, tree base_list)
13775 {
13776   tree *basep;
13777   tree binfo, base_binfo;
13778   unsigned max_vbases = 0; /* Maximum direct & indirect virtual bases.  */
13779   unsigned max_bases = 0;  /* Maximum direct bases.  */
13780   unsigned max_dvbases = 0; /* Maximum direct virtual bases.  */
13781   int i;
13782   tree default_access;
13783   tree igo_prev; /* Track Inheritance Graph Order.  */
13784
13785   if (ref == error_mark_node)
13786     return;
13787
13788   /* The base of a derived class is private by default, all others are
13789      public.  */
13790   default_access = (TREE_CODE (ref) == RECORD_TYPE
13791                     && CLASSTYPE_DECLARED_CLASS (ref)
13792                     ? access_private_node : access_public_node);
13793
13794   /* First, make sure that any templates in base-classes are
13795      instantiated.  This ensures that if we call ourselves recursively
13796      we do not get confused about which classes are marked and which
13797      are not.  */
13798   basep = &base_list;
13799   while (*basep)
13800     {
13801       tree basetype = TREE_VALUE (*basep);
13802
13803       /* The dependent_type_p call below should really be dependent_scope_p
13804          so that we give a hard error about using an incomplete type as a
13805          base, but we allow it with a pedwarn for backward
13806          compatibility.  */
13807       if (processing_template_decl
13808           && CLASS_TYPE_P (basetype) && TYPE_BEING_DEFINED (basetype))
13809         cxx_incomplete_type_diagnostic (NULL_TREE, basetype, DK_PEDWARN);
13810       if (!dependent_type_p (basetype)
13811           && !complete_type_or_else (basetype, NULL))
13812         /* An incomplete type.  Remove it from the list.  */
13813         *basep = TREE_CHAIN (*basep);
13814       else
13815         {
13816           max_bases++;
13817           if (TREE_TYPE (*basep))
13818             max_dvbases++;
13819           if (CLASS_TYPE_P (basetype))
13820             max_vbases += vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
13821           basep = &TREE_CHAIN (*basep);
13822         }
13823     }
13824   max_vbases += max_dvbases;
13825
13826   TYPE_MARKED_P (ref) = 1;
13827
13828   /* The binfo slot should be empty, unless this is an (ill-formed)
13829      redefinition.  */
13830   gcc_assert (!TYPE_BINFO (ref) || TYPE_SIZE (ref));
13831
13832   gcc_assert (TYPE_MAIN_VARIANT (ref) == ref);
13833
13834   binfo = make_tree_binfo (max_bases);
13835
13836   TYPE_BINFO (ref) = binfo;
13837   BINFO_OFFSET (binfo) = size_zero_node;
13838   BINFO_TYPE (binfo) = ref;
13839
13840   /* Apply base-class info set up to the variants of this type.  */
13841   fixup_type_variants (ref);
13842
13843   if (max_bases)
13844     {
13845       vec_alloc (BINFO_BASE_ACCESSES (binfo), max_bases);
13846       /* A C++98 POD cannot have base classes.  */
13847       CLASSTYPE_NON_LAYOUT_POD_P (ref) = true;
13848
13849       if (TREE_CODE (ref) == UNION_TYPE)
13850         {
13851           error ("derived union %qT invalid", ref);
13852           return;
13853         }
13854     }
13855
13856   if (max_bases > 1)
13857     warning (OPT_Wmultiple_inheritance,
13858              "%qT defined with multiple direct bases", ref);
13859
13860   if (max_vbases)
13861     {
13862       /* An aggregate can't have virtual base classes.  */
13863       CLASSTYPE_NON_AGGREGATE (ref) = true;
13864
13865       vec_alloc (CLASSTYPE_VBASECLASSES (ref), max_vbases);
13866
13867       if (max_dvbases)
13868         warning (OPT_Wvirtual_inheritance,
13869                  "%qT defined with direct virtual base", ref);
13870     }
13871
13872   for (igo_prev = binfo; base_list; base_list = TREE_CHAIN (base_list))
13873     {
13874       tree access = TREE_PURPOSE (base_list);
13875       int via_virtual = TREE_TYPE (base_list) != NULL_TREE;
13876       tree basetype = TREE_VALUE (base_list);
13877
13878       if (access == access_default_node)
13879         access = default_access;
13880
13881       /* Before C++17, an aggregate cannot have base classes.  In C++17, an
13882          aggregate can't have virtual, private, or protected base classes.  */
13883       if (cxx_dialect < cxx17
13884           || access != access_public_node
13885           || via_virtual)
13886         CLASSTYPE_NON_AGGREGATE (ref) = true;
13887
13888       if (PACK_EXPANSION_P (basetype))
13889         basetype = PACK_EXPANSION_PATTERN (basetype);
13890       if (TREE_CODE (basetype) == TYPE_DECL)
13891         basetype = TREE_TYPE (basetype);
13892       if (!MAYBE_CLASS_TYPE_P (basetype) || TREE_CODE (basetype) == UNION_TYPE)
13893         {
13894           error ("base type %qT fails to be a struct or class type",
13895                  basetype);
13896           goto dropped_base;
13897         }
13898
13899       base_binfo = NULL_TREE;
13900       if (CLASS_TYPE_P (basetype) && !dependent_scope_p (basetype))
13901         {
13902           base_binfo = TYPE_BINFO (basetype);
13903           /* The original basetype could have been a typedef'd type.  */
13904           basetype = BINFO_TYPE (base_binfo);
13905
13906           /* Inherit flags from the base.  */
13907           TYPE_HAS_NEW_OPERATOR (ref)
13908             |= TYPE_HAS_NEW_OPERATOR (basetype);
13909           TYPE_HAS_ARRAY_NEW_OPERATOR (ref)
13910             |= TYPE_HAS_ARRAY_NEW_OPERATOR (basetype);
13911           TYPE_GETS_DELETE (ref) |= TYPE_GETS_DELETE (basetype);
13912           TYPE_HAS_CONVERSION (ref) |= TYPE_HAS_CONVERSION (basetype);
13913           CLASSTYPE_DIAMOND_SHAPED_P (ref)
13914             |= CLASSTYPE_DIAMOND_SHAPED_P (basetype);
13915           CLASSTYPE_REPEATED_BASE_P (ref)
13916             |= CLASSTYPE_REPEATED_BASE_P (basetype);
13917         }
13918
13919       /* We must do this test after we've seen through a typedef
13920          type.  */
13921       if (TYPE_MARKED_P (basetype))
13922         {
13923           if (basetype == ref)
13924             error ("recursive type %qT undefined", basetype);
13925           else
13926             error ("duplicate base type %qT invalid", basetype);
13927           goto dropped_base;
13928         }
13929
13930       if (PACK_EXPANSION_P (TREE_VALUE (base_list)))
13931         /* Regenerate the pack expansion for the bases. */
13932         basetype = make_pack_expansion (basetype);
13933
13934       TYPE_MARKED_P (basetype) = 1;
13935
13936       base_binfo = copy_binfo (base_binfo, basetype, ref,
13937                                &igo_prev, via_virtual);
13938       if (!BINFO_INHERITANCE_CHAIN (base_binfo))
13939         BINFO_INHERITANCE_CHAIN (base_binfo) = binfo;
13940
13941       BINFO_BASE_APPEND (binfo, base_binfo);
13942       BINFO_BASE_ACCESS_APPEND (binfo, access);
13943       continue;
13944
13945     dropped_base:
13946       /* Update max_vbases to reflect the reality that we are dropping
13947          this base:  if it reaches zero we want to undo the vec_alloc
13948          above to avoid inconsistencies during error-recovery: eg, in
13949          build_special_member_call, CLASSTYPE_VBASECLASSES non null
13950          and vtt null (c++/27952).  */
13951       if (via_virtual)
13952         max_vbases--;
13953       if (CLASS_TYPE_P (basetype))
13954         max_vbases
13955           -= vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
13956     }
13957
13958   if (CLASSTYPE_VBASECLASSES (ref)
13959       && max_vbases == 0)
13960     vec_free (CLASSTYPE_VBASECLASSES (ref));
13961
13962   if (vec_safe_length (CLASSTYPE_VBASECLASSES (ref)) < max_vbases)
13963     /* If we didn't get max_vbases vbases, we must have shared at
13964        least one of them, and are therefore diamond shaped.  */
13965     CLASSTYPE_DIAMOND_SHAPED_P (ref) = 1;
13966
13967   /* Unmark all the types.  */
13968   for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
13969     TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
13970   TYPE_MARKED_P (ref) = 0;
13971
13972   /* Now see if we have a repeated base type.  */
13973   if (!CLASSTYPE_REPEATED_BASE_P (ref))
13974     {
13975       for (base_binfo = binfo; base_binfo;
13976            base_binfo = TREE_CHAIN (base_binfo))
13977         {
13978           if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
13979             {
13980               CLASSTYPE_REPEATED_BASE_P (ref) = 1;
13981               break;
13982             }
13983           TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 1;
13984         }
13985       for (base_binfo = binfo; base_binfo;
13986            base_binfo = TREE_CHAIN (base_binfo))
13987         if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
13988           TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
13989         else
13990           break;
13991     }
13992 }
13993
13994 \f
13995 /* Copies the enum-related properties from type SRC to type DST.
13996    Used with the underlying type of an enum and the enum itself.  */
13997 static void
13998 copy_type_enum (tree dst, tree src)
13999 {
14000   tree t;
14001   for (t = dst; t; t = TYPE_NEXT_VARIANT (t))
14002     {
14003       TYPE_MIN_VALUE (t) = TYPE_MIN_VALUE (src);
14004       TYPE_MAX_VALUE (t) = TYPE_MAX_VALUE (src);
14005       TYPE_SIZE (t) = TYPE_SIZE (src);
14006       TYPE_SIZE_UNIT (t) = TYPE_SIZE_UNIT (src);
14007       SET_TYPE_MODE (dst, TYPE_MODE (src));
14008       TYPE_PRECISION (t) = TYPE_PRECISION (src);
14009       unsigned valign = TYPE_ALIGN (src);
14010       if (TYPE_USER_ALIGN (t))
14011         valign = MAX (valign, TYPE_ALIGN (t));
14012       else
14013         TYPE_USER_ALIGN (t) = TYPE_USER_ALIGN (src);
14014       SET_TYPE_ALIGN (t, valign);
14015       TYPE_UNSIGNED (t) = TYPE_UNSIGNED (src);
14016     }
14017 }
14018
14019 /* Begin compiling the definition of an enumeration type.
14020    NAME is its name, 
14021
14022    if ENUMTYPE is not NULL_TREE then the type has alredy been found.
14023
14024    UNDERLYING_TYPE is the type that will be used as the storage for
14025    the enumeration type. This should be NULL_TREE if no storage type
14026    was specified.
14027
14028    ATTRIBUTES are any attributes specified after the enum-key.
14029
14030    SCOPED_ENUM_P is true if this is a scoped enumeration type.
14031
14032    if IS_NEW is not NULL, gets TRUE iff a new type is created.
14033
14034    Returns the type object, as yet incomplete.
14035    Also records info about it so that build_enumerator
14036    may be used to declare the individual values as they are read.  */
14037
14038 tree
14039 start_enum (tree name, tree enumtype, tree underlying_type,
14040             tree attributes, bool scoped_enum_p, bool *is_new)
14041 {
14042   tree prevtype = NULL_TREE;
14043   gcc_assert (identifier_p (name));
14044
14045   if (is_new)
14046     *is_new = false;
14047   /* [C++0x dcl.enum]p5:
14048
14049     If not explicitly specified, the underlying type of a scoped
14050     enumeration type is int.  */
14051   if (!underlying_type && scoped_enum_p)
14052     underlying_type = integer_type_node;
14053
14054   if (underlying_type)
14055     underlying_type = cv_unqualified (underlying_type);
14056
14057   /* If this is the real definition for a previous forward reference,
14058      fill in the contents in the same object that used to be the
14059      forward reference.  */
14060   if (!enumtype)
14061     enumtype = lookup_and_check_tag (enum_type, name,
14062                                      /*tag_scope=*/ts_current,
14063                                      /*template_header_p=*/false);
14064
14065   /* In case of a template_decl, the only check that should be deferred
14066      to instantiation time is the comparison of underlying types.  */
14067   if (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE)
14068     {
14069       if (scoped_enum_p != SCOPED_ENUM_P (enumtype))
14070         {
14071           error_at (input_location, "scoped/unscoped mismatch "
14072                     "in enum %q#T", enumtype);
14073           inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
14074                   "previous definition here");
14075           enumtype = error_mark_node;
14076         }
14077       else if (ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) != !! underlying_type)
14078         {
14079           error_at (input_location, "underlying type mismatch "
14080                     "in enum %q#T", enumtype);
14081           inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
14082                   "previous definition here");
14083           enumtype = error_mark_node;
14084         }
14085       else if (underlying_type && ENUM_UNDERLYING_TYPE (enumtype)
14086                && !dependent_type_p (underlying_type)
14087                && !dependent_type_p (ENUM_UNDERLYING_TYPE (enumtype))
14088                && !same_type_p (underlying_type,
14089                                 ENUM_UNDERLYING_TYPE (enumtype)))
14090         {
14091           error_at (input_location, "different underlying type "
14092                     "in enum %q#T", enumtype);
14093           inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
14094                   "previous definition here");
14095           underlying_type = NULL_TREE;
14096         }
14097     }
14098
14099   if (!enumtype || TREE_CODE (enumtype) != ENUMERAL_TYPE
14100       || processing_template_decl)
14101     {
14102       /* In case of error, make a dummy enum to allow parsing to
14103          continue.  */
14104       if (enumtype == error_mark_node)
14105         {
14106           name = make_anon_name ();
14107           enumtype = NULL_TREE;
14108         }
14109
14110       /* enumtype may be an ENUMERAL_TYPE if this is a redefinition
14111          of an opaque enum, or an opaque enum of an already defined
14112          enumeration (C++0x only).
14113          In any other case, it'll be NULL_TREE. */
14114       if (!enumtype)
14115         {
14116           if (is_new)
14117             *is_new = true;
14118         }
14119       prevtype = enumtype;
14120
14121       /* Do not push the decl more than once, unless we need to
14122          compare underlying types at instantiation time */
14123       if (!enumtype
14124           || TREE_CODE (enumtype) != ENUMERAL_TYPE
14125           || (underlying_type
14126               && dependent_type_p (underlying_type))
14127           || (ENUM_UNDERLYING_TYPE (enumtype)
14128               && dependent_type_p (ENUM_UNDERLYING_TYPE (enumtype))))
14129         {
14130           enumtype = cxx_make_type (ENUMERAL_TYPE);
14131           enumtype = pushtag (name, enumtype, /*tag_scope=*/ts_current);
14132
14133           /* std::byte aliases anything.  */
14134           if (enumtype != error_mark_node
14135               && TYPE_CONTEXT (enumtype) == std_node
14136               && !strcmp ("byte", TYPE_NAME_STRING (enumtype)))
14137             TYPE_ALIAS_SET (enumtype) = 0;
14138         }
14139       else
14140           enumtype = xref_tag (enum_type, name, /*tag_scope=*/ts_current,
14141                                false);
14142
14143       if (enumtype == error_mark_node)
14144         return error_mark_node;
14145
14146       /* The enum is considered opaque until the opening '{' of the
14147          enumerator list.  */
14148       SET_OPAQUE_ENUM_P (enumtype, true);
14149       ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) = !! underlying_type;
14150     }
14151
14152   SET_SCOPED_ENUM_P (enumtype, scoped_enum_p);
14153
14154   cplus_decl_attributes (&enumtype, attributes, (int)ATTR_FLAG_TYPE_IN_PLACE);
14155
14156   if (underlying_type)
14157     {
14158       if (ENUM_UNDERLYING_TYPE (enumtype))
14159         /* We already checked that it matches, don't change it to a different
14160            typedef variant.  */;
14161       else if (CP_INTEGRAL_TYPE_P (underlying_type))
14162         {
14163           copy_type_enum (enumtype, underlying_type);
14164           ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
14165         }
14166       else if (dependent_type_p (underlying_type))
14167         ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
14168       else
14169         error ("underlying type %qT of %qT must be an integral type", 
14170                underlying_type, enumtype);
14171     }
14172
14173   /* If into a template class, the returned enum is always the first
14174      declaration (opaque or not) seen. This way all the references to
14175      this type will be to the same declaration. The following ones are used
14176      only to check for definition errors.  */
14177   if (prevtype && processing_template_decl)
14178     return prevtype;
14179   else
14180     return enumtype;
14181 }
14182
14183 /* After processing and defining all the values of an enumeration type,
14184    install their decls in the enumeration type.
14185    ENUMTYPE is the type object.  */
14186
14187 void
14188 finish_enum_value_list (tree enumtype)
14189 {
14190   tree values;
14191   tree underlying_type;
14192   tree decl;
14193   tree value;
14194   tree minnode, maxnode;
14195   tree t;
14196
14197   bool fixed_underlying_type_p 
14198     = ENUM_UNDERLYING_TYPE (enumtype) != NULL_TREE;
14199
14200   /* We built up the VALUES in reverse order.  */
14201   TYPE_VALUES (enumtype) = nreverse (TYPE_VALUES (enumtype));
14202
14203   /* For an enum defined in a template, just set the type of the values;
14204      all further processing is postponed until the template is
14205      instantiated.  We need to set the type so that tsubst of a CONST_DECL
14206      works.  */
14207   if (processing_template_decl)
14208     {
14209       for (values = TYPE_VALUES (enumtype);
14210            values;
14211            values = TREE_CHAIN (values))
14212         TREE_TYPE (TREE_VALUE (values)) = enumtype;
14213       return;
14214     }
14215
14216   /* Determine the minimum and maximum values of the enumerators.  */
14217   if (TYPE_VALUES (enumtype))
14218     {
14219       minnode = maxnode = NULL_TREE;
14220
14221       for (values = TYPE_VALUES (enumtype);
14222            values;
14223            values = TREE_CHAIN (values))
14224         {
14225           decl = TREE_VALUE (values);
14226
14227           /* [dcl.enum]: Following the closing brace of an enum-specifier,
14228              each enumerator has the type of its enumeration.  Prior to the
14229              closing brace, the type of each enumerator is the type of its
14230              initializing value.  */
14231           TREE_TYPE (decl) = enumtype;
14232
14233           /* Update the minimum and maximum values, if appropriate.  */
14234           value = DECL_INITIAL (decl);
14235           if (value == error_mark_node)
14236             value = integer_zero_node;
14237           /* Figure out what the minimum and maximum values of the
14238              enumerators are.  */
14239           if (!minnode)
14240             minnode = maxnode = value;
14241           else if (tree_int_cst_lt (maxnode, value))
14242             maxnode = value;
14243           else if (tree_int_cst_lt (value, minnode))
14244             minnode = value;
14245         }
14246     }
14247   else
14248     /* [dcl.enum]
14249
14250        If the enumerator-list is empty, the underlying type is as if
14251        the enumeration had a single enumerator with value 0.  */
14252     minnode = maxnode = integer_zero_node;
14253
14254   if (!fixed_underlying_type_p)
14255     {
14256       /* Compute the number of bits require to represent all values of the
14257          enumeration.  We must do this before the type of MINNODE and
14258          MAXNODE are transformed, since tree_int_cst_min_precision relies
14259          on the TREE_TYPE of the value it is passed.  */
14260       signop sgn = tree_int_cst_sgn (minnode) >= 0 ? UNSIGNED : SIGNED;
14261       int lowprec = tree_int_cst_min_precision (minnode, sgn);
14262       int highprec = tree_int_cst_min_precision (maxnode, sgn);
14263       int precision = MAX (lowprec, highprec);
14264       unsigned int itk;
14265       bool use_short_enum;
14266
14267       /* Determine the underlying type of the enumeration.
14268
14269          [dcl.enum]
14270
14271          The underlying type of an enumeration is an integral type that
14272          can represent all the enumerator values defined in the
14273          enumeration.  It is implementation-defined which integral type is
14274          used as the underlying type for an enumeration except that the
14275          underlying type shall not be larger than int unless the value of
14276          an enumerator cannot fit in an int or unsigned int.
14277
14278          We use "int" or an "unsigned int" as the underlying type, even if
14279          a smaller integral type would work, unless the user has
14280          explicitly requested that we use the smallest possible type.  The
14281          user can request that for all enumerations with a command line
14282          flag, or for just one enumeration with an attribute.  */
14283
14284       use_short_enum = flag_short_enums
14285         || lookup_attribute ("packed", TYPE_ATTRIBUTES (enumtype));
14286
14287       /* If the precision of the type was specified with an attribute and it
14288          was too small, give an error.  Otherwise, use it.  */
14289       if (TYPE_PRECISION (enumtype))
14290         {
14291           if (precision > TYPE_PRECISION (enumtype))
14292             error ("specified mode too small for enumeral values");
14293           else
14294             {
14295               use_short_enum = true;
14296               precision = TYPE_PRECISION (enumtype);
14297             }
14298         }
14299
14300       for (itk = (use_short_enum ? itk_char : itk_int);
14301            itk != itk_none;
14302            itk++)
14303         {
14304           underlying_type = integer_types[itk];
14305           if (underlying_type != NULL_TREE
14306               && TYPE_PRECISION (underlying_type) >= precision
14307               && TYPE_SIGN (underlying_type) == sgn)
14308             break;
14309         }
14310       if (itk == itk_none)
14311         {
14312           /* DR 377
14313
14314              IF no integral type can represent all the enumerator values, the
14315              enumeration is ill-formed.  */
14316           error ("no integral type can represent all of the enumerator values "
14317                  "for %qT", enumtype);
14318           precision = TYPE_PRECISION (long_long_integer_type_node);
14319           underlying_type = integer_types[itk_unsigned_long_long];
14320         }
14321
14322       /* [dcl.enum]
14323
14324          The value of sizeof() applied to an enumeration type, an object
14325          of an enumeration type, or an enumerator, is the value of sizeof()
14326          applied to the underlying type.  */
14327       copy_type_enum (enumtype, underlying_type);
14328
14329       /* Compute the minimum and maximum values for the type.
14330
14331          [dcl.enum]
14332
14333          For an enumeration where emin is the smallest enumerator and emax
14334          is the largest, the values of the enumeration are the values of the
14335          underlying type in the range bmin to bmax, where bmin and bmax are,
14336          respectively, the smallest and largest values of the smallest bit-
14337          field that can store emin and emax.  */
14338
14339       /* The middle-end currently assumes that types with TYPE_PRECISION
14340          narrower than their underlying type are suitably zero or sign
14341          extended to fill their mode.  Similarly, it assumes that the front
14342          end assures that a value of a particular type must be within
14343          TYPE_MIN_VALUE and TYPE_MAX_VALUE.
14344
14345          We used to set these fields based on bmin and bmax, but that led
14346          to invalid assumptions like optimizing away bounds checking.  So
14347          now we just set the TYPE_PRECISION, TYPE_MIN_VALUE, and
14348          TYPE_MAX_VALUE to the values for the mode above and only restrict
14349          the ENUM_UNDERLYING_TYPE for the benefit of diagnostics.  */
14350       ENUM_UNDERLYING_TYPE (enumtype)
14351         = build_distinct_type_copy (underlying_type);
14352       TYPE_PRECISION (ENUM_UNDERLYING_TYPE (enumtype)) = precision;
14353       set_min_and_max_values_for_integral_type
14354         (ENUM_UNDERLYING_TYPE (enumtype), precision, sgn);
14355
14356       /* If -fstrict-enums, still constrain TYPE_MIN/MAX_VALUE.  */
14357       if (flag_strict_enums)
14358         set_min_and_max_values_for_integral_type (enumtype, precision, sgn);
14359     }
14360   else
14361     underlying_type = ENUM_UNDERLYING_TYPE (enumtype);
14362
14363   /* Convert each of the enumerators to the type of the underlying
14364      type of the enumeration.  */
14365   for (values = TYPE_VALUES (enumtype); values; values = TREE_CHAIN (values))
14366     {
14367       location_t saved_location;
14368
14369       decl = TREE_VALUE (values);
14370       saved_location = input_location;
14371       input_location = DECL_SOURCE_LOCATION (decl);
14372       if (fixed_underlying_type_p)
14373         /* If the enumeration type has a fixed underlying type, we
14374            already checked all of the enumerator values.  */
14375         value = DECL_INITIAL (decl);
14376       else
14377         value = perform_implicit_conversion (underlying_type,
14378                                              DECL_INITIAL (decl),
14379                                              tf_warning_or_error);
14380       input_location = saved_location;
14381
14382       /* Do not clobber shared ints.  */
14383       if (value != error_mark_node)
14384         {
14385           value = copy_node (value);
14386
14387           TREE_TYPE (value) = enumtype;
14388         }
14389       DECL_INITIAL (decl) = value;
14390     }
14391
14392   /* Fix up all variant types of this enum type.  */
14393   for (t = TYPE_MAIN_VARIANT (enumtype); t; t = TYPE_NEXT_VARIANT (t))
14394     TYPE_VALUES (t) = TYPE_VALUES (enumtype);
14395
14396   if (at_class_scope_p ()
14397       && COMPLETE_TYPE_P (current_class_type)
14398       && UNSCOPED_ENUM_P (enumtype))
14399     {
14400       insert_late_enum_def_bindings (current_class_type, enumtype);
14401       /* TYPE_FIELDS needs fixup.  */
14402       fixup_type_variants (current_class_type);
14403     }
14404
14405   /* Finish debugging output for this type.  */
14406   rest_of_type_compilation (enumtype, namespace_bindings_p ());
14407
14408   /* Each enumerator now has the type of its enumeration.  Clear the cache
14409      so that this change in types doesn't confuse us later on.  */
14410   clear_cv_and_fold_caches ();
14411 }
14412
14413 /* Finishes the enum type. This is called only the first time an
14414    enumeration is seen, be it opaque or odinary.
14415    ENUMTYPE is the type object.  */
14416
14417 void
14418 finish_enum (tree enumtype)
14419 {
14420   if (processing_template_decl)
14421     {
14422       if (at_function_scope_p ())
14423         add_stmt (build_min (TAG_DEFN, enumtype));
14424       return;
14425     }
14426
14427   /* If this is a forward declaration, there should not be any variants,
14428      though we can get a variant in the middle of an enum-specifier with
14429      wacky code like 'enum E { e = sizeof(const E*) };'  */
14430   gcc_assert (enumtype == TYPE_MAIN_VARIANT (enumtype)
14431               && (TYPE_VALUES (enumtype)
14432                   || !TYPE_NEXT_VARIANT (enumtype)));
14433 }
14434
14435 /* Build and install a CONST_DECL for an enumeration constant of the
14436    enumeration type ENUMTYPE whose NAME and VALUE (if any) are provided.
14437    Apply ATTRIBUTES if available.  LOC is the location of NAME.
14438    Assignment of sequential values by default is handled here.  */
14439
14440 void
14441 build_enumerator (tree name, tree value, tree enumtype, tree attributes,
14442                   location_t loc)
14443 {
14444   tree decl;
14445   tree context;
14446   tree type;
14447
14448   /* scalar_constant_value will pull out this expression, so make sure
14449      it's folded as appropriate.  */
14450   if (processing_template_decl)
14451     value = fold_non_dependent_expr (value);
14452
14453   /* If the VALUE was erroneous, pretend it wasn't there; that will
14454      result in the enum being assigned the next value in sequence.  */
14455   if (value == error_mark_node)
14456     value = NULL_TREE;
14457
14458   /* Remove no-op casts from the value.  */
14459   if (value)
14460     STRIP_TYPE_NOPS (value);
14461
14462   if (! processing_template_decl)
14463     {
14464       /* Validate and default VALUE.  */
14465       if (value != NULL_TREE)
14466         {
14467           if (!ENUM_UNDERLYING_TYPE (enumtype))
14468             {
14469               tree tmp_value = build_expr_type_conversion (WANT_INT | WANT_ENUM,
14470                                                            value, true);
14471               if (tmp_value)
14472                 value = tmp_value;
14473             }
14474           else if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
14475                    (TREE_TYPE (value)))
14476             value = perform_implicit_conversion_flags
14477               (ENUM_UNDERLYING_TYPE (enumtype), value, tf_warning_or_error,
14478                LOOKUP_IMPLICIT | LOOKUP_NO_NARROWING);
14479
14480           if (value == error_mark_node)
14481             value = NULL_TREE;
14482
14483           if (value != NULL_TREE)
14484             {
14485               if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
14486                   (TREE_TYPE (value)))
14487                 {
14488                   error ("enumerator value for %qD must have integral or "
14489                          "unscoped enumeration type", name);
14490                   value = NULL_TREE;
14491                 }
14492               else
14493                 {
14494                   value = cxx_constant_value (value);
14495
14496                   if (TREE_CODE (value) != INTEGER_CST)
14497                     {
14498                       error ("enumerator value for %qD is not an integer "
14499                              "constant", name);
14500                       value = NULL_TREE;
14501                     }
14502                 }
14503             }
14504         }
14505
14506       /* Default based on previous value.  */
14507       if (value == NULL_TREE)
14508         {
14509           if (TYPE_VALUES (enumtype))
14510             {
14511               tree prev_value;
14512               bool overflowed;
14513
14514               /* C++03 7.2/4: If no initializer is specified for the first
14515                  enumerator, the type is an unspecified integral
14516                  type. Otherwise the type is the same as the type of the
14517                  initializing value of the preceding enumerator unless the
14518                  incremented value is not representable in that type, in
14519                  which case the type is an unspecified integral type
14520                  sufficient to contain the incremented value.  */
14521               prev_value = DECL_INITIAL (TREE_VALUE (TYPE_VALUES (enumtype)));
14522               if (error_operand_p (prev_value))
14523                 value = error_mark_node;
14524               else
14525                 {
14526                   tree type = TREE_TYPE (prev_value);
14527                   signop sgn = TYPE_SIGN (type);
14528                   widest_int wi = wi::add (wi::to_widest (prev_value), 1, sgn,
14529                                            &overflowed);
14530                   if (!overflowed)
14531                     {
14532                       bool pos = !wi::neg_p (wi, sgn);
14533                       if (!wi::fits_to_tree_p (wi, type))
14534                         {
14535                           unsigned int itk;
14536                           for (itk = itk_int; itk != itk_none; itk++)
14537                             {
14538                               type = integer_types[itk];
14539                               if (type != NULL_TREE
14540                                   && (pos || !TYPE_UNSIGNED (type))
14541                                   && wi::fits_to_tree_p (wi, type))
14542                                 break;
14543                             }
14544                           if (type && cxx_dialect < cxx11
14545                               && itk > itk_unsigned_long)
14546                             pedwarn (input_location, OPT_Wlong_long,
14547                                      pos ? G_("\
14548 incremented enumerator value is too large for %<unsigned long%>") : G_("\
14549 incremented enumerator value is too large for %<long%>"));
14550                         }
14551                       if (type == NULL_TREE)
14552                         overflowed = true;
14553                       else
14554                         value = wide_int_to_tree (type, wi);
14555                     }
14556
14557                   if (overflowed)
14558                     {
14559                       error ("overflow in enumeration values at %qD", name);
14560                       value = error_mark_node;
14561                     }
14562                 }
14563             }
14564           else
14565             value = integer_zero_node;
14566         }
14567
14568       /* Remove no-op casts from the value.  */
14569       STRIP_TYPE_NOPS (value);
14570
14571       /* If the underlying type of the enum is fixed, check whether
14572          the enumerator values fits in the underlying type.  If it
14573          does not fit, the program is ill-formed [C++0x dcl.enum].  */
14574       if (ENUM_UNDERLYING_TYPE (enumtype)
14575           && value
14576           && TREE_CODE (value) == INTEGER_CST)
14577         {
14578           if (!int_fits_type_p (value, ENUM_UNDERLYING_TYPE (enumtype)))
14579             error ("enumerator value %qE is outside the range of underlying "
14580                    "type %qT", value, ENUM_UNDERLYING_TYPE (enumtype));
14581
14582           /* Convert the value to the appropriate type.  */
14583           value = fold_convert (ENUM_UNDERLYING_TYPE (enumtype), value);
14584         }
14585     }
14586
14587   /* C++ associates enums with global, function, or class declarations.  */
14588   context = current_scope ();
14589
14590   /* Build the actual enumeration constant.  Note that the enumeration
14591      constants have the underlying type of the enum (if it is fixed)
14592      or the type of their initializer (if the underlying type of the
14593      enum is not fixed):
14594
14595       [ C++0x dcl.enum ]
14596
14597         If the underlying type is fixed, the type of each enumerator
14598         prior to the closing brace is the underlying type; if the
14599         initializing value of an enumerator cannot be represented by
14600         the underlying type, the program is ill-formed. If the
14601         underlying type is not fixed, the type of each enumerator is
14602         the type of its initializing value.
14603
14604     If the underlying type is not fixed, it will be computed by
14605     finish_enum and we will reset the type of this enumerator.  Of
14606     course, if we're processing a template, there may be no value.  */
14607   type = value ? TREE_TYPE (value) : NULL_TREE;
14608
14609   decl = build_decl (loc, CONST_DECL, name, type);
14610   
14611   DECL_CONTEXT (decl) = enumtype;
14612   TREE_CONSTANT (decl) = 1;
14613   TREE_READONLY (decl) = 1;
14614   DECL_INITIAL (decl) = value;
14615
14616   if (attributes)
14617     cplus_decl_attributes (&decl, attributes, 0);
14618
14619   if (context && context == current_class_type && !SCOPED_ENUM_P (enumtype))
14620     {
14621       /* In something like `struct S { enum E { i = 7 }; };' we put `i'
14622          on the TYPE_FIELDS list for `S'.  (That's so that you can say
14623          things like `S::i' later.)  */
14624
14625       /* The enumerator may be getting declared outside of its enclosing
14626          class, like so:
14627
14628            class S { public: enum E : int; }; enum S::E : int { i = 7; };
14629
14630          For which case we need to make sure that the access of `S::i'
14631          matches the access of `S::E'.  */
14632       tree saved_cas = current_access_specifier;
14633       if (TREE_PRIVATE (TYPE_NAME (enumtype)))
14634         current_access_specifier = access_private_node;
14635       else if (TREE_PROTECTED (TYPE_NAME (enumtype)))
14636         current_access_specifier = access_protected_node;
14637       else
14638         current_access_specifier = access_public_node;
14639
14640       finish_member_declaration (decl);
14641
14642       current_access_specifier = saved_cas;
14643     }
14644   else
14645     pushdecl (decl);
14646
14647   /* Add this enumeration constant to the list for this type.  */
14648   TYPE_VALUES (enumtype) = tree_cons (name, decl, TYPE_VALUES (enumtype));
14649 }
14650
14651 /* Look for an enumerator with the given NAME within the enumeration
14652    type ENUMTYPE.  This routine is used primarily for qualified name
14653    lookup into an enumerator in C++0x, e.g.,
14654
14655      enum class Color { Red, Green, Blue };
14656
14657      Color color = Color::Red;
14658
14659    Returns the value corresponding to the enumerator, or
14660    NULL_TREE if no such enumerator was found.  */
14661 tree
14662 lookup_enumerator (tree enumtype, tree name)
14663 {
14664   tree e;
14665   gcc_assert (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE);
14666
14667   e = purpose_member (name, TYPE_VALUES (enumtype));
14668   return e? TREE_VALUE (e) : NULL_TREE;
14669 }
14670
14671 \f
14672 /* We're defining DECL.  Make sure that its type is OK.  */
14673
14674 static void
14675 check_function_type (tree decl, tree current_function_parms)
14676 {
14677   tree fntype = TREE_TYPE (decl);
14678   tree return_type = complete_type (TREE_TYPE (fntype));
14679
14680   /* In a function definition, arg types must be complete.  */
14681   require_complete_types_for_parms (current_function_parms);
14682
14683   if (dependent_type_p (return_type)
14684       || type_uses_auto (return_type))
14685     return;
14686   if (!COMPLETE_OR_VOID_TYPE_P (return_type))
14687     {
14688       tree args = TYPE_ARG_TYPES (fntype);
14689
14690       error ("return type %q#T is incomplete", return_type);
14691
14692       /* Make it return void instead.  */
14693       if (TREE_CODE (fntype) == METHOD_TYPE)
14694         fntype = build_method_type_directly (TREE_TYPE (TREE_VALUE (args)),
14695                                              void_type_node,
14696                                              TREE_CHAIN (args));
14697       else
14698         fntype = build_function_type (void_type_node, args);
14699       fntype
14700         = build_exception_variant (fntype,
14701                                    TYPE_RAISES_EXCEPTIONS (TREE_TYPE (decl)));
14702       fntype = (cp_build_type_attribute_variant
14703                 (fntype, TYPE_ATTRIBUTES (TREE_TYPE (decl))));
14704       TREE_TYPE (decl) = fntype;
14705     }
14706   else
14707     {
14708       abstract_virtuals_error (decl, TREE_TYPE (fntype));
14709       maybe_warn_parm_abi (TREE_TYPE (fntype),
14710                            DECL_SOURCE_LOCATION (decl));
14711     }
14712 }
14713
14714 /* True iff FN is an implicitly-defined default constructor.  */
14715
14716 static bool
14717 implicit_default_ctor_p (tree fn)
14718 {
14719   return (DECL_CONSTRUCTOR_P (fn)
14720           && !user_provided_p (fn)
14721           && sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (fn)));
14722 }
14723
14724 /* Clobber the contents of *this to let the back end know that the object
14725    storage is dead when we enter the constructor or leave the destructor.  */
14726
14727 static tree
14728 build_clobber_this ()
14729 {
14730   /* Clobbering an empty base is pointless, and harmful if its one byte
14731      TYPE_SIZE overlays real data.  */
14732   if (is_empty_class (current_class_type))
14733     return void_node;
14734
14735   /* If we have virtual bases, clobber the whole object, but only if we're in
14736      charge.  If we don't have virtual bases, clobber the as-base type so we
14737      don't mess with tail padding.  */
14738   bool vbases = CLASSTYPE_VBASECLASSES (current_class_type);
14739
14740   tree ctype = current_class_type;
14741   if (!vbases)
14742     ctype = CLASSTYPE_AS_BASE (ctype);
14743
14744   tree clobber = build_constructor (ctype, NULL);
14745   TREE_THIS_VOLATILE (clobber) = true;
14746
14747   tree thisref = current_class_ref;
14748   if (ctype != current_class_type)
14749     {
14750       thisref = build_nop (build_reference_type (ctype), current_class_ptr);
14751       thisref = convert_from_reference (thisref);
14752     }
14753
14754   tree exprstmt = build2 (MODIFY_EXPR, void_type_node, thisref, clobber);
14755   if (vbases)
14756     exprstmt = build_if_in_charge (exprstmt);
14757
14758   return exprstmt;
14759 }
14760
14761 /* Create the FUNCTION_DECL for a function definition.
14762    DECLSPECS and DECLARATOR are the parts of the declaration;
14763    they describe the function's name and the type it returns,
14764    but twisted together in a fashion that parallels the syntax of C.
14765
14766    FLAGS is a bitwise or of SF_PRE_PARSED (indicating that the
14767    DECLARATOR is really the DECL for the function we are about to
14768    process and that DECLSPECS should be ignored), SF_INCLASS_INLINE
14769    indicating that the function is an inline defined in-class.
14770
14771    This function creates a binding context for the function body
14772    as well as setting up the FUNCTION_DECL in current_function_decl.
14773
14774    For C++, we must first check whether that datum makes any sense.
14775    For example, "class A local_a(1,2);" means that variable local_a
14776    is an aggregate of type A, which should have a constructor
14777    applied to it with the argument list [1, 2].
14778
14779    On entry, DECL_INITIAL (decl1) should be NULL_TREE or error_mark_node,
14780    or may be a BLOCK if the function has been defined previously
14781    in this translation unit.  On exit, DECL_INITIAL (decl1) will be
14782    error_mark_node if the function has never been defined, or
14783    a BLOCK if the function has been defined somewhere.  */
14784
14785 bool
14786 start_preparsed_function (tree decl1, tree attrs, int flags)
14787 {
14788   tree ctype = NULL_TREE;
14789   tree fntype;
14790   tree restype;
14791   int doing_friend = 0;
14792   cp_binding_level *bl;
14793   tree current_function_parms;
14794   struct c_fileinfo *finfo
14795     = get_fileinfo (LOCATION_FILE (DECL_SOURCE_LOCATION (decl1)));
14796   bool honor_interface;
14797
14798   /* Sanity check.  */
14799   gcc_assert (VOID_TYPE_P (TREE_VALUE (void_list_node)));
14800   gcc_assert (TREE_CHAIN (void_list_node) == NULL_TREE);
14801
14802   fntype = TREE_TYPE (decl1);
14803   if (TREE_CODE (fntype) == METHOD_TYPE)
14804     ctype = TYPE_METHOD_BASETYPE (fntype);
14805
14806   /* ISO C++ 11.4/5.  A friend function defined in a class is in
14807      the (lexical) scope of the class in which it is defined.  */
14808   if (!ctype && DECL_FRIEND_P (decl1))
14809     {
14810       ctype = DECL_FRIEND_CONTEXT (decl1);
14811
14812       /* CTYPE could be null here if we're dealing with a template;
14813          for example, `inline friend float foo()' inside a template
14814          will have no CTYPE set.  */
14815       if (ctype && TREE_CODE (ctype) != RECORD_TYPE)
14816         ctype = NULL_TREE;
14817       else
14818         doing_friend = 1;
14819     }
14820
14821   if (DECL_DECLARED_INLINE_P (decl1)
14822       && lookup_attribute ("noinline", attrs))
14823     warning_at (DECL_SOURCE_LOCATION (decl1), 0,
14824                 "inline function %qD given attribute noinline", decl1);
14825
14826   /* Handle gnu_inline attribute.  */
14827   if (GNU_INLINE_P (decl1))
14828     {
14829       DECL_EXTERNAL (decl1) = 1;
14830       DECL_NOT_REALLY_EXTERN (decl1) = 0;
14831       DECL_INTERFACE_KNOWN (decl1) = 1;
14832       DECL_DISREGARD_INLINE_LIMITS (decl1) = 1;
14833     }
14834
14835   if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl1))
14836     /* This is a constructor, we must ensure that any default args
14837        introduced by this definition are propagated to the clones
14838        now. The clones are used directly in overload resolution.  */
14839     adjust_clone_args (decl1);
14840
14841   /* Sometimes we don't notice that a function is a static member, and
14842      build a METHOD_TYPE for it.  Fix that up now.  */
14843   gcc_assert (!(ctype != NULL_TREE && DECL_STATIC_FUNCTION_P (decl1)
14844                 && TREE_CODE (TREE_TYPE (decl1)) == METHOD_TYPE));
14845
14846   /* Set up current_class_type, and enter the scope of the class, if
14847      appropriate.  */
14848   if (ctype)
14849     push_nested_class (ctype);
14850   else if (DECL_STATIC_FUNCTION_P (decl1))
14851     push_nested_class (DECL_CONTEXT (decl1));
14852
14853   /* Now that we have entered the scope of the class, we must restore
14854      the bindings for any template parameters surrounding DECL1, if it
14855      is an inline member template.  (Order is important; consider the
14856      case where a template parameter has the same name as a field of
14857      the class.)  It is not until after this point that
14858      PROCESSING_TEMPLATE_DECL is guaranteed to be set up correctly.  */
14859   if (flags & SF_INCLASS_INLINE)
14860     maybe_begin_member_template_processing (decl1);
14861
14862   /* Effective C++ rule 15.  */
14863   if (warn_ecpp
14864       && DECL_ASSIGNMENT_OPERATOR_P (decl1)
14865       && DECL_OVERLOADED_OPERATOR_IS (decl1, NOP_EXPR)
14866       && VOID_TYPE_P (TREE_TYPE (fntype)))
14867     warning (OPT_Weffc__,
14868              "%<operator=%> should return a reference to %<*this%>");
14869
14870   /* Make the init_value nonzero so pushdecl knows this is not tentative.
14871      error_mark_node is replaced below (in poplevel) with the BLOCK.  */
14872   if (!DECL_INITIAL (decl1))
14873     DECL_INITIAL (decl1) = error_mark_node;
14874
14875   /* This function exists in static storage.
14876      (This does not mean `static' in the C sense!)  */
14877   TREE_STATIC (decl1) = 1;
14878
14879   /* We must call push_template_decl after current_class_type is set
14880      up.  (If we are processing inline definitions after exiting a
14881      class scope, current_class_type will be NULL_TREE until set above
14882      by push_nested_class.)  */
14883   if (processing_template_decl)
14884     {
14885       tree newdecl1 = push_template_decl (decl1);
14886       if (newdecl1 == error_mark_node)
14887         {
14888           if (ctype || DECL_STATIC_FUNCTION_P (decl1))
14889             pop_nested_class ();
14890           return false;
14891         }
14892       decl1 = newdecl1;
14893     }
14894
14895   /* Make sure the parameter and return types are reasonable.  When
14896      you declare a function, these types can be incomplete, but they
14897      must be complete when you define the function.  */
14898   check_function_type (decl1, DECL_ARGUMENTS (decl1));
14899
14900   /* Build the return declaration for the function.  */
14901   restype = TREE_TYPE (fntype);
14902
14903   if (DECL_RESULT (decl1) == NULL_TREE)
14904     {
14905       tree resdecl;
14906
14907       resdecl = build_decl (input_location, RESULT_DECL, 0, restype);
14908       DECL_ARTIFICIAL (resdecl) = 1;
14909       DECL_IGNORED_P (resdecl) = 1;
14910       DECL_RESULT (decl1) = resdecl;
14911
14912       cp_apply_type_quals_to_decl (cp_type_quals (restype), resdecl);
14913     }
14914
14915   /* Record the decl so that the function name is defined.
14916      If we already have a decl for this name, and it is a FUNCTION_DECL,
14917      use the old decl.  */
14918   if (!processing_template_decl && !(flags & SF_PRE_PARSED))
14919     {
14920       /* A specialization is not used to guide overload resolution.  */
14921       if (!DECL_FUNCTION_MEMBER_P (decl1)
14922           && !(DECL_USE_TEMPLATE (decl1) &&
14923                PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl1))))
14924         {
14925           tree olddecl = pushdecl (decl1);
14926
14927           if (olddecl == error_mark_node)
14928             /* If something went wrong when registering the declaration,
14929                use DECL1; we have to have a FUNCTION_DECL to use when
14930                parsing the body of the function.  */
14931             ;
14932           else
14933             {
14934               /* Otherwise, OLDDECL is either a previous declaration
14935                  of the same function or DECL1 itself.  */
14936
14937               if (warn_missing_declarations
14938                   && olddecl == decl1
14939                   && !DECL_MAIN_P (decl1)
14940                   && TREE_PUBLIC (decl1)
14941                   && !DECL_DECLARED_INLINE_P (decl1))
14942                 {
14943                   tree context;
14944
14945                   /* Check whether DECL1 is in an anonymous
14946                      namespace.  */
14947                   for (context = DECL_CONTEXT (decl1);
14948                        context;
14949                        context = DECL_CONTEXT (context))
14950                     {
14951                       if (TREE_CODE (context) == NAMESPACE_DECL
14952                           && DECL_NAME (context) == NULL_TREE)
14953                         break;
14954                     }
14955
14956                   if (context == NULL)
14957                     warning_at (DECL_SOURCE_LOCATION (decl1),
14958                                 OPT_Wmissing_declarations,
14959                                 "no previous declaration for %qD", decl1);
14960                 }
14961
14962               decl1 = olddecl;
14963             }
14964         }
14965       else
14966         {
14967           /* We need to set the DECL_CONTEXT.  */
14968           if (!DECL_CONTEXT (decl1) && DECL_TEMPLATE_INFO (decl1))
14969             DECL_CONTEXT (decl1) = DECL_CONTEXT (DECL_TI_TEMPLATE (decl1));
14970         }
14971       fntype = TREE_TYPE (decl1);
14972       restype = TREE_TYPE (fntype);
14973
14974       /* If #pragma weak applies, mark the decl appropriately now.
14975          The pragma only applies to global functions.  Because
14976          determining whether or not the #pragma applies involves
14977          computing the mangled name for the declaration, we cannot
14978          apply the pragma until after we have merged this declaration
14979          with any previous declarations; if the original declaration
14980          has a linkage specification, that specification applies to
14981          the definition as well, and may affect the mangled name.  */
14982       if (DECL_FILE_SCOPE_P (decl1))
14983         maybe_apply_pragma_weak (decl1);
14984     }
14985
14986   /* We are now in the scope of the function being defined.  */
14987   current_function_decl = decl1;
14988
14989   /* Save the parm names or decls from this function's declarator
14990      where store_parm_decls will find them.  */
14991   current_function_parms = DECL_ARGUMENTS (decl1);
14992
14993   /* Let the user know we're compiling this function.  */
14994   announce_function (decl1);
14995
14996   gcc_assert (DECL_INITIAL (decl1));
14997
14998   /* This function may already have been parsed, in which case just
14999      return; our caller will skip over the body without parsing.  */
15000   if (DECL_INITIAL (decl1) != error_mark_node)
15001     return true;
15002
15003   /* Initialize RTL machinery.  We cannot do this until
15004      CURRENT_FUNCTION_DECL and DECL_RESULT are set up.  We do this
15005      even when processing a template; this is how we get
15006      CFUN set up, and our per-function variables initialized.
15007      FIXME factor out the non-RTL stuff.  */
15008   bl = current_binding_level;
15009   allocate_struct_function (decl1, processing_template_decl);
15010
15011   /* Initialize the language data structures.  Whenever we start
15012      a new function, we destroy temporaries in the usual way.  */
15013   cfun->language = ggc_cleared_alloc<language_function> ();
15014   current_stmt_tree ()->stmts_are_full_exprs_p = 1;
15015   current_binding_level = bl;
15016
15017   if (!processing_template_decl && type_uses_auto (restype))
15018     {
15019       FNDECL_USED_AUTO (decl1) = true;
15020       current_function_auto_return_pattern = restype;
15021     }
15022
15023   /* Start the statement-tree, start the tree now.  */
15024   DECL_SAVED_TREE (decl1) = push_stmt_list ();
15025
15026   /* If we are (erroneously) defining a function that we have already
15027      defined before, wipe out what we knew before.  */
15028   if (!DECL_PENDING_INLINE_P (decl1))
15029     DECL_SAVED_FUNCTION_DATA (decl1) = NULL;
15030
15031   if (ctype && !doing_friend && !DECL_STATIC_FUNCTION_P (decl1))
15032     {
15033       /* We know that this was set up by `grokclassfn'.  We do not
15034          wait until `store_parm_decls', since evil parse errors may
15035          never get us to that point.  Here we keep the consistency
15036          between `current_class_type' and `current_class_ptr'.  */
15037       tree t = DECL_ARGUMENTS (decl1);
15038
15039       gcc_assert (t != NULL_TREE && TREE_CODE (t) == PARM_DECL);
15040       gcc_assert (TYPE_PTR_P (TREE_TYPE (t)));
15041
15042       cp_function_chain->x_current_class_ref
15043         = cp_build_fold_indirect_ref (t);
15044       /* Set this second to avoid shortcut in cp_build_indirect_ref.  */
15045       cp_function_chain->x_current_class_ptr = t;
15046
15047       /* Constructors and destructors need to know whether they're "in
15048          charge" of initializing virtual base classes.  */
15049       t = DECL_CHAIN (t);
15050       if (DECL_HAS_IN_CHARGE_PARM_P (decl1))
15051         {
15052           current_in_charge_parm = t;
15053           t = DECL_CHAIN (t);
15054         }
15055       if (DECL_HAS_VTT_PARM_P (decl1))
15056         {
15057           gcc_assert (DECL_NAME (t) == vtt_parm_identifier);
15058           current_vtt_parm = t;
15059         }
15060     }
15061
15062   honor_interface = (!DECL_TEMPLATE_INSTANTIATION (decl1)
15063                      /* Implicitly-defined methods (like the
15064                         destructor for a class in which no destructor
15065                         is explicitly declared) must not be defined
15066                         until their definition is needed.  So, we
15067                         ignore interface specifications for
15068                         compiler-generated functions.  */
15069                      && !DECL_ARTIFICIAL (decl1));
15070
15071   if (processing_template_decl)
15072     /* Don't mess with interface flags.  */;
15073   else if (DECL_INTERFACE_KNOWN (decl1))
15074     {
15075       tree ctx = decl_function_context (decl1);
15076
15077       if (DECL_NOT_REALLY_EXTERN (decl1))
15078         DECL_EXTERNAL (decl1) = 0;
15079
15080       if (ctx != NULL_TREE && vague_linkage_p (ctx))
15081         /* This is a function in a local class in an extern inline
15082            or template function.  */
15083         comdat_linkage (decl1);
15084     }
15085   /* If this function belongs to an interface, it is public.
15086      If it belongs to someone else's interface, it is also external.
15087      This only affects inlines and template instantiations.  */
15088   else if (!finfo->interface_unknown && honor_interface)
15089     {
15090       if (DECL_DECLARED_INLINE_P (decl1)
15091           || DECL_TEMPLATE_INSTANTIATION (decl1))
15092         {
15093           DECL_EXTERNAL (decl1)
15094             = (finfo->interface_only
15095                || (DECL_DECLARED_INLINE_P (decl1)
15096                    && ! flag_implement_inlines
15097                    && !DECL_VINDEX (decl1)));
15098
15099           /* For WIN32 we also want to put these in linkonce sections.  */
15100           maybe_make_one_only (decl1);
15101         }
15102       else
15103         DECL_EXTERNAL (decl1) = 0;
15104       DECL_INTERFACE_KNOWN (decl1) = 1;
15105       /* If this function is in an interface implemented in this file,
15106          make sure that the back end knows to emit this function
15107          here.  */
15108       if (!DECL_EXTERNAL (decl1))
15109         mark_needed (decl1);
15110     }
15111   else if (finfo->interface_unknown && finfo->interface_only
15112            && honor_interface)
15113     {
15114       /* If MULTIPLE_SYMBOL_SPACES is defined and we saw a #pragma
15115          interface, we will have both finfo->interface_unknown and
15116          finfo->interface_only set.  In that case, we don't want to
15117          use the normal heuristics because someone will supply a
15118          #pragma implementation elsewhere, and deducing it here would
15119          produce a conflict.  */
15120       comdat_linkage (decl1);
15121       DECL_EXTERNAL (decl1) = 0;
15122       DECL_INTERFACE_KNOWN (decl1) = 1;
15123       DECL_DEFER_OUTPUT (decl1) = 1;
15124     }
15125   else
15126     {
15127       /* This is a definition, not a reference.
15128          So clear DECL_EXTERNAL, unless this is a GNU extern inline.  */
15129       if (!GNU_INLINE_P (decl1))
15130         DECL_EXTERNAL (decl1) = 0;
15131
15132       if ((DECL_DECLARED_INLINE_P (decl1)
15133            || DECL_TEMPLATE_INSTANTIATION (decl1))
15134           && ! DECL_INTERFACE_KNOWN (decl1))
15135         DECL_DEFER_OUTPUT (decl1) = 1;
15136       else
15137         DECL_INTERFACE_KNOWN (decl1) = 1;
15138     }
15139
15140   /* Determine the ELF visibility attribute for the function.  We must not
15141      do this before calling "pushdecl", as we must allow "duplicate_decls"
15142      to merge any attributes appropriately.  We also need to wait until
15143      linkage is set.  */
15144   if (!DECL_CLONED_FUNCTION_P (decl1))
15145     determine_visibility (decl1);
15146
15147   if (!processing_template_decl)
15148     maybe_instantiate_noexcept (decl1);
15149
15150   begin_scope (sk_function_parms, decl1);
15151
15152   ++function_depth;
15153
15154   if (DECL_DESTRUCTOR_P (decl1)
15155       || (DECL_CONSTRUCTOR_P (decl1)
15156           && targetm.cxx.cdtor_returns_this ()))
15157     {
15158       cdtor_label = create_artificial_label (input_location);
15159       LABEL_DECL_CDTOR (cdtor_label) = true;
15160     }
15161
15162   start_fname_decls ();
15163
15164   store_parm_decls (current_function_parms);
15165
15166   if (!processing_template_decl
15167       && (flag_lifetime_dse > 1)
15168       && DECL_CONSTRUCTOR_P (decl1)
15169       && !DECL_CLONED_FUNCTION_P (decl1)
15170       /* Clobbering an empty base is harmful if it overlays real data.  */
15171       && !is_empty_class (current_class_type)
15172       /* We can't clobber safely for an implicitly-defined default constructor
15173          because part of the initialization might happen before we enter the
15174          constructor, via AGGR_INIT_ZERO_FIRST (c++/68006).  */
15175       && !implicit_default_ctor_p (decl1))
15176     finish_expr_stmt (build_clobber_this ());
15177
15178   if (!processing_template_decl
15179       && DECL_CONSTRUCTOR_P (decl1)
15180       && sanitize_flags_p (SANITIZE_VPTR)
15181       && !DECL_CLONED_FUNCTION_P (decl1)
15182       && !implicit_default_ctor_p (decl1))
15183     cp_ubsan_maybe_initialize_vtbl_ptrs (current_class_ptr);
15184
15185   start_lambda_scope (decl1);
15186
15187   return true;
15188 }
15189
15190
15191 /* Like start_preparsed_function, except that instead of a
15192    FUNCTION_DECL, this function takes DECLSPECS and DECLARATOR.
15193
15194    Returns true on success.  If the DECLARATOR is not suitable
15195    for a function, we return false, which tells the parser to
15196    skip the entire function.  */
15197
15198 bool
15199 start_function (cp_decl_specifier_seq *declspecs,
15200                 const cp_declarator *declarator,
15201                 tree attrs)
15202 {
15203   tree decl1;
15204
15205   decl1 = grokdeclarator (declarator, declspecs, FUNCDEF, 1, &attrs);
15206   invoke_plugin_callbacks (PLUGIN_START_PARSE_FUNCTION, decl1);
15207   if (decl1 == error_mark_node)
15208     return false;
15209   /* If the declarator is not suitable for a function definition,
15210      cause a syntax error.  */
15211   if (decl1 == NULL_TREE || TREE_CODE (decl1) != FUNCTION_DECL)
15212     {
15213       error ("invalid function declaration");
15214       return false;
15215     }
15216
15217   if (DECL_MAIN_P (decl1))
15218     /* main must return int.  grokfndecl should have corrected it
15219        (and issued a diagnostic) if the user got it wrong.  */
15220     gcc_assert (same_type_p (TREE_TYPE (TREE_TYPE (decl1)),
15221                              integer_type_node));
15222
15223   return start_preparsed_function (decl1, attrs, /*flags=*/SF_DEFAULT);
15224 }
15225 \f
15226 /* Returns true iff an EH_SPEC_BLOCK should be created in the body of
15227    FN.  */
15228
15229 static bool
15230 use_eh_spec_block (tree fn)
15231 {
15232   return (flag_exceptions && flag_enforce_eh_specs
15233           && !processing_template_decl
15234           && !type_throw_all_p (TREE_TYPE (fn))
15235           /* We insert the EH_SPEC_BLOCK only in the original
15236              function; then, it is copied automatically to the
15237              clones.  */
15238           && !DECL_CLONED_FUNCTION_P (fn)
15239           /* Implicitly-generated constructors and destructors have
15240              exception specifications.  However, those specifications
15241              are the union of the possible exceptions specified by the
15242              constructors/destructors for bases and members, so no
15243              unallowed exception will ever reach this function.  By
15244              not creating the EH_SPEC_BLOCK we save a little memory,
15245              and we avoid spurious warnings about unreachable
15246              code.  */
15247           && !DECL_DEFAULTED_FN (fn));
15248 }
15249
15250 /* Store the parameter declarations into the current function declaration.
15251    This is called after parsing the parameter declarations, before
15252    digesting the body of the function.
15253
15254    Also install to binding contour return value identifier, if any.  */
15255
15256 static void
15257 store_parm_decls (tree current_function_parms)
15258 {
15259   tree fndecl = current_function_decl;
15260   tree parm;
15261
15262   /* This is a chain of any other decls that came in among the parm
15263      declarations.  If a parm is declared with  enum {foo, bar} x;
15264      then CONST_DECLs for foo and bar are put here.  */
15265   tree nonparms = NULL_TREE;
15266
15267   if (current_function_parms)
15268     {
15269       /* This case is when the function was defined with an ANSI prototype.
15270          The parms already have decls, so we need not do anything here
15271          except record them as in effect
15272          and complain if any redundant old-style parm decls were written.  */
15273
15274       tree specparms = current_function_parms;
15275       tree next;
15276
15277       /* Must clear this because it might contain TYPE_DECLs declared
15278              at class level.  */
15279       current_binding_level->names = NULL;
15280
15281       /* If we're doing semantic analysis, then we'll call pushdecl
15282              for each of these.  We must do them in reverse order so that
15283              they end in the correct forward order.  */
15284       specparms = nreverse (specparms);
15285
15286       for (parm = specparms; parm; parm = next)
15287         {
15288           next = DECL_CHAIN (parm);
15289           if (TREE_CODE (parm) == PARM_DECL)
15290             pushdecl (parm);
15291           else
15292             {
15293               /* If we find an enum constant or a type tag,
15294                  put it aside for the moment.  */
15295               TREE_CHAIN (parm) = NULL_TREE;
15296               nonparms = chainon (nonparms, parm);
15297             }
15298         }
15299
15300       /* Get the decls in their original chain order and record in the
15301          function.  This is all and only the PARM_DECLs that were
15302          pushed into scope by the loop above.  */
15303       DECL_ARGUMENTS (fndecl) = get_local_decls ();
15304     }
15305   else
15306     DECL_ARGUMENTS (fndecl) = NULL_TREE;
15307
15308   /* Now store the final chain of decls for the arguments
15309      as the decl-chain of the current lexical scope.
15310      Put the enumerators in as well, at the front so that
15311      DECL_ARGUMENTS is not modified.  */
15312   current_binding_level->names = chainon (nonparms, DECL_ARGUMENTS (fndecl));
15313
15314   if (use_eh_spec_block (current_function_decl))
15315     current_eh_spec_block = begin_eh_spec_block ();
15316 }
15317
15318 \f
15319 /* We have finished doing semantic analysis on DECL, but have not yet
15320    generated RTL for its body.  Save away our current state, so that
15321    when we want to generate RTL later we know what to do.  */
15322
15323 static void
15324 save_function_data (tree decl)
15325 {
15326   struct language_function *f;
15327
15328   /* Save the language-specific per-function data so that we can
15329      get it back when we really expand this function.  */
15330   gcc_assert (!DECL_PENDING_INLINE_P (decl));
15331
15332   /* Make a copy.  */
15333   f = ggc_alloc<language_function> ();
15334   memcpy (f, cp_function_chain, sizeof (struct language_function));
15335   DECL_SAVED_FUNCTION_DATA (decl) = f;
15336
15337   /* Clear out the bits we don't need.  */
15338   f->base.x_stmt_tree.x_cur_stmt_list = NULL;
15339   f->bindings = NULL;
15340   f->x_local_names = NULL;
15341   f->base.local_typedefs = NULL;
15342 }
15343
15344
15345 /* Set the return value of the constructor (if present).  */
15346
15347 static void
15348 finish_constructor_body (void)
15349 {
15350   tree val;
15351   tree exprstmt;
15352
15353   if (targetm.cxx.cdtor_returns_this ())
15354     {
15355       /* Any return from a constructor will end up here.  */
15356       add_stmt (build_stmt (input_location, LABEL_EXPR, cdtor_label));
15357
15358       val = DECL_ARGUMENTS (current_function_decl);
15359       val = build2 (MODIFY_EXPR, TREE_TYPE (val),
15360                     DECL_RESULT (current_function_decl), val);
15361       /* Return the address of the object.  */
15362       exprstmt = build_stmt (input_location, RETURN_EXPR, val);
15363       add_stmt (exprstmt);
15364     }
15365 }
15366
15367 /* Do all the processing for the beginning of a destructor; set up the
15368    vtable pointers and cleanups for bases and members.  */
15369
15370 static void
15371 begin_destructor_body (void)
15372 {
15373   tree compound_stmt;
15374
15375   /* If the CURRENT_CLASS_TYPE is incomplete, we will have already
15376      issued an error message.  We still want to try to process the
15377      body of the function, but initialize_vtbl_ptrs will crash if
15378      TYPE_BINFO is NULL.  */
15379   if (COMPLETE_TYPE_P (current_class_type))
15380     {
15381       compound_stmt = begin_compound_stmt (0);
15382       /* Make all virtual function table pointers in non-virtual base
15383          classes point to CURRENT_CLASS_TYPE's virtual function
15384          tables.  */
15385       initialize_vtbl_ptrs (current_class_ptr);
15386       finish_compound_stmt (compound_stmt);
15387
15388       if (flag_lifetime_dse
15389           /* Clobbering an empty base is harmful if it overlays real data.  */
15390           && !is_empty_class (current_class_type))
15391       {
15392         if (sanitize_flags_p (SANITIZE_VPTR)
15393             && (flag_sanitize_recover & SANITIZE_VPTR) == 0
15394             && TYPE_CONTAINS_VPTR_P (current_class_type))
15395           {
15396             tree binfo = TYPE_BINFO (current_class_type);
15397             tree ref
15398               = cp_build_fold_indirect_ref (current_class_ptr);
15399
15400             tree vtbl_ptr = build_vfield_ref (ref, TREE_TYPE (binfo));
15401             tree vtbl = build_zero_cst (TREE_TYPE (vtbl_ptr));
15402             tree stmt = cp_build_modify_expr (input_location, vtbl_ptr,
15403                                               NOP_EXPR, vtbl,
15404                                               tf_warning_or_error);
15405             finish_decl_cleanup (NULL_TREE, stmt);
15406           }
15407         else
15408           finish_decl_cleanup (NULL_TREE, build_clobber_this ());
15409       }
15410
15411       /* And insert cleanups for our bases and members so that they
15412          will be properly destroyed if we throw.  */
15413       push_base_cleanups ();
15414     }
15415 }
15416
15417 /* At the end of every destructor we generate code to delete the object if
15418    necessary.  Do that now.  */
15419
15420 static void
15421 finish_destructor_body (void)
15422 {
15423   tree exprstmt;
15424
15425   /* Any return from a destructor will end up here; that way all base
15426      and member cleanups will be run when the function returns.  */
15427   add_stmt (build_stmt (input_location, LABEL_EXPR, cdtor_label));
15428
15429   if (targetm.cxx.cdtor_returns_this ())
15430     {
15431       tree val;
15432
15433       val = DECL_ARGUMENTS (current_function_decl);
15434       val = build2 (MODIFY_EXPR, TREE_TYPE (val),
15435                     DECL_RESULT (current_function_decl), val);
15436       /* Return the address of the object.  */
15437       exprstmt = build_stmt (input_location, RETURN_EXPR, val);
15438       add_stmt (exprstmt);
15439     }
15440 }
15441
15442 /* Do the necessary processing for the beginning of a function body, which
15443    in this case includes member-initializers, but not the catch clauses of
15444    a function-try-block.  Currently, this means opening a binding level
15445    for the member-initializers (in a ctor), member cleanups (in a dtor),
15446    and capture proxies (in a lambda operator()).  */
15447
15448 tree
15449 begin_function_body (void)
15450 {
15451   tree stmt;
15452
15453   if (! FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
15454     return NULL_TREE;
15455
15456   if (processing_template_decl)
15457     /* Do nothing now.  */;
15458   else
15459     /* Always keep the BLOCK node associated with the outermost pair of
15460        curly braces of a function.  These are needed for correct
15461        operation of dwarfout.c.  */
15462     keep_next_level (true);
15463
15464   stmt = begin_compound_stmt (BCS_FN_BODY);
15465
15466   if (processing_template_decl)
15467     /* Do nothing now.  */;
15468   else if (DECL_DESTRUCTOR_P (current_function_decl))
15469     begin_destructor_body ();
15470
15471   return stmt;
15472 }
15473
15474 /* Do the processing for the end of a function body.  Currently, this means
15475    closing out the cleanups for fully-constructed bases and members, and in
15476    the case of the destructor, deleting the object if desired.  Again, this
15477    is only meaningful for [cd]tors, since they are the only functions where
15478    there is a significant distinction between the main body and any
15479    function catch clauses.  Handling, say, main() return semantics here
15480    would be wrong, as flowing off the end of a function catch clause for
15481    main() would also need to return 0.  */
15482
15483 void
15484 finish_function_body (tree compstmt)
15485 {
15486   if (compstmt == NULL_TREE)
15487     return;
15488
15489   /* Close the block.  */
15490   finish_compound_stmt (compstmt);
15491
15492   if (processing_template_decl)
15493     /* Do nothing now.  */;
15494   else if (DECL_CONSTRUCTOR_P (current_function_decl))
15495     finish_constructor_body ();
15496   else if (DECL_DESTRUCTOR_P (current_function_decl))
15497     finish_destructor_body ();
15498 }
15499
15500 /* Given a function, returns the BLOCK corresponding to the outermost level
15501    of curly braces, skipping the artificial block created for constructor
15502    initializers.  */
15503
15504 tree
15505 outer_curly_brace_block (tree fndecl)
15506 {
15507   tree block = DECL_INITIAL (fndecl);
15508   if (BLOCK_OUTER_CURLY_BRACE_P (block))
15509     return block;
15510   block = BLOCK_SUBBLOCKS (block);
15511   if (BLOCK_OUTER_CURLY_BRACE_P (block))
15512     return block;
15513   block = BLOCK_SUBBLOCKS (block);
15514   gcc_assert (BLOCK_OUTER_CURLY_BRACE_P (block));
15515   return block;
15516 }
15517
15518 /* If FNDECL is a class's key method, add the class to the list of
15519    keyed classes that should be emitted.  */
15520
15521 static void
15522 record_key_method_defined (tree fndecl)
15523 {
15524   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
15525       && DECL_VIRTUAL_P (fndecl)
15526       && !processing_template_decl)
15527     {
15528       tree fnclass = DECL_CONTEXT (fndecl);
15529       if (fndecl == CLASSTYPE_KEY_METHOD (fnclass))
15530         vec_safe_push (keyed_classes, fnclass);
15531     }
15532 }
15533
15534 /* Subroutine of finish_function.
15535    Save the body of constexpr functions for possible
15536    future compile time evaluation.  */
15537
15538 static void
15539 maybe_save_function_definition (tree fun)
15540 {
15541   if (!processing_template_decl
15542       && DECL_DECLARED_CONSTEXPR_P (fun)
15543       && !cp_function_chain->invalid_constexpr
15544       && !DECL_CLONED_FUNCTION_P (fun))
15545     register_constexpr_fundef (fun, DECL_SAVED_TREE (fun));
15546 }
15547
15548 /* Finish up a function declaration and compile that function
15549    all the way to assembler language output.  The free the storage
15550    for the function definition. INLINE_P is TRUE if we just
15551    finished processing the body of an in-class inline function
15552    definition.  (This processing will have taken place after the
15553    class definition is complete.)  */
15554
15555 tree
15556 finish_function (bool inline_p)
15557 {
15558   tree fndecl = current_function_decl;
15559   tree fntype, ctype = NULL_TREE;
15560
15561   /* When we get some parse errors, we can end up without a
15562      current_function_decl, so cope.  */
15563   if (fndecl == NULL_TREE)
15564     return error_mark_node;
15565
15566   finish_lambda_scope ();
15567
15568   if (c_dialect_objc ())
15569     objc_finish_function ();
15570
15571   record_key_method_defined (fndecl);
15572
15573   fntype = TREE_TYPE (fndecl);
15574
15575   /*  TREE_READONLY (fndecl) = 1;
15576       This caused &foo to be of type ptr-to-const-function
15577       which then got a warning when stored in a ptr-to-function variable.  */
15578
15579   gcc_assert (building_stmt_list_p ());
15580   /* The current function is being defined, so its DECL_INITIAL should
15581      be set, and unless there's a multiple definition, it should be
15582      error_mark_node.  */
15583   gcc_assert (DECL_INITIAL (fndecl) == error_mark_node);
15584
15585   /* For a cloned function, we've already got all the code we need;
15586      there's no need to add any extra bits.  */
15587   if (!DECL_CLONED_FUNCTION_P (fndecl))
15588     {
15589       /* Make it so that `main' always returns 0 by default.  */
15590       if (DECL_MAIN_P (current_function_decl))
15591         finish_return_stmt (integer_zero_node);
15592
15593       if (use_eh_spec_block (current_function_decl))
15594         finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
15595                               (TREE_TYPE (current_function_decl)),
15596                               current_eh_spec_block);
15597     }
15598
15599   /* If we're saving up tree structure, tie off the function now.  */
15600   DECL_SAVED_TREE (fndecl) = pop_stmt_list (DECL_SAVED_TREE (fndecl));
15601
15602   finish_fname_decls ();
15603
15604   /* If this function can't throw any exceptions, remember that.  */
15605   if (!processing_template_decl
15606       && !cp_function_chain->can_throw
15607       && !flag_non_call_exceptions
15608       && !decl_replaceable_p (fndecl))
15609     TREE_NOTHROW (fndecl) = 1;
15610
15611   /* This must come after expand_function_end because cleanups might
15612      have declarations (from inline functions) that need to go into
15613      this function's blocks.  */
15614
15615   /* If the current binding level isn't the outermost binding level
15616      for this function, either there is a bug, or we have experienced
15617      syntax errors and the statement tree is malformed.  */
15618   if (current_binding_level->kind != sk_function_parms)
15619     {
15620       /* Make sure we have already experienced errors.  */
15621       gcc_assert (errorcount);
15622
15623       /* Throw away the broken statement tree and extra binding
15624          levels.  */
15625       DECL_SAVED_TREE (fndecl) = alloc_stmt_list ();
15626
15627       while (current_binding_level->kind != sk_function_parms)
15628         {
15629           if (current_binding_level->kind == sk_class)
15630             pop_nested_class ();
15631           else
15632             poplevel (0, 0, 0);
15633         }
15634     }
15635   poplevel (1, 0, 1);
15636
15637   /* Statements should always be full-expressions at the outermost set
15638      of curly braces for a function.  */
15639   gcc_assert (stmts_are_full_exprs_p ());
15640
15641   /* If there are no return statements in a function with auto return type,
15642      the return type is void.  But if the declared type is something like
15643      auto*, this is an error.  */
15644   if (!processing_template_decl && FNDECL_USED_AUTO (fndecl)
15645       && TREE_TYPE (fntype) == current_function_auto_return_pattern)
15646     {
15647       if (is_auto (current_function_auto_return_pattern))
15648         {
15649           apply_deduced_return_type (fndecl, void_type_node);
15650           fntype = TREE_TYPE (fndecl);
15651         }
15652       else if (!current_function_returns_value
15653                && !current_function_returns_null)
15654         {
15655           error ("no return statements in function returning %qT",
15656                  current_function_auto_return_pattern);
15657           inform (input_location, "only plain %<auto%> return type can be "
15658                   "deduced to %<void%>");
15659         }
15660     }
15661
15662   // If this is a concept, check that the definition is reasonable.
15663   if (DECL_DECLARED_CONCEPT_P (fndecl))
15664     check_function_concept (fndecl);
15665
15666   /* Lambda closure members are implicitly constexpr if possible.  */
15667   if (cxx_dialect >= cxx17
15668       && LAMBDA_TYPE_P (CP_DECL_CONTEXT (fndecl)))
15669     DECL_DECLARED_CONSTEXPR_P (fndecl)
15670       = ((processing_template_decl
15671           || is_valid_constexpr_fn (fndecl, /*complain*/false))
15672          && potential_constant_expression (DECL_SAVED_TREE (fndecl)));
15673
15674   /* Save constexpr function body before it gets munged by
15675      the NRV transformation.   */
15676   maybe_save_function_definition (fndecl);
15677
15678   /* Invoke the pre-genericize plugin before we start munging things.  */
15679   if (!processing_template_decl)
15680     invoke_plugin_callbacks (PLUGIN_PRE_GENERICIZE, fndecl);
15681
15682   /* Perform delayed folding before NRV transformation.  */
15683   if (!processing_template_decl)
15684     cp_fold_function (fndecl);
15685
15686   /* Set up the named return value optimization, if we can.  Candidate
15687      variables are selected in check_return_expr.  */
15688   if (current_function_return_value)
15689     {
15690       tree r = current_function_return_value;
15691       tree outer;
15692
15693       if (r != error_mark_node
15694           /* This is only worth doing for fns that return in memory--and
15695              simpler, since we don't have to worry about promoted modes.  */
15696           && aggregate_value_p (TREE_TYPE (TREE_TYPE (fndecl)), fndecl)
15697           /* Only allow this for variables declared in the outer scope of
15698              the function so we know that their lifetime always ends with a
15699              return; see g++.dg/opt/nrv6.C.  We could be more flexible if
15700              we were to do this optimization in tree-ssa.  */
15701           && (outer = outer_curly_brace_block (fndecl))
15702           && chain_member (r, BLOCK_VARS (outer)))
15703         finalize_nrv (&DECL_SAVED_TREE (fndecl), r, DECL_RESULT (fndecl));
15704
15705       current_function_return_value = NULL_TREE;
15706     }
15707
15708   /* Remember that we were in class scope.  */
15709   if (current_class_name)
15710     ctype = current_class_type;
15711
15712   /* Must mark the RESULT_DECL as being in this function.  */
15713   DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
15714
15715   /* Set the BLOCK_SUPERCONTEXT of the outermost function scope to point
15716      to the FUNCTION_DECL node itself.  */
15717   BLOCK_SUPERCONTEXT (DECL_INITIAL (fndecl)) = fndecl;
15718
15719   /* Save away current state, if appropriate.  */
15720   if (!processing_template_decl)
15721     save_function_data (fndecl);
15722
15723   /* Complain if there's just no return statement.  */
15724   if (warn_return_type
15725       && !VOID_TYPE_P (TREE_TYPE (fntype))
15726       && !dependent_type_p (TREE_TYPE (fntype))
15727       && !current_function_returns_value && !current_function_returns_null
15728       /* Don't complain if we abort or throw.  */
15729       && !current_function_returns_abnormally
15730       /* Don't complain if there's an infinite loop.  */
15731       && !current_function_infinite_loop
15732       /* Don't complain if we are declared noreturn.  */
15733       && !TREE_THIS_VOLATILE (fndecl)
15734       && !DECL_NAME (DECL_RESULT (fndecl))
15735       && !TREE_NO_WARNING (fndecl)
15736       /* Structor return values (if any) are set by the compiler.  */
15737       && !DECL_CONSTRUCTOR_P (fndecl)
15738       && !DECL_DESTRUCTOR_P (fndecl)
15739       && targetm.warn_func_return (fndecl))
15740     {
15741       warning (OPT_Wreturn_type,
15742                "no return statement in function returning non-void");
15743       TREE_NO_WARNING (fndecl) = 1;
15744     }
15745
15746   /* Store the end of the function, so that we get good line number
15747      info for the epilogue.  */
15748   cfun->function_end_locus = input_location;
15749
15750   /* Complain about parameters that are only set, but never otherwise used.  */
15751   if (warn_unused_but_set_parameter
15752       && !processing_template_decl
15753       && errorcount == unused_but_set_errorcount
15754       && !DECL_CLONED_FUNCTION_P (fndecl))
15755     {
15756       tree decl;
15757
15758       for (decl = DECL_ARGUMENTS (fndecl);
15759            decl;
15760            decl = DECL_CHAIN (decl))
15761         if (TREE_USED (decl)
15762             && TREE_CODE (decl) == PARM_DECL
15763             && !DECL_READ_P (decl)
15764             && DECL_NAME (decl)
15765             && !DECL_ARTIFICIAL (decl)
15766             && !TREE_NO_WARNING (decl)
15767             && !DECL_IN_SYSTEM_HEADER (decl)
15768             && TREE_TYPE (decl) != error_mark_node
15769             && TREE_CODE (TREE_TYPE (decl)) != REFERENCE_TYPE
15770             && (!CLASS_TYPE_P (TREE_TYPE (decl))
15771                 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl))))
15772           warning_at (DECL_SOURCE_LOCATION (decl),
15773                       OPT_Wunused_but_set_parameter,
15774                       "parameter %qD set but not used", decl);
15775       unused_but_set_errorcount = errorcount;
15776     }
15777
15778   /* Complain about locally defined typedefs that are not used in this
15779      function.  */
15780   maybe_warn_unused_local_typedefs ();
15781
15782   /* Possibly warn about unused parameters.  */
15783   if (warn_unused_parameter
15784       && !processing_template_decl 
15785       && !DECL_CLONED_FUNCTION_P (fndecl))
15786     do_warn_unused_parameter (fndecl);
15787
15788   /* Genericize before inlining.  */
15789   if (!processing_template_decl)
15790     {
15791       struct language_function *f = DECL_SAVED_FUNCTION_DATA (fndecl);
15792       cp_genericize (fndecl);
15793       /* Clear out the bits we don't need.  */
15794       f->x_current_class_ptr = NULL;
15795       f->x_current_class_ref = NULL;
15796       f->x_eh_spec_block = NULL;
15797       f->x_in_charge_parm = NULL;
15798       f->x_vtt_parm = NULL;
15799       f->x_return_value = NULL;
15800       f->bindings = NULL;
15801       f->extern_decl_map = NULL;
15802       f->infinite_loops = NULL;
15803     }
15804   /* Clear out the bits we don't need.  */
15805   local_names = NULL;
15806
15807   /* We're leaving the context of this function, so zap cfun.  It's still in
15808      DECL_STRUCT_FUNCTION, and we'll restore it in tree_rest_of_compilation.  */
15809   set_cfun (NULL);
15810   current_function_decl = NULL;
15811
15812   /* If this is an in-class inline definition, we may have to pop the
15813      bindings for the template parameters that we added in
15814      maybe_begin_member_template_processing when start_function was
15815      called.  */
15816   if (inline_p)
15817     maybe_end_member_template_processing ();
15818
15819   /* Leave the scope of the class.  */
15820   if (ctype)
15821     pop_nested_class ();
15822
15823   --function_depth;
15824
15825   /* Clean up.  */
15826   current_function_decl = NULL_TREE;
15827
15828   invoke_plugin_callbacks (PLUGIN_FINISH_PARSE_FUNCTION, fndecl);
15829   return fndecl;
15830 }
15831 \f
15832 /* Create the FUNCTION_DECL for a function definition.
15833    DECLSPECS and DECLARATOR are the parts of the declaration;
15834    they describe the return type and the name of the function,
15835    but twisted together in a fashion that parallels the syntax of C.
15836
15837    This function creates a binding context for the function body
15838    as well as setting up the FUNCTION_DECL in current_function_decl.
15839
15840    Returns a FUNCTION_DECL on success.
15841
15842    If the DECLARATOR is not suitable for a function (it defines a datum
15843    instead), we return 0, which tells yyparse to report a parse error.
15844
15845    May return void_type_node indicating that this method is actually
15846    a friend.  See grokfield for more details.
15847
15848    Came here with a `.pushlevel' .
15849
15850    DO NOT MAKE ANY CHANGES TO THIS CODE WITHOUT MAKING CORRESPONDING
15851    CHANGES TO CODE IN `grokfield'.  */
15852
15853 tree
15854 grokmethod (cp_decl_specifier_seq *declspecs,
15855             const cp_declarator *declarator, tree attrlist)
15856 {
15857   tree fndecl = grokdeclarator (declarator, declspecs, MEMFUNCDEF, 0,
15858                                 &attrlist);
15859
15860   if (fndecl == error_mark_node)
15861     return error_mark_node;
15862
15863   if (fndecl == NULL || TREE_CODE (fndecl) != FUNCTION_DECL)
15864     {
15865       error ("invalid member function declaration");
15866       return error_mark_node;
15867     }
15868
15869   if (attrlist)
15870     cplus_decl_attributes (&fndecl, attrlist, 0);
15871
15872   /* Pass friends other than inline friend functions back.  */
15873   if (fndecl == void_type_node)
15874     return fndecl;
15875
15876   if (DECL_IN_AGGR_P (fndecl))
15877     {
15878       if (DECL_CLASS_SCOPE_P (fndecl))
15879         error ("%qD is already defined in class %qT", fndecl,
15880                DECL_CONTEXT (fndecl));
15881       return error_mark_node;
15882     }
15883
15884   check_template_shadow (fndecl);
15885
15886   if (TREE_PUBLIC (fndecl))
15887     DECL_COMDAT (fndecl) = 1;
15888   DECL_DECLARED_INLINE_P (fndecl) = 1;
15889   DECL_NO_INLINE_WARNING_P (fndecl) = 1;
15890
15891   /* We process method specializations in finish_struct_1.  */
15892   if (processing_template_decl && !DECL_TEMPLATE_SPECIALIZATION (fndecl))
15893     {
15894       fndecl = push_template_decl (fndecl);
15895       if (fndecl == error_mark_node)
15896         return fndecl;
15897     }
15898
15899   if (! DECL_FRIEND_P (fndecl))
15900     {
15901       if (DECL_CHAIN (fndecl))
15902         {
15903           fndecl = copy_node (fndecl);
15904           TREE_CHAIN (fndecl) = NULL_TREE;
15905         }
15906     }
15907
15908   cp_finish_decl (fndecl, NULL_TREE, false, NULL_TREE, 0);
15909
15910   DECL_IN_AGGR_P (fndecl) = 1;
15911   return fndecl;
15912 }
15913 \f
15914
15915 /* VAR is a VAR_DECL.  If its type is incomplete, remember VAR so that
15916    we can lay it out later, when and if its type becomes complete.
15917
15918    Also handle constexpr variables where the initializer involves
15919    an unlowered PTRMEM_CST because the class isn't complete yet.  */
15920
15921 void
15922 maybe_register_incomplete_var (tree var)
15923 {
15924   gcc_assert (VAR_P (var));
15925
15926   /* Keep track of variables with incomplete types.  */
15927   if (!processing_template_decl && TREE_TYPE (var) != error_mark_node
15928       && DECL_EXTERNAL (var))
15929     {
15930       tree inner_type = TREE_TYPE (var);
15931
15932       while (TREE_CODE (inner_type) == ARRAY_TYPE)
15933         inner_type = TREE_TYPE (inner_type);
15934       inner_type = TYPE_MAIN_VARIANT (inner_type);
15935
15936       if ((!COMPLETE_TYPE_P (inner_type) && CLASS_TYPE_P (inner_type))
15937           /* RTTI TD entries are created while defining the type_info.  */
15938           || (TYPE_LANG_SPECIFIC (inner_type)
15939               && TYPE_BEING_DEFINED (inner_type)))
15940         {
15941           incomplete_var iv = {var, inner_type};
15942           vec_safe_push (incomplete_vars, iv);
15943         }
15944       else if (!(DECL_LANG_SPECIFIC (var) && DECL_TEMPLATE_INFO (var))
15945                && decl_constant_var_p (var)
15946                && (TYPE_PTRMEM_P (inner_type) || CLASS_TYPE_P (inner_type)))
15947         {
15948           /* When the outermost open class is complete we can resolve any
15949              pointers-to-members.  */
15950           tree context = outermost_open_class ();
15951           incomplete_var iv = {var, context};
15952           vec_safe_push (incomplete_vars, iv);
15953         }
15954     }
15955 }
15956
15957 /* Called when a class type (given by TYPE) is defined.  If there are
15958    any existing VAR_DECLs whose type has been completed by this
15959    declaration, update them now.  */
15960
15961 void
15962 complete_vars (tree type)
15963 {
15964   unsigned ix;
15965   incomplete_var *iv;
15966
15967   for (ix = 0; vec_safe_iterate (incomplete_vars, ix, &iv); )
15968     {
15969       if (same_type_p (type, iv->incomplete_type))
15970         {
15971           tree var = iv->decl;
15972           tree type = TREE_TYPE (var);
15973
15974           if (type != error_mark_node
15975               && (TYPE_MAIN_VARIANT (strip_array_types (type))
15976                   == iv->incomplete_type))
15977             {
15978               /* Complete the type of the variable.  The VAR_DECL itself
15979                  will be laid out in expand_expr.  */
15980               complete_type (type);
15981               cp_apply_type_quals_to_decl (cp_type_quals (type), var);
15982             }
15983
15984           /* Remove this entry from the list.  */
15985           incomplete_vars->unordered_remove (ix);
15986         }
15987       else
15988         ix++;
15989     }
15990
15991   /* Check for pending declarations which may have abstract type.  */
15992   complete_type_check_abstract (type);
15993 }
15994
15995 /* If DECL is of a type which needs a cleanup, build and return an
15996    expression to perform that cleanup here.  Return NULL_TREE if no
15997    cleanup need be done.  DECL can also be a _REF when called from
15998    split_nonconstant_init_1.  */
15999
16000 tree
16001 cxx_maybe_build_cleanup (tree decl, tsubst_flags_t complain)
16002 {
16003   tree type;
16004   tree attr;
16005   tree cleanup;
16006
16007   /* Assume no cleanup is required.  */
16008   cleanup = NULL_TREE;
16009
16010   if (error_operand_p (decl))
16011     return cleanup;
16012
16013   /* Handle "__attribute__((cleanup))".  We run the cleanup function
16014      before the destructor since the destructor is what actually
16015      terminates the lifetime of the object.  */
16016   if (DECL_P (decl))
16017     attr = lookup_attribute ("cleanup", DECL_ATTRIBUTES (decl));
16018   else
16019     attr = NULL_TREE;
16020   if (attr)
16021     {
16022       tree id;
16023       tree fn;
16024       tree arg;
16025
16026       /* Get the name specified by the user for the cleanup function.  */
16027       id = TREE_VALUE (TREE_VALUE (attr));
16028       /* Look up the name to find the cleanup function to call.  It is
16029          important to use lookup_name here because that is what is
16030          used in c-common.c:handle_cleanup_attribute when performing
16031          initial checks on the attribute.  Note that those checks
16032          include ensuring that the function found is not an overloaded
16033          function, or an object with an overloaded call operator,
16034          etc.; we can rely on the fact that the function found is an
16035          ordinary FUNCTION_DECL.  */
16036       fn = lookup_name (id);
16037       arg = build_address (decl);
16038       if (!mark_used (decl, complain) && !(complain & tf_error))
16039         return error_mark_node;
16040       cleanup = cp_build_function_call_nary (fn, complain, arg, NULL_TREE);
16041       if (cleanup == error_mark_node)
16042         return error_mark_node;
16043     }
16044   /* Handle ordinary C++ destructors.  */
16045   type = TREE_TYPE (decl);
16046   if (type_build_dtor_call (type))
16047     {
16048       int flags = LOOKUP_NORMAL|LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR;
16049       tree addr;
16050       tree call;
16051
16052       if (TREE_CODE (type) == ARRAY_TYPE)
16053         addr = decl;
16054       else
16055         addr = build_address (decl);
16056
16057       call = build_delete (TREE_TYPE (addr), addr,
16058                            sfk_complete_destructor, flags, 0, complain);
16059       if (call == error_mark_node)
16060         cleanup = error_mark_node;
16061       else if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
16062         /* Discard the call.  */;
16063       else if (cleanup)
16064         cleanup = cp_build_compound_expr (cleanup, call, complain);
16065       else
16066         cleanup = call;
16067     }
16068
16069   /* build_delete sets the location of the destructor call to the
16070      current location, even though the destructor is going to be
16071      called later, at the end of the current scope.  This can lead to
16072      a "jumpy" behavior for users of debuggers when they step around
16073      the end of the block.  So let's unset the location of the
16074      destructor call instead.  */
16075   protected_set_expr_location (cleanup, UNKNOWN_LOCATION);
16076
16077   if (cleanup
16078       && DECL_P (decl)
16079       && !lookup_attribute ("warn_unused", TYPE_ATTRIBUTES (TREE_TYPE (decl)))
16080       /* Treat objects with destructors as used; the destructor may do
16081          something substantive.  */
16082       && !mark_used (decl, complain) && !(complain & tf_error))
16083     return error_mark_node;
16084
16085   return cleanup;
16086 }
16087
16088 \f
16089 /* Return the FUNCTION_TYPE that corresponds to MEMFNTYPE, which can be a
16090    FUNCTION_DECL, METHOD_TYPE, FUNCTION_TYPE, pointer or reference to
16091    METHOD_TYPE or FUNCTION_TYPE, or pointer to member function.  */
16092
16093 tree
16094 static_fn_type (tree memfntype)
16095 {
16096   tree fntype;
16097   tree args;
16098
16099   if (TYPE_PTRMEMFUNC_P (memfntype))
16100     memfntype = TYPE_PTRMEMFUNC_FN_TYPE (memfntype);
16101   if (POINTER_TYPE_P (memfntype)
16102       || TREE_CODE (memfntype) == FUNCTION_DECL)
16103     memfntype = TREE_TYPE (memfntype);
16104   if (TREE_CODE (memfntype) == FUNCTION_TYPE)
16105     return memfntype;
16106   gcc_assert (TREE_CODE (memfntype) == METHOD_TYPE);
16107   args = TYPE_ARG_TYPES (memfntype);
16108   cp_ref_qualifier rqual = type_memfn_rqual (memfntype);
16109   fntype = build_function_type (TREE_TYPE (memfntype), TREE_CHAIN (args));
16110   fntype = apply_memfn_quals (fntype, type_memfn_quals (memfntype), rqual);
16111   fntype = (cp_build_type_attribute_variant
16112             (fntype, TYPE_ATTRIBUTES (memfntype)));
16113   fntype = (build_exception_variant
16114             (fntype, TYPE_RAISES_EXCEPTIONS (memfntype)));
16115   if (TYPE_HAS_LATE_RETURN_TYPE (memfntype))
16116     TYPE_HAS_LATE_RETURN_TYPE (fntype) = 1;
16117   return fntype;
16118 }
16119
16120 /* DECL was originally constructed as a non-static member function,
16121    but turned out to be static.  Update it accordingly.  */
16122
16123 void
16124 revert_static_member_fn (tree decl)
16125 {
16126   tree stype = static_fn_type (decl);
16127   cp_cv_quals quals = type_memfn_quals (stype);
16128   cp_ref_qualifier rqual = type_memfn_rqual (stype);
16129
16130   if (quals != TYPE_UNQUALIFIED || rqual != REF_QUAL_NONE)
16131     stype = apply_memfn_quals (stype, TYPE_UNQUALIFIED, REF_QUAL_NONE);
16132
16133   TREE_TYPE (decl) = stype;
16134
16135   if (DECL_ARGUMENTS (decl))
16136     DECL_ARGUMENTS (decl) = DECL_CHAIN (DECL_ARGUMENTS (decl));
16137   DECL_STATIC_FUNCTION_P (decl) = 1;
16138 }
16139
16140 /* Return which tree structure is used by T, or TS_CP_GENERIC if T is
16141    one of the language-independent trees.  */
16142
16143 enum cp_tree_node_structure_enum
16144 cp_tree_node_structure (union lang_tree_node * t)
16145 {
16146   switch (TREE_CODE (&t->generic))
16147     {
16148     case DEFAULT_ARG:           return TS_CP_DEFAULT_ARG;
16149     case DEFERRED_NOEXCEPT:     return TS_CP_DEFERRED_NOEXCEPT;
16150     case IDENTIFIER_NODE:       return TS_CP_IDENTIFIER;
16151     case OVERLOAD:              return TS_CP_OVERLOAD;
16152     case TEMPLATE_PARM_INDEX:   return TS_CP_TPI;
16153     case PTRMEM_CST:            return TS_CP_PTRMEM;
16154     case BASELINK:              return TS_CP_BASELINK;
16155     case TEMPLATE_DECL:         return TS_CP_TEMPLATE_DECL;
16156     case STATIC_ASSERT:         return TS_CP_STATIC_ASSERT;
16157     case ARGUMENT_PACK_SELECT:  return TS_CP_ARGUMENT_PACK_SELECT;
16158     case TRAIT_EXPR:            return TS_CP_TRAIT_EXPR;
16159     case LAMBDA_EXPR:           return TS_CP_LAMBDA_EXPR;
16160     case TEMPLATE_INFO:         return TS_CP_TEMPLATE_INFO;
16161     case CONSTRAINT_INFO:       return TS_CP_CONSTRAINT_INFO;
16162     case USERDEF_LITERAL:       return TS_CP_USERDEF_LITERAL;
16163     default:                    return TS_CP_GENERIC;
16164     }
16165 }
16166
16167 /* Build the void_list_node (void_type_node having been created).  */
16168 tree
16169 build_void_list_node (void)
16170 {
16171   tree t = build_tree_list (NULL_TREE, void_type_node);
16172   return t;
16173 }
16174
16175 bool
16176 cp_missing_noreturn_ok_p (tree decl)
16177 {
16178   /* A missing noreturn is ok for the `main' function.  */
16179   return DECL_MAIN_P (decl);
16180 }
16181
16182 /* Return the decl used to identify the COMDAT group into which DECL should
16183    be placed.  */
16184
16185 tree
16186 cxx_comdat_group (tree decl)
16187 {
16188   /* Virtual tables, construction virtual tables, and virtual table
16189      tables all go in a single COMDAT group, named after the primary
16190      virtual table.  */
16191   if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
16192     decl = CLASSTYPE_VTABLES (DECL_CONTEXT (decl));
16193   /* For all other DECLs, the COMDAT group is the mangled name of the
16194      declaration itself.  */
16195   else
16196     {
16197       while (DECL_THUNK_P (decl))
16198         {
16199           /* If TARGET_USE_LOCAL_THUNK_ALIAS_P, use_thunk puts the thunk
16200              into the same section as the target function.  In that case
16201              we must return target's name.  */
16202           tree target = THUNK_TARGET (decl);
16203           if (TARGET_USE_LOCAL_THUNK_ALIAS_P (target)
16204               && DECL_SECTION_NAME (target) != NULL
16205               && DECL_ONE_ONLY (target))
16206             decl = target;
16207           else
16208             break;
16209         }
16210     }
16211
16212   return decl;
16213 }
16214
16215 /* Returns the return type for FN as written by the user, which may include
16216    a placeholder for a deduced return type.  */
16217
16218 tree
16219 fndecl_declared_return_type (tree fn)
16220 {
16221   fn = STRIP_TEMPLATE (fn);
16222   if (FNDECL_USED_AUTO (fn))
16223     {
16224       struct language_function *f = NULL;
16225       if (DECL_STRUCT_FUNCTION (fn))
16226         f = DECL_STRUCT_FUNCTION (fn)->language;
16227       if (f == NULL)
16228         f = DECL_SAVED_FUNCTION_DATA (fn);
16229       return f->x_auto_return_pattern;
16230     }
16231   return TREE_TYPE (TREE_TYPE (fn));
16232 }
16233
16234 /* Returns true iff DECL is a variable or function declared with an auto type
16235    that has not yet been deduced to a real type.  */
16236
16237 bool
16238 undeduced_auto_decl (tree decl)
16239 {
16240   if (cxx_dialect < cxx11)
16241     return false;
16242   return ((VAR_OR_FUNCTION_DECL_P (decl)
16243            || TREE_CODE (decl) == TEMPLATE_DECL)
16244           && type_uses_auto (TREE_TYPE (decl)));
16245 }
16246
16247 /* Complain if DECL has an undeduced return type.  */
16248
16249 bool
16250 require_deduced_type (tree decl, tsubst_flags_t complain)
16251 {
16252   if (undeduced_auto_decl (decl))
16253     {
16254       if (complain & tf_error)
16255         error ("use of %qD before deduction of %<auto%>", decl);
16256       return false;
16257     }
16258   return true;
16259 }
16260
16261 #include "gt-cp-decl.h"