libstdc++: [_Hashtable] Fix some implementation inconsistencies
[official-gcc.git] / gcc / cp / decl.cc
blob07fb9855cd20b4fbc91fd55b4961abedb7269299
1 /* Process declarations and variables for -*- C++ -*- compiler.
2 Copyright (C) 1988-2024 Free Software Foundation, Inc.
3 Contributed by Michael Tiemann (tiemann@cygnus.com)
5 This file is part of GCC.
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.
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.
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/>. */
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. */
26 /* ??? not all decl nodes are given the most useful possible
27 line numbers. For example, the CONST_DECLs for enum values. */
29 #include "config.h"
30 #define INCLUDE_MEMORY
31 #include "system.h"
32 #include "coretypes.h"
33 #include "target.h"
34 #include "c-family/c-target.h"
35 #include "cp-tree.h"
36 #include "timevar.h"
37 #include "stringpool.h"
38 #include "cgraph.h"
39 #include "stor-layout.h"
40 #include "varasm.h"
41 #include "attribs.h"
42 #include "flags.h"
43 #include "tree-iterator.h"
44 #include "decl.h"
45 #include "intl.h"
46 #include "toplev.h"
47 #include "c-family/c-objc.h"
48 #include "c-family/c-pragma.h"
49 #include "c-family/c-ubsan.h"
50 #include "cp/cp-name-hint.h"
51 #include "debug.h"
52 #include "plugin.h"
53 #include "builtins.h"
54 #include "gimplify.h"
55 #include "asan.h"
56 #include "gcc-rich-location.h"
57 #include "langhooks.h"
58 #include "context.h" /* For 'g'. */
59 #include "omp-general.h"
60 #include "omp-offload.h" /* For offload_vars. */
61 #include "opts.h"
62 #include "langhooks-def.h" /* For lhd_simulate_record_decl */
63 #include "coroutines.h"
65 /* Possible cases of bad specifiers type used by bad_specifiers. */
66 enum bad_spec_place {
67 BSP_VAR, /* variable */
68 BSP_PARM, /* parameter */
69 BSP_TYPE, /* type */
70 BSP_FIELD /* field */
73 static const char *redeclaration_error_message (tree, tree);
75 static bool decl_jump_unsafe (tree);
76 static void require_complete_types_for_parms (tree);
77 static tree grok_reference_init (tree, tree, tree, int);
78 static tree grokvardecl (tree, tree, tree, const cp_decl_specifier_seq *,
79 int, int, int, bool, int, tree, location_t);
80 static void check_static_variable_definition (tree, tree);
81 static void record_unknown_type (tree, const char *);
82 static int member_function_or_else (tree, tree, enum overload_flags);
83 static tree local_variable_p_walkfn (tree *, int *, void *);
84 static const char *tag_name (enum tag_types);
85 static tree lookup_and_check_tag (enum tag_types, tree, TAG_how, bool);
86 static void maybe_deduce_size_from_array_init (tree, tree);
87 static void layout_var_decl (tree);
88 static tree check_initializer (tree, tree, int, vec<tree, va_gc> **);
89 static void make_rtl_for_nonlocal_decl (tree, tree, const char *);
90 static void copy_type_enum (tree , tree);
91 static void check_function_type (tree, tree);
92 static void begin_destructor_body (void);
93 static void record_key_method_defined (tree);
94 static tree create_array_type_for_decl (tree, tree, tree, location_t);
95 static tree get_atexit_node (void);
96 static tree get_dso_handle_node (void);
97 static tree start_cleanup_fn (bool);
98 static void end_cleanup_fn (void);
99 static tree cp_make_fname_decl (location_t, tree, int);
100 static void initialize_predefined_identifiers (void);
101 static tree check_special_function_return_type
102 (special_function_kind, tree, tree, int, const location_t*);
103 static tree push_cp_library_fn (enum tree_code, tree, int);
104 static tree build_cp_library_fn (tree, enum tree_code, tree, int);
105 static void store_parm_decls (tree);
106 static void initialize_local_var (tree, tree, bool);
107 static void expand_static_init (tree, tree);
108 static location_t smallest_type_location (const cp_decl_specifier_seq*);
109 static bool identify_goto (tree, location_t, const location_t *,
110 diagnostic_t, bool);
112 /* The following symbols are subsumed in the cp_global_trees array, and
113 listed here individually for documentation purposes.
115 C++ extensions
116 tree wchar_decl_node;
118 tree vtable_entry_type;
119 tree delta_type_node;
120 tree __t_desc_type_node;
122 tree class_type_node;
123 tree unknown_type_node;
125 Array type `vtable_entry_type[]'
127 tree vtbl_type_node;
128 tree vtbl_ptr_type_node;
130 Namespaces,
132 tree std_node;
133 tree abi_node;
135 A FUNCTION_DECL which can call `abort'. Not necessarily the
136 one that the user will declare, but sufficient to be called
137 by routines that want to abort the program.
139 tree abort_fndecl;
141 Used by RTTI
142 tree type_info_type_node, tinfo_decl_id, tinfo_decl_type;
143 tree tinfo_var_id; */
145 tree cp_global_trees[CPTI_MAX];
147 /* A list of objects which have constructors or destructors
148 which reside in namespace scope. The decl is stored in
149 the TREE_VALUE slot and the initializer is stored
150 in the TREE_PURPOSE slot. */
151 tree static_aggregates;
153 /* Like static_aggregates, but for thread_local variables. */
154 tree tls_aggregates;
156 /* A hash-map mapping from variable decls to the dynamic initializer for
157 the decl. This is currently only used by OpenMP. */
158 decl_tree_map *dynamic_initializers;
160 /* -- end of C++ */
162 /* A node for the integer constant 2. */
164 tree integer_two_node;
166 /* vector of static decls. */
167 vec<tree, va_gc> *static_decls;
169 /* vector of keyed classes. */
170 vec<tree, va_gc> *keyed_classes;
172 /* Used only for jumps to as-yet undefined labels, since jumps to
173 defined labels can have their validity checked immediately. */
175 struct GTY((chain_next ("%h.next"))) named_label_use_entry {
176 struct named_label_use_entry *next;
177 /* The binding level to which this entry is *currently* attached.
178 This is initially the binding level in which the goto appeared,
179 but is modified as scopes are closed. */
180 cp_binding_level *binding_level;
181 /* The head of the names list that was current when the goto appeared,
182 or the inner scope popped. These are the decls that will *not* be
183 skipped when jumping to the label. */
184 tree names_in_scope;
185 /* If the use is a possible destination of a computed goto, a vec of decls
186 that aren't destroyed, filled in by poplevel_named_label_1. */
187 vec<tree,va_gc> *computed_goto;
188 /* The location of the goto, for error reporting. */
189 location_t o_goto_locus;
190 /* True if an OpenMP structured block scope has been closed since
191 the goto appeared. This means that the branch from the label will
192 illegally exit an OpenMP scope. */
193 bool in_omp_scope;
196 /* A list of all LABEL_DECLs in the function that have names. Here so
197 we can clear out their names' definitions at the end of the
198 function, and so we can check the validity of jumps to these labels. */
200 struct GTY((for_user)) named_label_entry {
202 tree name; /* Name of decl. */
204 tree label_decl; /* LABEL_DECL, unless deleted local label. */
206 named_label_entry *outer; /* Outer shadowed chain. */
208 /* The binding level to which the label is *currently* attached.
209 This is initially set to the binding level in which the label
210 is defined, but is modified as scopes are closed. */
211 cp_binding_level *binding_level;
213 /* The head of the names list that was current when the label was
214 defined, or the inner scope popped. These are the decls that will
215 be skipped when jumping to the label. */
216 tree names_in_scope;
218 /* A vector of all decls from all binding levels that would be
219 crossed by a backward branch to the label. */
220 vec<tree, va_gc> *bad_decls;
222 /* A list of uses of the label, before the label is defined. */
223 named_label_use_entry *uses;
225 /* True if we've seen &&label. Appalently we can't use TREE_ADDRESSABLE for
226 this, it has a more specific meaning for LABEL_DECL. */
227 bool addressed;
229 /* The following bits are set after the label is defined, and are
230 updated as scopes are popped. They indicate that a jump to the
231 label will illegally enter a scope of the given flavor. */
232 bool in_try_scope;
233 bool in_catch_scope;
234 bool in_omp_scope;
235 bool in_transaction_scope;
236 bool in_constexpr_if;
237 bool in_consteval_if;
238 bool in_stmt_expr;
241 #define named_labels cp_function_chain->x_named_labels
243 /* The number of function bodies which we are currently processing.
244 (Zero if we are at namespace scope, one inside the body of a
245 function, two inside the body of a function in a local class, etc.) */
246 int function_depth;
248 /* Whether the exception-specifier is part of a function type (i.e. C++17). */
249 bool flag_noexcept_type;
251 /* States indicating how grokdeclarator() should handle declspecs marked
252 with __attribute__((deprecated)). An object declared as
253 __attribute__((deprecated)) suppresses warnings of uses of other
254 deprecated items. */
255 enum deprecated_states deprecated_state = DEPRECATED_NORMAL;
258 /* A list of VAR_DECLs whose type was incomplete at the time the
259 variable was declared. */
261 struct GTY(()) incomplete_var {
262 tree decl;
263 tree incomplete_type;
267 static GTY(()) vec<incomplete_var, va_gc> *incomplete_vars;
269 /* Returns the kind of template specialization we are currently
270 processing, given that it's declaration contained N_CLASS_SCOPES
271 explicit scope qualifications. */
273 tmpl_spec_kind
274 current_tmpl_spec_kind (int n_class_scopes)
276 int n_template_parm_scopes = 0;
277 int seen_specialization_p = 0;
278 int innermost_specialization_p = 0;
279 cp_binding_level *b;
281 /* Scan through the template parameter scopes. */
282 for (b = current_binding_level;
283 b->kind == sk_template_parms;
284 b = b->level_chain)
286 /* If we see a specialization scope inside a parameter scope,
287 then something is wrong. That corresponds to a declaration
288 like:
290 template <class T> template <> ...
292 which is always invalid since [temp.expl.spec] forbids the
293 specialization of a class member template if the enclosing
294 class templates are not explicitly specialized as well. */
295 if (b->explicit_spec_p)
297 if (n_template_parm_scopes == 0)
298 innermost_specialization_p = 1;
299 else
300 seen_specialization_p = 1;
302 else if (seen_specialization_p == 1)
303 return tsk_invalid_member_spec;
305 ++n_template_parm_scopes;
308 /* Handle explicit instantiations. */
309 if (processing_explicit_instantiation)
311 if (n_template_parm_scopes != 0)
312 /* We've seen a template parameter list during an explicit
313 instantiation. For example:
315 template <class T> template void f(int);
317 This is erroneous. */
318 return tsk_invalid_expl_inst;
319 else
320 return tsk_expl_inst;
323 if (n_template_parm_scopes < n_class_scopes)
324 /* We've not seen enough template headers to match all the
325 specialized classes present. For example:
327 template <class T> void R<T>::S<T>::f(int);
329 This is invalid; there needs to be one set of template
330 parameters for each class. */
331 return tsk_insufficient_parms;
332 else if (n_template_parm_scopes == n_class_scopes)
333 /* We're processing a non-template declaration (even though it may
334 be a member of a template class.) For example:
336 template <class T> void S<T>::f(int);
338 The `class T' matches the `S<T>', leaving no template headers
339 corresponding to the `f'. */
340 return tsk_none;
341 else if (n_template_parm_scopes > n_class_scopes + 1)
342 /* We've got too many template headers. For example:
344 template <> template <class T> void f (T);
346 There need to be more enclosing classes. */
347 return tsk_excessive_parms;
348 else
349 /* This must be a template. It's of the form:
351 template <class T> template <class U> void S<T>::f(U);
353 This is a specialization if the innermost level was a
354 specialization; otherwise it's just a definition of the
355 template. */
356 return innermost_specialization_p ? tsk_expl_spec : tsk_template;
359 /* Exit the current scope. */
361 void
362 finish_scope (void)
364 poplevel (0, 0, 0);
367 /* When a label goes out of scope, check to see if that label was used
368 in a valid manner, and issue any appropriate warnings or errors. */
370 static void
371 check_label_used (tree label)
373 if (!processing_template_decl)
375 if (DECL_INITIAL (label) == NULL_TREE)
377 location_t location;
379 error ("label %q+D used but not defined", label);
380 location = input_location;
381 /* FIXME want (LOCATION_FILE (input_location), (line)0) */
382 /* Avoid crashing later. */
383 define_label (location, DECL_NAME (label));
385 else
386 warn_for_unused_label (label);
390 /* Helper function to sort named label entries in a vector by DECL_UID. */
392 static int
393 sort_labels (const void *a, const void *b)
395 tree label1 = *(tree const *) a;
396 tree label2 = *(tree const *) b;
398 /* DECL_UIDs can never be equal. */
399 return DECL_UID (label1) > DECL_UID (label2) ? -1 : +1;
402 /* At the end of a function, all labels declared within the function
403 go out of scope. BLOCK is the top-level block for the
404 function. */
406 static void
407 pop_labels (tree block)
409 if (!named_labels)
410 return;
412 /* We need to add the labels to the block chain, so debug
413 information is emitted. But, we want the order to be stable so
414 need to sort them first. Otherwise the debug output could be
415 randomly ordered. I guess it's mostly stable, unless the hash
416 table implementation changes. */
417 auto_vec<tree, 32> labels (named_labels->elements ());
418 hash_table<named_label_hash>::iterator end (named_labels->end ());
419 for (hash_table<named_label_hash>::iterator iter
420 (named_labels->begin ()); iter != end; ++iter)
422 named_label_entry *ent = *iter;
424 gcc_checking_assert (!ent->outer);
425 if (ent->label_decl)
426 labels.quick_push (ent->label_decl);
427 ggc_free (ent);
429 named_labels = NULL;
430 labels.qsort (sort_labels);
432 while (labels.length ())
434 tree label = labels.pop ();
436 DECL_CHAIN (label) = BLOCK_VARS (block);
437 BLOCK_VARS (block) = label;
439 check_label_used (label);
443 /* At the end of a block with local labels, restore the outer definition. */
445 static void
446 pop_local_label (tree id, tree label)
448 check_label_used (label);
449 named_label_entry **slot = named_labels->find_slot_with_hash
450 (id, IDENTIFIER_HASH_VALUE (id), NO_INSERT);
451 named_label_entry *ent = *slot;
453 if (ent->outer)
454 ent = ent->outer;
455 else
457 ent = ggc_cleared_alloc<named_label_entry> ();
458 ent->name = id;
460 *slot = ent;
463 /* The following two routines are used to interface to Objective-C++.
464 The binding level is purposely treated as an opaque type. */
466 void *
467 objc_get_current_scope (void)
469 return current_binding_level;
472 /* The following routine is used by the NeXT-style SJLJ exceptions;
473 variables get marked 'volatile' so as to not be clobbered by
474 _setjmp()/_longjmp() calls. All variables in the current scope,
475 as well as parent scopes up to (but not including) ENCLOSING_BLK
476 shall be thusly marked. */
478 void
479 objc_mark_locals_volatile (void *enclosing_blk)
481 cp_binding_level *scope;
483 for (scope = current_binding_level;
484 scope && scope != enclosing_blk;
485 scope = scope->level_chain)
487 tree decl;
489 for (decl = scope->names; decl; decl = TREE_CHAIN (decl))
490 objc_volatilize_decl (decl);
492 /* Do not climb up past the current function. */
493 if (scope->kind == sk_function_parms)
494 break;
498 /* True if B is the level for the condition of a constexpr if. */
500 static bool
501 level_for_constexpr_if (cp_binding_level *b)
503 return (b->kind == sk_cond && b->this_entity
504 && TREE_CODE (b->this_entity) == IF_STMT
505 && IF_STMT_CONSTEXPR_P (b->this_entity));
508 /* True if B is the level for the condition of a consteval if. */
510 static bool
511 level_for_consteval_if (cp_binding_level *b)
513 return (b->kind == sk_cond && b->this_entity
514 && TREE_CODE (b->this_entity) == IF_STMT
515 && IF_STMT_CONSTEVAL_P (b->this_entity));
518 /* True if T is a non-static VAR_DECL that has a non-trivial destructor.
519 See [stmt.dcl]/2. */
521 static bool
522 automatic_var_with_nontrivial_dtor_p (const_tree t)
524 if (error_operand_p (t))
525 return false;
527 return (VAR_P (t)
528 && decl_storage_duration (CONST_CAST_TREE (t)) == dk_auto
529 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (t)));
532 /* Update data for defined and undefined labels when leaving a scope. */
535 poplevel_named_label_1 (named_label_entry **slot, cp_binding_level *bl)
537 named_label_entry *ent = *slot;
538 cp_binding_level *obl = bl->level_chain;
540 if (ent->binding_level == bl)
542 tree decl;
544 /* ENT->NAMES_IN_SCOPE may contain a mixture of DECLs and
545 TREE_LISTs representing OVERLOADs, so be careful. */
546 for (decl = ent->names_in_scope; decl; decl = (DECL_P (decl)
547 ? DECL_CHAIN (decl)
548 : TREE_CHAIN (decl)))
549 if (decl_jump_unsafe (decl))
550 vec_safe_push (ent->bad_decls, decl);
552 ent->binding_level = obl;
553 ent->names_in_scope = obl->names;
554 switch (bl->kind)
556 case sk_try:
557 ent->in_try_scope = true;
558 break;
559 case sk_catch:
560 ent->in_catch_scope = true;
561 break;
562 case sk_omp:
563 ent->in_omp_scope = true;
564 break;
565 case sk_transaction:
566 ent->in_transaction_scope = true;
567 break;
568 case sk_stmt_expr:
569 ent->in_stmt_expr = true;
570 break;
571 case sk_block:
572 if (level_for_constexpr_if (bl->level_chain))
573 ent->in_constexpr_if = true;
574 else if (level_for_consteval_if (bl->level_chain))
575 ent->in_consteval_if = true;
576 break;
577 default:
578 break;
581 else if (ent->uses)
583 struct named_label_use_entry *use;
585 for (use = ent->uses; use ; use = use->next)
586 if (use->binding_level == bl)
588 if (auto &cg = use->computed_goto)
590 if (bl->kind == sk_catch)
591 vec_safe_push (cg, get_identifier ("catch"));
592 for (tree d = use->names_in_scope; d; d = DECL_CHAIN (d))
593 if (automatic_var_with_nontrivial_dtor_p (d))
594 vec_safe_push (cg, d);
597 use->binding_level = obl;
598 use->names_in_scope = obl->names;
599 if (bl->kind == sk_omp)
600 use->in_omp_scope = true;
604 return 1;
607 /* Saved errorcount to avoid -Wunused-but-set-{parameter,variable} warnings
608 when errors were reported, except for -Werror-unused-but-set-*. */
609 static int unused_but_set_errorcount;
611 /* Exit a binding level.
612 Pop the level off, and restore the state of the identifier-decl mappings
613 that were in effect when this level was entered.
615 If KEEP == 1, this level had explicit declarations, so
616 and create a "block" (a BLOCK node) for the level
617 to record its declarations and subblocks for symbol table output.
619 If FUNCTIONBODY is nonzero, this level is the body of a function,
620 so create a block as if KEEP were set and also clear out all
621 label names.
623 If REVERSE is nonzero, reverse the order of decls before putting
624 them into the BLOCK. */
626 tree
627 poplevel (int keep, int reverse, int functionbody)
629 tree link;
630 /* The chain of decls was accumulated in reverse order.
631 Put it into forward order, just for cleanliness. */
632 tree decls;
633 tree subblocks;
634 tree block;
635 tree decl;
636 scope_kind kind;
638 auto_cond_timevar tv (TV_NAME_LOOKUP);
639 restart:
641 block = NULL_TREE;
643 gcc_assert (current_binding_level->kind != sk_class
644 && current_binding_level->kind != sk_namespace);
646 if (current_binding_level->kind == sk_cleanup)
647 functionbody = 0;
648 subblocks = functionbody >= 0 ? current_binding_level->blocks : 0;
650 gcc_assert (!vec_safe_length (current_binding_level->class_shadowed));
652 /* We used to use KEEP == 2 to indicate that the new block should go
653 at the beginning of the list of blocks at this binding level,
654 rather than the end. This hack is no longer used. */
655 gcc_assert (keep == 0 || keep == 1);
657 if (current_binding_level->keep)
658 keep = 1;
660 /* Any uses of undefined labels, and any defined labels, now operate
661 under constraints of next binding contour. */
662 if (cfun && !functionbody && named_labels)
663 named_labels->traverse<cp_binding_level *, poplevel_named_label_1>
664 (current_binding_level);
666 /* Get the decls in the order they were written.
667 Usually current_binding_level->names is in reverse order.
668 But parameter decls were previously put in forward order. */
670 decls = current_binding_level->names;
671 if (reverse)
673 decls = nreverse (decls);
674 current_binding_level->names = decls;
677 /* If there were any declarations or structure tags in that level,
678 or if this level is a function body,
679 create a BLOCK to record them for the life of this function. */
680 block = NULL_TREE;
681 /* Avoid function body block if possible. */
682 if (functionbody && subblocks && BLOCK_CHAIN (subblocks) == NULL_TREE)
683 keep = 0;
684 else if (keep == 1 || functionbody)
685 block = make_node (BLOCK);
686 if (block != NULL_TREE)
688 BLOCK_VARS (block) = decls;
689 BLOCK_SUBBLOCKS (block) = subblocks;
692 /* In each subblock, record that this is its superior. */
693 if (keep >= 0)
694 for (link = subblocks; link; link = BLOCK_CHAIN (link))
695 BLOCK_SUPERCONTEXT (link) = block;
697 /* Before we remove the declarations first check for unused variables. */
698 if ((warn_unused_variable || warn_unused_but_set_variable)
699 && current_binding_level->kind != sk_template_parms
700 && !processing_template_decl)
701 for (tree d = get_local_decls (); d; d = TREE_CHAIN (d))
703 /* There are cases where D itself is a TREE_LIST. See in
704 push_local_binding where the list of decls returned by
705 getdecls is built. */
706 tree udecl = TREE_CODE (d) == TREE_LIST ? TREE_VALUE (d) : d;
707 decl = strip_using_decl (udecl);
709 tree type = TREE_TYPE (decl);
710 if (VAR_P (decl)
711 && (!TREE_USED (decl) || !DECL_READ_P (decl))
712 && !DECL_IN_SYSTEM_HEADER (udecl)
713 /* For structured bindings, consider only real variables, not
714 subobjects. */
715 && (DECL_DECOMPOSITION_P (decl) ? DECL_DECOMP_IS_BASE (decl)
716 : (DECL_NAME (decl) && !DECL_ARTIFICIAL (decl)))
717 /* Don't warn about name-independent declarations. */
718 && !name_independent_decl_p (decl)
719 && type != error_mark_node
720 && (!CLASS_TYPE_P (type)
721 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
722 || lookup_attribute ("warn_unused",
723 TYPE_ATTRIBUTES (TREE_TYPE (decl)))))
725 if (!TREE_USED (decl))
727 if (TREE_CODE (udecl) == USING_DECL)
728 warning_at (DECL_SOURCE_LOCATION (udecl),
729 OPT_Wunused_variable,
730 "unused using-declaration %qD", udecl);
731 else if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
732 warning_at (DECL_SOURCE_LOCATION (decl),
733 OPT_Wunused_variable,
734 "unused structured binding declaration");
735 else
736 warning_at (DECL_SOURCE_LOCATION (decl),
737 OPT_Wunused_variable, "unused variable %qD", decl);
738 suppress_warning (decl, OPT_Wunused_variable);
740 else if (DECL_CONTEXT (decl) == current_function_decl
741 // For -Wunused-but-set-variable leave references alone.
742 && !TYPE_REF_P (TREE_TYPE (decl))
743 && errorcount == unused_but_set_errorcount)
745 if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
746 warning_at (DECL_SOURCE_LOCATION (decl),
747 OPT_Wunused_but_set_variable, "structured "
748 "binding declaration set but not used");
749 else
750 warning_at (DECL_SOURCE_LOCATION (decl),
751 OPT_Wunused_but_set_variable,
752 "variable %qD set but not used", decl);
753 unused_but_set_errorcount = errorcount;
758 /* Remove declarations for all the DECLs in this level. */
759 for (link = decls; link; link = TREE_CHAIN (link))
761 tree name;
762 if (TREE_CODE (link) == TREE_LIST)
764 decl = TREE_VALUE (link);
765 name = TREE_PURPOSE (link);
766 gcc_checking_assert (name);
768 else
770 decl = link;
771 name = DECL_NAME (decl);
774 /* Remove the binding. */
775 if (TREE_CODE (decl) == LABEL_DECL)
776 pop_local_label (name, decl);
777 else
778 pop_local_binding (name, decl);
781 /* Restore the IDENTIFIER_TYPE_VALUEs. */
782 for (link = current_binding_level->type_shadowed;
783 link; link = TREE_CHAIN (link))
784 SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (link), TREE_VALUE (link));
786 /* There may be OVERLOADs (wrapped in TREE_LISTs) on the BLOCK_VARs
787 list if a `using' declaration put them there. The debugging
788 back ends won't understand OVERLOAD, so we remove them here.
789 Because the BLOCK_VARS are (temporarily) shared with
790 CURRENT_BINDING_LEVEL->NAMES we must do this fixup after we have
791 popped all the bindings. Also remove undeduced 'auto' decls,
792 which LTO doesn't understand, and can't have been used by anything. */
793 if (block)
795 tree* d;
797 for (d = &BLOCK_VARS (block); *d; )
799 if (TREE_CODE (*d) == TREE_LIST
800 || (!processing_template_decl
801 && undeduced_auto_decl (*d)))
802 *d = TREE_CHAIN (*d);
803 else
804 d = &DECL_CHAIN (*d);
808 /* If the level being exited is the top level of a function,
809 check over all the labels. */
810 if (functionbody)
812 if (block)
814 /* Since this is the top level block of a function, the vars are
815 the function's parameters. Don't leave them in the BLOCK
816 because they are found in the FUNCTION_DECL instead. */
817 BLOCK_VARS (block) = 0;
818 pop_labels (block);
820 else
821 pop_labels (subblocks);
824 kind = current_binding_level->kind;
825 if (kind == sk_cleanup)
827 tree stmt;
829 /* If this is a temporary binding created for a cleanup, then we'll
830 have pushed a statement list level. Pop that, create a new
831 BIND_EXPR for the block, and insert it into the stream. */
832 stmt = pop_stmt_list (current_binding_level->statement_list);
833 stmt = c_build_bind_expr (input_location, block, stmt);
834 add_stmt (stmt);
837 leave_scope ();
838 if (functionbody)
840 /* The current function is being defined, so its DECL_INITIAL
841 should be error_mark_node. */
842 gcc_assert (DECL_INITIAL (current_function_decl) == error_mark_node);
843 DECL_INITIAL (current_function_decl) = block ? block : subblocks;
844 if (subblocks)
846 if (FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
848 if (BLOCK_SUBBLOCKS (subblocks))
849 BLOCK_OUTER_CURLY_BRACE_P (BLOCK_SUBBLOCKS (subblocks)) = 1;
851 else
852 BLOCK_OUTER_CURLY_BRACE_P (subblocks) = 1;
855 else if (block)
856 current_binding_level->blocks
857 = block_chainon (current_binding_level->blocks, block);
859 /* If we did not make a block for the level just exited,
860 any blocks made for inner levels
861 (since they cannot be recorded as subblocks in that level)
862 must be carried forward so they will later become subblocks
863 of something else. */
864 else if (subblocks)
865 current_binding_level->blocks
866 = block_chainon (current_binding_level->blocks, subblocks);
868 /* Each and every BLOCK node created here in `poplevel' is important
869 (e.g. for proper debugging information) so if we created one
870 earlier, mark it as "used". */
871 if (block)
872 TREE_USED (block) = 1;
874 /* All temporary bindings created for cleanups are popped silently. */
875 if (kind == sk_cleanup)
876 goto restart;
878 return block;
881 /* Call wrapup_globals_declarations for the globals in NAMESPACE. */
882 /* Diagnose odr-used extern inline variables without definitions
883 in the current TU. */
886 wrapup_namespace_globals ()
888 if (vec<tree, va_gc> *statics = static_decls)
890 for (tree decl : *statics)
892 if (warn_unused_function
893 && TREE_CODE (decl) == FUNCTION_DECL
894 && DECL_INITIAL (decl) == 0
895 && DECL_EXTERNAL (decl)
896 && !TREE_PUBLIC (decl)
897 && !DECL_ARTIFICIAL (decl)
898 && !DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
899 && !warning_suppressed_p (decl, OPT_Wunused_function))
900 warning_at (DECL_SOURCE_LOCATION (decl),
901 OPT_Wunused_function,
902 "%qF declared %<static%> but never defined", decl);
904 if (VAR_P (decl)
905 && DECL_EXTERNAL (decl)
906 && DECL_INLINE_VAR_P (decl)
907 && DECL_ODR_USED (decl))
908 error_at (DECL_SOURCE_LOCATION (decl),
909 "odr-used inline variable %qD is not defined", decl);
912 /* Clear out the list, so we don't rescan next time. */
913 static_decls = NULL;
915 /* Write out any globals that need to be output. */
916 return wrapup_global_declarations (statics->address (),
917 statics->length ());
919 return 0;
922 /* In C++, you don't have to write `struct S' to refer to `S'; you
923 can just use `S'. We accomplish this by creating a TYPE_DECL as
924 if the user had written `typedef struct S S'. Create and return
925 the TYPE_DECL for TYPE. */
927 tree
928 create_implicit_typedef (tree name, tree type)
930 tree decl;
932 decl = build_decl (input_location, TYPE_DECL, name, type);
933 DECL_ARTIFICIAL (decl) = 1;
934 /* There are other implicit type declarations, like the one *within*
935 a class that allows you to write `S::S'. We must distinguish
936 amongst these. */
937 SET_DECL_IMPLICIT_TYPEDEF_P (decl);
938 TYPE_NAME (type) = decl;
939 TYPE_STUB_DECL (type) = decl;
941 return decl;
944 /* Function-scope local entities that need discriminators. Each entry
945 is a {decl,name} pair. VAR_DECLs for anon unions get their name
946 smashed, so we cannot rely on DECL_NAME. */
948 static GTY((deletable)) vec<tree, va_gc> *local_entities;
950 /* Determine the mangling discriminator of local DECL. There are
951 generally very few of these in any particular function. */
953 void
954 determine_local_discriminator (tree decl, tree name)
956 auto_cond_timevar tv (TV_NAME_LOOKUP);
957 retrofit_lang_decl (decl);
958 tree ctx = DECL_CONTEXT (decl);
959 size_t nelts = vec_safe_length (local_entities);
960 if (name == NULL_TREE)
961 name = (TREE_CODE (decl) == TYPE_DECL
962 && TYPE_UNNAMED_P (TREE_TYPE (decl))
963 ? NULL_TREE : DECL_NAME (decl));
964 for (size_t i = 0; i < nelts; i += 2)
966 tree *pair = &(*local_entities)[i];
967 tree d = pair[0];
968 tree n = pair[1];
969 gcc_checking_assert (d != decl);
970 if (name == n
971 && TREE_CODE (decl) == TREE_CODE (d)
972 && ctx == DECL_CONTEXT (d))
974 tree disc = integer_one_node;
975 if (DECL_DISCRIMINATOR (d))
976 disc = build_int_cst (TREE_TYPE (disc),
977 TREE_INT_CST_LOW (DECL_DISCRIMINATOR (d)) + 1);
978 DECL_DISCRIMINATOR (decl) = disc;
979 /* Replace the saved decl. */
980 pair[0] = decl;
981 decl = NULL_TREE;
982 break;
986 if (decl)
988 vec_safe_reserve (local_entities, 2);
989 local_entities->quick_push (decl);
990 local_entities->quick_push (name);
995 /* True if DECL is a constrained hidden friend as per [temp.friend]/9:
997 A non-template friend declaration with a requires-clause shall be a
998 definition. A friend function template with a constraint that depends on a
999 template parameter from an enclosing template shall be a definition. Such a
1000 constrained friend function or function template declaration does not
1001 declare the same function or function template as a declaration in any other
1002 scope.
1004 The ABI calls this a "member-like constrained friend" and mangles it like a
1005 member function to avoid collisions. */
1007 bool
1008 member_like_constrained_friend_p (tree decl)
1010 return (TREE_CODE (decl) == FUNCTION_DECL
1011 && DECL_UNIQUE_FRIEND_P (decl)
1012 && DECL_FRIEND_CONTEXT (decl)
1013 && get_constraints (decl)
1014 && (!DECL_TEMPLATE_INFO (decl)
1015 || !PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl))
1016 || (uses_outer_template_parms_in_constraints
1017 (most_general_template (decl)))));
1020 /* Returns true if functions FN1 and FN2 have equivalent trailing
1021 requires clauses. */
1023 static bool
1024 function_requirements_equivalent_p (tree newfn, tree oldfn)
1026 /* [temp.friend]/9 "Such a constrained friend function does not declare the
1027 same function as a declaration in any other scope." So no need to
1028 actually compare the requirements. */
1029 if (member_like_constrained_friend_p (newfn)
1030 || member_like_constrained_friend_p (oldfn))
1031 return false;
1033 /* Compare only trailing requirements. */
1034 tree reqs1 = get_trailing_function_requirements (newfn);
1035 tree reqs2 = get_trailing_function_requirements (oldfn);
1036 if ((reqs1 != NULL_TREE) != (reqs2 != NULL_TREE))
1037 return false;
1039 /* Substitution is needed when friends are involved. */
1040 reqs1 = maybe_substitute_reqs_for (reqs1, newfn);
1041 reqs2 = maybe_substitute_reqs_for (reqs2, oldfn);
1043 return cp_tree_equal (reqs1, reqs2);
1046 /* Two functions of the same name correspond [basic.scope.scope] if
1048 + both declare functions with the same non-object-parameter-type-list,
1049 equivalent ([temp.over.link]) trailing requires-clauses (if any, except as
1050 specified in [temp.friend]), and, if both are non-static members, they have
1051 corresponding object parameters, or
1053 + both declare function templates with equivalent
1054 non-object-parameter-type-lists, return types (if any), template-heads, and
1055 trailing requires-clauses (if any), and, if both are non-static members,
1056 they have corresponding object parameters.
1058 This is a subset of decls_match: it identifies declarations that cannot be
1059 overloaded with one another. This function does not consider DECL_NAME. */
1061 bool
1062 fns_correspond (tree newdecl, tree olddecl)
1064 if (TREE_CODE (newdecl) != TREE_CODE (olddecl))
1065 return false;
1067 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1069 if (!template_heads_equivalent_p (newdecl, olddecl))
1070 return 0;
1071 newdecl = DECL_TEMPLATE_RESULT (newdecl);
1072 olddecl = DECL_TEMPLATE_RESULT (olddecl);
1075 tree f1 = TREE_TYPE (newdecl);
1076 tree f2 = TREE_TYPE (olddecl);
1078 int rq1 = type_memfn_rqual (f1);
1079 int rq2 = type_memfn_rqual (f2);
1081 /* If only one is a non-static member function, ignore ref-quals. */
1082 if (TREE_CODE (f1) != TREE_CODE (f2))
1083 rq1 = rq2;
1084 /* Two non-static member functions have corresponding object parameters if:
1085 + exactly one is an implicit object member function with no ref-qualifier
1086 and the types of their object parameters ([dcl.fct]), after removing
1087 top-level references, are the same, or
1088 + their object parameters have the same type. */
1089 /* ??? We treat member functions of different classes as corresponding even
1090 though that means the object parameters have different types. */
1091 else if ((rq1 == REF_QUAL_NONE) != (rq2 == REF_QUAL_NONE))
1092 rq1 = rq2;
1094 bool types_match = rq1 == rq2;
1096 if (types_match)
1098 tree p1 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1099 tree p2 = FUNCTION_FIRST_USER_PARMTYPE (olddecl);
1100 types_match = compparms (p1, p2);
1103 /* Two function declarations match if either has a requires-clause
1104 then both have a requires-clause and their constraints-expressions
1105 are equivalent. */
1106 if (types_match && flag_concepts)
1107 types_match = function_requirements_equivalent_p (newdecl, olddecl);
1109 return types_match;
1112 /* Subroutine of duplicate_decls: return truthvalue of whether
1113 or not types of these decls match.
1115 For C++, we must compare the parameter list so that `int' can match
1116 `int&' in a parameter position, but `int&' is not confused with
1117 `const int&'. */
1120 decls_match (tree newdecl, tree olddecl, bool record_versions /* = true */)
1122 int types_match;
1124 if (newdecl == olddecl)
1125 return 1;
1127 if (TREE_CODE (newdecl) != TREE_CODE (olddecl))
1128 /* If the two DECLs are not even the same kind of thing, we're not
1129 interested in their types. */
1130 return 0;
1132 gcc_assert (DECL_P (newdecl));
1134 if (TREE_CODE (newdecl) == FUNCTION_DECL)
1136 /* Specializations of different templates are different functions
1137 even if they have the same type. */
1138 tree t1 = (DECL_USE_TEMPLATE (newdecl)
1139 ? DECL_TI_TEMPLATE (newdecl)
1140 : NULL_TREE);
1141 tree t2 = (DECL_USE_TEMPLATE (olddecl)
1142 ? DECL_TI_TEMPLATE (olddecl)
1143 : NULL_TREE);
1144 if (t1 != t2)
1145 return 0;
1147 if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1148 && ! (DECL_EXTERN_C_P (newdecl)
1149 && DECL_EXTERN_C_P (olddecl)))
1150 return 0;
1152 /* A new declaration doesn't match a built-in one unless it
1153 is also extern "C". */
1154 if (DECL_IS_UNDECLARED_BUILTIN (olddecl)
1155 && DECL_EXTERN_C_P (olddecl) && !DECL_EXTERN_C_P (newdecl))
1156 return 0;
1158 tree f1 = TREE_TYPE (newdecl);
1159 tree f2 = TREE_TYPE (olddecl);
1160 if (TREE_CODE (f1) != TREE_CODE (f2))
1161 return 0;
1163 /* A declaration with deduced return type should use its pre-deduction
1164 type for declaration matching. */
1165 tree r2 = fndecl_declared_return_type (olddecl);
1166 tree r1 = fndecl_declared_return_type (newdecl);
1168 /* For memchr et al, allow const void* return type (as specified by C++)
1169 when we expect void* (as in C). */
1170 if (DECL_IS_UNDECLARED_BUILTIN (olddecl)
1171 && DECL_EXTERN_C_P (olddecl)
1172 && !same_type_p (r1, r2)
1173 && TREE_CODE (r1) == POINTER_TYPE
1174 && TREE_CODE (r2) == POINTER_TYPE
1175 && comp_ptr_ttypes (TREE_TYPE (r1), TREE_TYPE (r2)))
1176 r2 = r1;
1178 tree p1 = TYPE_ARG_TYPES (f1);
1179 tree p2 = TYPE_ARG_TYPES (f2);
1181 if (same_type_p (r1, r2))
1183 if (!prototype_p (f2) && DECL_EXTERN_C_P (olddecl)
1184 && fndecl_built_in_p (olddecl))
1186 types_match = self_promoting_args_p (p1);
1187 if (p1 == void_list_node)
1188 TREE_TYPE (newdecl) = TREE_TYPE (olddecl);
1190 else
1191 types_match =
1192 compparms (p1, p2)
1193 && type_memfn_rqual (f1) == type_memfn_rqual (f2)
1194 && (TYPE_ATTRIBUTES (TREE_TYPE (newdecl)) == NULL_TREE
1195 || comp_type_attributes (TREE_TYPE (newdecl),
1196 TREE_TYPE (olddecl)) != 0);
1198 else
1199 types_match = 0;
1201 /* Two function declarations match if either has a requires-clause
1202 then both have a requires-clause and their constraints-expressions
1203 are equivalent. */
1204 if (types_match && flag_concepts)
1205 types_match = function_requirements_equivalent_p (newdecl, olddecl);
1207 /* The decls dont match if they correspond to two different versions
1208 of the same function. Disallow extern "C" functions to be
1209 versions for now. */
1210 if (types_match
1211 && !DECL_EXTERN_C_P (newdecl)
1212 && !DECL_EXTERN_C_P (olddecl)
1213 && targetm.target_option.function_versions (newdecl, olddecl))
1215 if (record_versions)
1216 maybe_version_functions (newdecl, olddecl,
1217 (!DECL_FUNCTION_VERSIONED (newdecl)
1218 || !DECL_FUNCTION_VERSIONED (olddecl)));
1219 return 0;
1222 else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1224 if (!template_heads_equivalent_p (newdecl, olddecl))
1225 return 0;
1227 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1228 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1230 if (TREE_CODE (newres) != TREE_CODE (oldres))
1231 return 0;
1233 /* Two template types match if they are the same. Otherwise, compare
1234 the underlying declarations. */
1235 if (TREE_CODE (newres) == TYPE_DECL)
1236 types_match = same_type_p (TREE_TYPE (newres), TREE_TYPE (oldres));
1237 else
1238 types_match = decls_match (newres, oldres);
1240 else
1242 /* Need to check scope for variable declaration (VAR_DECL).
1243 For typedef (TYPE_DECL), scope is ignored. */
1244 if (VAR_P (newdecl)
1245 && CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1246 /* [dcl.link]
1247 Two declarations for an object with C language linkage
1248 with the same name (ignoring the namespace that qualify
1249 it) that appear in different namespace scopes refer to
1250 the same object. */
1251 && !(DECL_EXTERN_C_P (olddecl) && DECL_EXTERN_C_P (newdecl)))
1252 return 0;
1254 if (TREE_TYPE (newdecl) == error_mark_node)
1255 types_match = TREE_TYPE (olddecl) == error_mark_node;
1256 else if (TREE_TYPE (olddecl) == NULL_TREE)
1257 types_match = TREE_TYPE (newdecl) == NULL_TREE;
1258 else if (TREE_TYPE (newdecl) == NULL_TREE)
1259 types_match = 0;
1260 else
1261 types_match = comptypes (TREE_TYPE (newdecl),
1262 TREE_TYPE (olddecl),
1263 COMPARE_REDECLARATION);
1266 return types_match;
1269 /* Mark DECL as versioned if it isn't already. */
1271 static void
1272 maybe_mark_function_versioned (tree decl)
1274 if (!DECL_FUNCTION_VERSIONED (decl))
1276 DECL_FUNCTION_VERSIONED (decl) = 1;
1277 /* If DECL_ASSEMBLER_NAME has already been set, re-mangle
1278 to include the version marker. */
1279 if (DECL_ASSEMBLER_NAME_SET_P (decl))
1280 mangle_decl (decl);
1284 /* NEWDECL and OLDDECL have identical signatures. If they are
1285 different versions adjust them and return true.
1286 If RECORD is set to true, record function versions. */
1288 bool
1289 maybe_version_functions (tree newdecl, tree olddecl, bool record)
1291 if (!targetm.target_option.function_versions (newdecl, olddecl))
1292 return false;
1294 maybe_mark_function_versioned (olddecl);
1295 if (DECL_LOCAL_DECL_P (olddecl))
1297 olddecl = DECL_LOCAL_DECL_ALIAS (olddecl);
1298 maybe_mark_function_versioned (olddecl);
1301 maybe_mark_function_versioned (newdecl);
1302 if (DECL_LOCAL_DECL_P (newdecl))
1304 /* Unfortunately, we can get here before pushdecl naturally calls
1305 push_local_extern_decl_alias, so we need to call it directly. */
1306 if (!DECL_LOCAL_DECL_ALIAS (newdecl))
1307 push_local_extern_decl_alias (newdecl);
1308 newdecl = DECL_LOCAL_DECL_ALIAS (newdecl);
1309 maybe_mark_function_versioned (newdecl);
1312 if (record)
1313 cgraph_node::record_function_versions (olddecl, newdecl);
1315 return true;
1318 /* If NEWDECL is `static' and an `extern' was seen previously,
1319 warn about it. OLDDECL is the previous declaration.
1321 Note that this does not apply to the C++ case of declaring
1322 a variable `extern const' and then later `const'.
1324 Don't complain about built-in functions, since they are beyond
1325 the user's control. */
1327 void
1328 warn_extern_redeclared_static (tree newdecl, tree olddecl)
1330 if (TREE_CODE (newdecl) == TYPE_DECL
1331 || TREE_CODE (newdecl) == TEMPLATE_DECL
1332 || TREE_CODE (newdecl) == CONST_DECL
1333 || TREE_CODE (newdecl) == NAMESPACE_DECL)
1334 return;
1336 /* Don't get confused by static member functions; that's a different
1337 use of `static'. */
1338 if (TREE_CODE (newdecl) == FUNCTION_DECL
1339 && DECL_STATIC_FUNCTION_P (newdecl))
1340 return;
1342 /* If the old declaration was `static', or the new one isn't, then
1343 everything is OK. */
1344 if (DECL_THIS_STATIC (olddecl) || !DECL_THIS_STATIC (newdecl))
1345 return;
1347 /* It's OK to declare a builtin function as `static'. */
1348 if (TREE_CODE (olddecl) == FUNCTION_DECL
1349 && DECL_ARTIFICIAL (olddecl))
1350 return;
1352 auto_diagnostic_group d;
1353 if (permerror (DECL_SOURCE_LOCATION (newdecl),
1354 "%qD was declared %<extern%> and later %<static%>", newdecl))
1355 inform (DECL_SOURCE_LOCATION (olddecl),
1356 "previous declaration of %qD", olddecl);
1359 /* NEW_DECL is a redeclaration of OLD_DECL; both are functions or
1360 function templates. If their exception specifications do not
1361 match, issue a diagnostic. */
1363 static void
1364 check_redeclaration_exception_specification (tree new_decl,
1365 tree old_decl)
1367 tree new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1368 tree old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1370 /* Two default specs are equivalent, don't force evaluation. */
1371 if (UNEVALUATED_NOEXCEPT_SPEC_P (new_exceptions)
1372 && UNEVALUATED_NOEXCEPT_SPEC_P (old_exceptions))
1373 return;
1375 if (!type_dependent_expression_p (old_decl))
1377 maybe_instantiate_noexcept (new_decl);
1378 maybe_instantiate_noexcept (old_decl);
1380 new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1381 old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1383 /* [except.spec]
1385 If any declaration of a function has an exception-specification,
1386 all declarations, including the definition and an explicit
1387 specialization, of that function shall have an
1388 exception-specification with the same set of type-ids. */
1389 if (!DECL_IS_UNDECLARED_BUILTIN (old_decl)
1390 && !DECL_IS_UNDECLARED_BUILTIN (new_decl)
1391 && !comp_except_specs (new_exceptions, old_exceptions, ce_normal))
1393 const char *const msg
1394 = G_("declaration of %qF has a different exception specifier");
1395 bool complained = true;
1396 location_t new_loc = DECL_SOURCE_LOCATION (new_decl);
1397 auto_diagnostic_group d;
1399 if (DECL_IN_SYSTEM_HEADER (old_decl) && DECL_EXTERN_C_P (old_decl))
1400 /* Don't fuss about the C library; the C library functions are not
1401 specified to have exception specifications (just behave as if they
1402 have them), but some implementations include them. */
1403 complained = pedwarn (new_loc, OPT_Wsystem_headers, msg, new_decl);
1404 else if (!flag_exceptions)
1405 /* We used to silently permit mismatched eh specs with
1406 -fno-exceptions, so only complain if -pedantic. */
1407 complained = pedwarn (new_loc, OPT_Wpedantic, msg, new_decl);
1408 else if (!new_exceptions)
1409 /* Reduce to pedwarn for omitted exception specification. No warning
1410 flag for this; silence the warning by correcting the code. */
1411 complained = pedwarn (new_loc, 0, msg, new_decl);
1412 else
1413 error_at (new_loc, msg, new_decl);
1415 if (complained)
1416 inform (DECL_SOURCE_LOCATION (old_decl),
1417 "from previous declaration %qF", old_decl);
1419 /* Copy the old exception specification if new_decl has none. Unless the
1420 old decl is extern "C", as obscure code might depend on the type of
1421 the new declaration (e.g. noexcept-type19.C). */
1422 if (!new_exceptions && !DECL_EXTERN_C_P (old_decl))
1423 TREE_TYPE (new_decl)
1424 = build_exception_variant (TREE_TYPE (new_decl), old_exceptions);
1428 /* Return true if OLD_DECL and NEW_DECL agree on constexprness.
1429 Otherwise issue diagnostics. */
1431 bool
1432 validate_constexpr_redeclaration (tree old_decl, tree new_decl)
1434 old_decl = STRIP_TEMPLATE (old_decl);
1435 new_decl = STRIP_TEMPLATE (new_decl);
1436 if (!VAR_OR_FUNCTION_DECL_P (old_decl)
1437 || !VAR_OR_FUNCTION_DECL_P (new_decl))
1438 return true;
1439 if (DECL_DECLARED_CONSTEXPR_P (old_decl)
1440 == DECL_DECLARED_CONSTEXPR_P (new_decl))
1442 if (TREE_CODE (old_decl) != FUNCTION_DECL)
1443 return true;
1444 if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1445 == DECL_IMMEDIATE_FUNCTION_P (new_decl))
1446 return true;
1448 if (TREE_CODE (old_decl) == FUNCTION_DECL)
1450 /* With -fimplicit-constexpr, ignore changes in the constexpr
1451 keyword. */
1452 if (flag_implicit_constexpr
1453 && (DECL_IMMEDIATE_FUNCTION_P (new_decl)
1454 == DECL_IMMEDIATE_FUNCTION_P (old_decl)))
1455 return true;
1456 if (fndecl_built_in_p (old_decl))
1458 /* Hide a built-in declaration. */
1459 DECL_DECLARED_CONSTEXPR_P (old_decl)
1460 = DECL_DECLARED_CONSTEXPR_P (new_decl);
1461 if (DECL_IMMEDIATE_FUNCTION_P (new_decl))
1462 SET_DECL_IMMEDIATE_FUNCTION_P (old_decl);
1463 return true;
1465 /* 7.1.5 [dcl.constexpr]
1466 Note: An explicit specialization can differ from the template
1467 declaration with respect to the constexpr specifier. */
1468 if (! DECL_TEMPLATE_SPECIALIZATION (old_decl)
1469 && DECL_TEMPLATE_SPECIALIZATION (new_decl))
1470 return true;
1472 const char *kind = "constexpr";
1473 if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1474 || DECL_IMMEDIATE_FUNCTION_P (new_decl))
1475 kind = "consteval";
1476 auto_diagnostic_group d;
1477 error_at (DECL_SOURCE_LOCATION (new_decl),
1478 "redeclaration %qD differs in %qs "
1479 "from previous declaration", new_decl,
1480 kind);
1481 inform (DECL_SOURCE_LOCATION (old_decl),
1482 "previous declaration %qD", old_decl);
1483 return false;
1485 return true;
1488 /* DECL is a redeclaration of a function or function template. If
1489 it does have default arguments issue a diagnostic. Note: this
1490 function is used to enforce the requirements in C++11 8.3.6 about
1491 no default arguments in redeclarations. */
1493 static void
1494 check_redeclaration_no_default_args (tree decl)
1496 gcc_assert (DECL_DECLARES_FUNCTION_P (decl));
1498 for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
1499 t && t != void_list_node; t = TREE_CHAIN (t))
1500 if (TREE_PURPOSE (t))
1502 permerror (DECL_SOURCE_LOCATION (decl),
1503 "redeclaration of %q#D may not have default "
1504 "arguments", decl);
1505 return;
1509 /* NEWDECL is a redeclaration of a function or function template OLDDECL,
1510 in any case represented as FUNCTION_DECLs (the DECL_TEMPLATE_RESULTs of
1511 the TEMPLATE_DECLs in case of function templates). This function is used
1512 to enforce the final part of C++17 11.3.6/4, about a single declaration:
1513 "If a friend declaration specifies a default argument expression, that
1514 declaration shall be a definition and shall be the only declaration of
1515 the function or function template in the translation unit." */
1517 static void
1518 check_no_redeclaration_friend_default_args (tree olddecl, tree newdecl)
1520 if (!DECL_UNIQUE_FRIEND_P (olddecl) && !DECL_UNIQUE_FRIEND_P (newdecl))
1521 return;
1523 for (tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl),
1524 t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1525 t1 && t1 != void_list_node;
1526 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1527 if ((DECL_UNIQUE_FRIEND_P (olddecl) && TREE_PURPOSE (t1))
1528 || (DECL_UNIQUE_FRIEND_P (newdecl) && TREE_PURPOSE (t2)))
1530 auto_diagnostic_group d;
1531 if (permerror (DECL_SOURCE_LOCATION (newdecl),
1532 "friend declaration of %q#D specifies default "
1533 "arguments and isn%'t the only declaration", newdecl))
1534 inform (DECL_SOURCE_LOCATION (olddecl),
1535 "previous declaration of %q#D", olddecl);
1536 return;
1540 /* Merge tree bits that correspond to attributes noreturn, nothrow,
1541 const, malloc, and pure from NEWDECL with those of OLDDECL. */
1543 static void
1544 merge_attribute_bits (tree newdecl, tree olddecl)
1546 TREE_THIS_VOLATILE (newdecl) |= TREE_THIS_VOLATILE (olddecl);
1547 TREE_THIS_VOLATILE (olddecl) |= TREE_THIS_VOLATILE (newdecl);
1548 TREE_NOTHROW (newdecl) |= TREE_NOTHROW (olddecl);
1549 TREE_NOTHROW (olddecl) |= TREE_NOTHROW (newdecl);
1550 TREE_READONLY (newdecl) |= TREE_READONLY (olddecl);
1551 TREE_READONLY (olddecl) |= TREE_READONLY (newdecl);
1552 DECL_IS_MALLOC (newdecl) |= DECL_IS_MALLOC (olddecl);
1553 DECL_IS_MALLOC (olddecl) |= DECL_IS_MALLOC (newdecl);
1554 DECL_PURE_P (newdecl) |= DECL_PURE_P (olddecl);
1555 DECL_PURE_P (olddecl) |= DECL_PURE_P (newdecl);
1556 DECL_UNINLINABLE (newdecl) |= DECL_UNINLINABLE (olddecl);
1557 DECL_UNINLINABLE (olddecl) |= DECL_UNINLINABLE (newdecl);
1558 TREE_DEPRECATED (newdecl) |= TREE_DEPRECATED (olddecl);
1559 TREE_DEPRECATED (olddecl) |= TREE_DEPRECATED (newdecl);
1560 TREE_UNAVAILABLE (newdecl) |= TREE_UNAVAILABLE (olddecl);
1561 TREE_UNAVAILABLE (olddecl) |= TREE_UNAVAILABLE (newdecl);
1564 #define GNU_INLINE_P(fn) (DECL_DECLARED_INLINE_P (fn) \
1565 && lookup_attribute ("gnu_inline", \
1566 DECL_ATTRIBUTES (fn)))
1568 /* A subroutine of duplicate_decls. Emits a diagnostic when newdecl
1569 ambiguates olddecl. Returns true if an error occurs. */
1571 static bool
1572 duplicate_function_template_decls (tree newdecl, tree olddecl)
1574 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1575 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1576 /* Function template declarations can be differentiated by parameter
1577 and return type. */
1578 if (compparms (TYPE_ARG_TYPES (TREE_TYPE (oldres)),
1579 TYPE_ARG_TYPES (TREE_TYPE (newres)))
1580 && same_type_p (TREE_TYPE (TREE_TYPE (newdecl)),
1581 TREE_TYPE (TREE_TYPE (olddecl))))
1583 /* ... and also by their template-heads and requires-clauses. */
1584 if (template_heads_equivalent_p (newdecl, olddecl)
1585 && function_requirements_equivalent_p (newres, oldres))
1587 auto_diagnostic_group d;
1588 error ("ambiguating new declaration %q+#D", newdecl);
1589 inform (DECL_SOURCE_LOCATION (olddecl),
1590 "old declaration %q#D", olddecl);
1591 return true;
1594 /* FIXME: The types are the same but the are differences
1595 in either the template heads or function requirements.
1596 We should be able to diagnose a set of common errors
1597 stemming from these declarations. For example:
1599 template<typename T> requires C void f(...);
1600 template<typename T> void f(...) requires C;
1602 These are functionally equivalent but not equivalent. */
1605 return false;
1608 /* OLD_PARMS is the innermost set of template parameters for some template
1609 declaration, and NEW_PARMS is the corresponding set of template parameters
1610 for a redeclaration of that template. Merge the default arguments within
1611 these two sets of parameters. CLASS_P is true iff the template in
1612 question is a class template. */
1614 bool
1615 merge_default_template_args (tree new_parms, tree old_parms, bool class_p)
1617 gcc_checking_assert (TREE_VEC_LENGTH (new_parms)
1618 == TREE_VEC_LENGTH (old_parms));
1619 for (int i = 0; i < TREE_VEC_LENGTH (new_parms); i++)
1621 tree new_parm = TREE_VALUE (TREE_VEC_ELT (new_parms, i));
1622 tree old_parm = TREE_VALUE (TREE_VEC_ELT (old_parms, i));
1623 tree& new_default = TREE_PURPOSE (TREE_VEC_ELT (new_parms, i));
1624 tree& old_default = TREE_PURPOSE (TREE_VEC_ELT (old_parms, i));
1625 if (error_operand_p (new_parm) || error_operand_p (old_parm))
1626 return false;
1627 if (new_default != NULL_TREE && old_default != NULL_TREE)
1629 auto_diagnostic_group d;
1630 error ("redefinition of default argument for %q+#D", new_parm);
1631 inform (DECL_SOURCE_LOCATION (old_parm),
1632 "original definition appeared here");
1633 return false;
1635 else if (new_default != NULL_TREE)
1636 /* Update the previous template parameters (which are the ones
1637 that will really count) with the new default value. */
1638 old_default = new_default;
1639 else if (class_p && old_default != NULL_TREE)
1640 /* Update the new parameters, too; they'll be used as the
1641 parameters for any members. */
1642 new_default = old_default;
1644 return true;
1647 /* If NEWDECL is a redeclaration of OLDDECL, merge the declarations.
1648 If the redeclaration is invalid, a diagnostic is issued, and the
1649 error_mark_node is returned. Otherwise, OLDDECL is returned.
1651 If NEWDECL is not a redeclaration of OLDDECL, NULL_TREE is
1652 returned.
1654 HIDING is true if the new decl is being hidden. WAS_HIDDEN is true
1655 if the old decl was hidden.
1657 Hidden decls can be anticipated builtins, injected friends, or
1658 (coming soon) injected from a local-extern decl. */
1660 tree
1661 duplicate_decls (tree newdecl, tree olddecl, bool hiding, bool was_hidden)
1663 unsigned olddecl_uid = DECL_UID (olddecl);
1664 int types_match = 0;
1665 int new_defines_function = 0;
1666 tree new_template_info;
1667 location_t olddecl_loc = DECL_SOURCE_LOCATION (olddecl);
1668 location_t newdecl_loc = DECL_SOURCE_LOCATION (newdecl);
1670 if (newdecl == olddecl)
1671 return olddecl;
1673 types_match = decls_match (newdecl, olddecl);
1675 /* If either the type of the new decl or the type of the old decl is an
1676 error_mark_node, then that implies that we have already issued an
1677 error (earlier) for some bogus type specification, and in that case,
1678 it is rather pointless to harass the user with yet more error message
1679 about the same declaration, so just pretend the types match here. */
1680 if (TREE_TYPE (newdecl) == error_mark_node
1681 || TREE_TYPE (olddecl) == error_mark_node)
1682 return error_mark_node;
1684 /* Check for redeclaration and other discrepancies. */
1685 if (TREE_CODE (olddecl) == FUNCTION_DECL
1686 && DECL_IS_UNDECLARED_BUILTIN (olddecl))
1688 if (TREE_CODE (newdecl) != FUNCTION_DECL)
1690 /* Avoid warnings redeclaring built-ins which have not been
1691 explicitly declared. */
1692 if (was_hidden)
1694 if (TREE_PUBLIC (newdecl)
1695 && CP_DECL_CONTEXT (newdecl) == global_namespace)
1696 warning_at (newdecl_loc,
1697 OPT_Wbuiltin_declaration_mismatch,
1698 "built-in function %qD declared as non-function",
1699 newdecl);
1700 return NULL_TREE;
1703 /* If you declare a built-in or predefined function name as static,
1704 the old definition is overridden, but optionally warn this was a
1705 bad choice of name. */
1706 if (! TREE_PUBLIC (newdecl))
1708 warning_at (newdecl_loc,
1709 OPT_Wshadow,
1710 fndecl_built_in_p (olddecl)
1711 ? G_("shadowing built-in function %q#D")
1712 : G_("shadowing library function %q#D"), olddecl);
1713 /* Discard the old built-in function. */
1714 return NULL_TREE;
1716 /* If the built-in is not ansi, then programs can override
1717 it even globally without an error. */
1718 else if (! fndecl_built_in_p (olddecl))
1719 warning_at (newdecl_loc, 0,
1720 "library function %q#D redeclared as non-function %q#D",
1721 olddecl, newdecl);
1722 else
1723 error_at (newdecl_loc,
1724 "declaration of %q#D conflicts with built-in "
1725 "declaration %q#D", newdecl, olddecl);
1726 return NULL_TREE;
1728 else if (!types_match)
1730 /* Avoid warnings redeclaring built-ins which have not been
1731 explicitly declared. */
1732 if (was_hidden)
1734 tree t1, t2;
1736 /* A new declaration doesn't match a built-in one unless it
1737 is also extern "C". */
1738 gcc_assert (DECL_IS_UNDECLARED_BUILTIN (olddecl));
1739 gcc_assert (DECL_EXTERN_C_P (olddecl));
1740 if (!DECL_EXTERN_C_P (newdecl))
1741 return NULL_TREE;
1743 for (t1 = TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1744 t2 = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1745 t1 || t2;
1746 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1748 if (!t1 || !t2)
1749 break;
1750 /* FILE, tm types are not known at the time
1751 we create the builtins. */
1752 for (unsigned i = 0;
1753 i < sizeof (builtin_structptr_types)
1754 / sizeof (builtin_structptr_type);
1755 ++i)
1756 if (TREE_VALUE (t2) == builtin_structptr_types[i].node)
1758 tree t = TREE_VALUE (t1);
1760 if (TYPE_PTR_P (t)
1761 && TYPE_IDENTIFIER (TREE_TYPE (t))
1762 == get_identifier (builtin_structptr_types[i].str)
1763 && compparms (TREE_CHAIN (t1), TREE_CHAIN (t2)))
1765 tree oldargs = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1767 TYPE_ARG_TYPES (TREE_TYPE (olddecl))
1768 = TYPE_ARG_TYPES (TREE_TYPE (newdecl));
1769 types_match = decls_match (newdecl, olddecl);
1770 if (types_match)
1771 return duplicate_decls (newdecl, olddecl,
1772 hiding, was_hidden);
1773 TYPE_ARG_TYPES (TREE_TYPE (olddecl)) = oldargs;
1775 goto next_arg;
1778 if (! same_type_p (TREE_VALUE (t1), TREE_VALUE (t2)))
1779 break;
1780 next_arg:;
1783 warning_at (newdecl_loc,
1784 OPT_Wbuiltin_declaration_mismatch,
1785 "declaration of %q#D conflicts with built-in "
1786 "declaration %q#D", newdecl, olddecl);
1788 else if ((DECL_EXTERN_C_P (newdecl)
1789 && DECL_EXTERN_C_P (olddecl))
1790 || compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1791 TYPE_ARG_TYPES (TREE_TYPE (olddecl))))
1793 /* Don't really override olddecl for __* prefixed builtins
1794 except for __[^b]*_chk, the compiler might be using those
1795 explicitly. */
1796 if (fndecl_built_in_p (olddecl))
1798 tree id = DECL_NAME (olddecl);
1799 const char *name = IDENTIFIER_POINTER (id);
1800 size_t len;
1802 if (name[0] == '_'
1803 && name[1] == '_'
1804 && (startswith (name + 2, "builtin_")
1805 || (len = strlen (name)) <= strlen ("___chk")
1806 || memcmp (name + len - strlen ("_chk"),
1807 "_chk", strlen ("_chk") + 1) != 0))
1809 if (DECL_INITIAL (newdecl))
1811 error_at (newdecl_loc,
1812 "definition of %q#D ambiguates built-in "
1813 "declaration %q#D", newdecl, olddecl);
1814 return error_mark_node;
1816 auto_diagnostic_group d;
1817 if (permerror (newdecl_loc,
1818 "new declaration %q#D ambiguates built-in"
1819 " declaration %q#D", newdecl, olddecl)
1820 && flag_permissive)
1821 inform (newdecl_loc,
1822 "ignoring the %q#D declaration", newdecl);
1823 return flag_permissive ? olddecl : error_mark_node;
1827 /* A near match; override the builtin. */
1829 if (TREE_PUBLIC (newdecl))
1830 warning_at (newdecl_loc,
1831 OPT_Wbuiltin_declaration_mismatch,
1832 "new declaration %q#D ambiguates built-in "
1833 "declaration %q#D", newdecl, olddecl);
1834 else
1835 warning (OPT_Wshadow,
1836 fndecl_built_in_p (olddecl)
1837 ? G_("shadowing built-in function %q#D")
1838 : G_("shadowing library function %q#D"), olddecl);
1840 else
1841 /* Discard the old built-in function. */
1842 return NULL_TREE;
1844 /* Replace the old RTL to avoid problems with inlining. */
1845 COPY_DECL_RTL (newdecl, olddecl);
1847 else
1849 /* Even if the types match, prefer the new declarations type
1850 for built-ins which have not been explicitly declared,
1851 for exception lists, etc... */
1852 tree type = TREE_TYPE (newdecl);
1853 tree attribs = (*targetm.merge_type_attributes)
1854 (TREE_TYPE (olddecl), type);
1856 type = cp_build_type_attribute_variant (type, attribs);
1857 TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = type;
1860 /* If a function is explicitly declared "throw ()", propagate that to
1861 the corresponding builtin. */
1862 if (DECL_BUILT_IN_CLASS (olddecl) == BUILT_IN_NORMAL
1863 && was_hidden
1864 && TREE_NOTHROW (newdecl)
1865 && !TREE_NOTHROW (olddecl))
1867 enum built_in_function fncode = DECL_FUNCTION_CODE (olddecl);
1868 tree tmpdecl = builtin_decl_explicit (fncode);
1869 if (tmpdecl && tmpdecl != olddecl && types_match)
1870 TREE_NOTHROW (tmpdecl) = 1;
1873 /* Whether or not the builtin can throw exceptions has no
1874 bearing on this declarator. */
1875 TREE_NOTHROW (olddecl) = 0;
1877 if (DECL_THIS_STATIC (newdecl) && !DECL_THIS_STATIC (olddecl))
1879 /* If a builtin function is redeclared as `static', merge
1880 the declarations, but make the original one static. */
1881 DECL_THIS_STATIC (olddecl) = 1;
1882 TREE_PUBLIC (olddecl) = 0;
1884 /* Make the old declaration consistent with the new one so
1885 that all remnants of the builtin-ness of this function
1886 will be banished. */
1887 SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
1888 COPY_DECL_RTL (newdecl, olddecl);
1891 else if (TREE_CODE (olddecl) != TREE_CODE (newdecl))
1893 /* C++ Standard, 3.3, clause 4:
1894 "[Note: a namespace name or a class template name must be unique
1895 in its declarative region (7.3.2, clause 14). ]" */
1896 if (TREE_CODE (olddecl) == NAMESPACE_DECL
1897 || TREE_CODE (newdecl) == NAMESPACE_DECL)
1898 /* Namespace conflicts with not namespace. */;
1899 else if (DECL_TYPE_TEMPLATE_P (olddecl)
1900 || DECL_TYPE_TEMPLATE_P (newdecl))
1901 /* Class template conflicts. */;
1902 else if ((TREE_CODE (olddecl) == TEMPLATE_DECL
1903 && DECL_TEMPLATE_RESULT (olddecl)
1904 && TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)) == VAR_DECL)
1905 || (TREE_CODE (newdecl) == TEMPLATE_DECL
1906 && DECL_TEMPLATE_RESULT (newdecl)
1907 && TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == VAR_DECL))
1908 /* Variable template conflicts. */;
1909 else if (concept_definition_p (olddecl)
1910 || concept_definition_p (newdecl))
1911 /* Concept conflicts. */;
1912 else if ((TREE_CODE (newdecl) == FUNCTION_DECL
1913 && DECL_FUNCTION_TEMPLATE_P (olddecl))
1914 || (TREE_CODE (olddecl) == FUNCTION_DECL
1915 && DECL_FUNCTION_TEMPLATE_P (newdecl)))
1917 /* One is a function and the other is a template
1918 function. */
1919 if (!UDLIT_OPER_P (DECL_NAME (newdecl)))
1920 return NULL_TREE;
1922 /* There can only be one! */
1923 auto_diagnostic_group d;
1924 if (TREE_CODE (newdecl) == TEMPLATE_DECL
1925 && check_raw_literal_operator (olddecl))
1926 error_at (newdecl_loc,
1927 "literal operator %q#D conflicts with"
1928 " raw literal operator", newdecl);
1929 else if (check_raw_literal_operator (newdecl))
1930 error_at (newdecl_loc,
1931 "raw literal operator %q#D conflicts with"
1932 " literal operator template", newdecl);
1933 else
1934 return NULL_TREE;
1936 inform (olddecl_loc, "previous declaration %q#D", olddecl);
1937 return error_mark_node;
1939 else if (DECL_DECOMPOSITION_P (olddecl) || DECL_DECOMPOSITION_P (newdecl))
1940 /* A structured binding must be unique in its declarative region. */;
1941 else if (DECL_IMPLICIT_TYPEDEF_P (olddecl)
1942 || DECL_IMPLICIT_TYPEDEF_P (newdecl))
1943 /* One is an implicit typedef, that's ok. */
1944 return NULL_TREE;
1946 auto_diagnostic_group d;
1947 error ("%q#D redeclared as different kind of entity", newdecl);
1948 inform (olddecl_loc, "previous declaration %q#D", olddecl);
1950 return error_mark_node;
1952 else if (!types_match)
1954 if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl))
1955 /* These are certainly not duplicate declarations; they're
1956 from different scopes. */
1957 return NULL_TREE;
1959 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1961 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1962 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1964 /* The name of a class template may not be declared to refer to
1965 any other template, class, function, object, namespace, value,
1966 or type in the same scope. */
1967 if (TREE_CODE (oldres) == TYPE_DECL
1968 || TREE_CODE (newres) == TYPE_DECL)
1970 auto_diagnostic_group d;
1971 error_at (newdecl_loc,
1972 "conflicting declaration of template %q#D", newdecl);
1973 inform (olddecl_loc,
1974 "previous declaration %q#D", olddecl);
1975 return error_mark_node;
1978 else if (TREE_CODE (oldres) == FUNCTION_DECL
1979 && TREE_CODE (newres) == FUNCTION_DECL)
1981 if (duplicate_function_template_decls (newdecl, olddecl))
1982 return error_mark_node;
1983 return NULL_TREE;
1985 return NULL_TREE;
1987 if (TREE_CODE (newdecl) == FUNCTION_DECL)
1989 if (DECL_EXTERN_C_P (newdecl) && DECL_EXTERN_C_P (olddecl))
1991 auto_diagnostic_group d;
1992 error_at (newdecl_loc,
1993 "conflicting declaration of C function %q#D",
1994 newdecl);
1995 inform (olddecl_loc,
1996 "previous declaration %q#D", olddecl);
1997 return error_mark_node;
1999 /* For function versions, params and types match, but they
2000 are not ambiguous. */
2001 else if ((!DECL_FUNCTION_VERSIONED (newdecl)
2002 && !DECL_FUNCTION_VERSIONED (olddecl))
2003 /* Let constrained hidden friends coexist for now, we'll
2004 check satisfaction later. */
2005 && !member_like_constrained_friend_p (newdecl)
2006 && !member_like_constrained_friend_p (olddecl)
2007 // The functions have the same parameter types.
2008 && compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
2009 TYPE_ARG_TYPES (TREE_TYPE (olddecl)))
2010 // And the same constraints.
2011 && equivalently_constrained (newdecl, olddecl))
2013 auto_diagnostic_group d;
2014 error_at (newdecl_loc,
2015 "ambiguating new declaration of %q#D", newdecl);
2016 inform (olddecl_loc,
2017 "old declaration %q#D", olddecl);
2018 return error_mark_node;
2020 else
2021 return NULL_TREE;
2023 else
2025 auto_diagnostic_group d;
2026 error_at (newdecl_loc, "conflicting declaration %q#D", newdecl);
2027 inform (olddecl_loc,
2028 "previous declaration as %q#D", olddecl);
2029 return error_mark_node;
2032 else if (TREE_CODE (newdecl) == FUNCTION_DECL
2033 && DECL_OMP_DECLARE_REDUCTION_P (newdecl))
2035 /* OMP UDRs are never duplicates. */
2036 gcc_assert (DECL_OMP_DECLARE_REDUCTION_P (olddecl));
2037 auto_diagnostic_group d;
2038 error_at (newdecl_loc,
2039 "redeclaration of %<pragma omp declare reduction%>");
2040 inform (olddecl_loc,
2041 "previous %<pragma omp declare reduction%> declaration");
2042 return error_mark_node;
2044 else if (TREE_CODE (newdecl) == FUNCTION_DECL
2045 && ((DECL_TEMPLATE_SPECIALIZATION (olddecl)
2046 && (!DECL_TEMPLATE_INFO (newdecl)
2047 || (DECL_TI_TEMPLATE (newdecl)
2048 != DECL_TI_TEMPLATE (olddecl))))
2049 || (DECL_TEMPLATE_SPECIALIZATION (newdecl)
2050 && (!DECL_TEMPLATE_INFO (olddecl)
2051 || (DECL_TI_TEMPLATE (olddecl)
2052 != DECL_TI_TEMPLATE (newdecl))))))
2053 /* It's OK to have a template specialization and a non-template
2054 with the same type, or to have specializations of two
2055 different templates with the same type. Note that if one is a
2056 specialization, and the other is an instantiation of the same
2057 template, that we do not exit at this point. That situation
2058 can occur if we instantiate a template class, and then
2059 specialize one of its methods. This situation is valid, but
2060 the declarations must be merged in the usual way. */
2061 return NULL_TREE;
2062 else if (TREE_CODE (newdecl) == FUNCTION_DECL
2063 && ((DECL_TEMPLATE_INSTANTIATION (olddecl)
2064 && !DECL_USE_TEMPLATE (newdecl))
2065 || (DECL_TEMPLATE_INSTANTIATION (newdecl)
2066 && !DECL_USE_TEMPLATE (olddecl))))
2067 /* One of the declarations is a template instantiation, and the
2068 other is not a template at all. That's OK. */
2069 return NULL_TREE;
2070 else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
2072 /* In [namespace.alias] we have:
2074 In a declarative region, a namespace-alias-definition can be
2075 used to redefine a namespace-alias declared in that declarative
2076 region to refer only to the namespace to which it already
2077 refers.
2079 Therefore, if we encounter a second alias directive for the same
2080 alias, we can just ignore the second directive. */
2081 if (DECL_NAMESPACE_ALIAS (newdecl)
2082 && (DECL_NAMESPACE_ALIAS (newdecl)
2083 == DECL_NAMESPACE_ALIAS (olddecl)))
2084 return olddecl;
2086 /* Leave it to update_binding to merge or report error. */
2087 return NULL_TREE;
2089 else
2091 const char *errmsg = redeclaration_error_message (newdecl, olddecl);
2092 if (errmsg)
2094 auto_diagnostic_group d;
2095 error_at (newdecl_loc, errmsg, newdecl);
2096 if (DECL_NAME (olddecl) != NULL_TREE)
2097 inform (olddecl_loc,
2098 (DECL_INITIAL (olddecl) && namespace_bindings_p ())
2099 ? G_("%q#D previously defined here")
2100 : G_("%q#D previously declared here"), olddecl);
2101 if (cxx_dialect >= cxx26
2102 && DECL_NAME (newdecl)
2103 && id_equal (DECL_NAME (newdecl), "_")
2104 && !name_independent_decl_p (newdecl))
2106 if (TREE_CODE (newdecl) == PARM_DECL)
2107 inform (newdecl_loc,
2108 "parameter declaration is not name-independent");
2109 else if (DECL_DECOMPOSITION_P (newdecl))
2111 if (at_namespace_scope_p ())
2112 inform (newdecl_loc,
2113 "structured binding at namespace scope is not "
2114 "name-independent");
2115 else if (TREE_STATIC (newdecl))
2116 inform (newdecl_loc,
2117 "static structured binding is not "
2118 "name-independent");
2119 else if (DECL_EXTERNAL (newdecl))
2120 inform (newdecl_loc,
2121 "extern structured binding is not "
2122 "name-independent");
2124 else if (at_class_scope_p ()
2125 && VAR_P (newdecl)
2126 && TREE_STATIC (newdecl))
2127 inform (newdecl_loc,
2128 "static data member is not name-independent");
2129 else if (VAR_P (newdecl) && at_namespace_scope_p ())
2130 inform (newdecl_loc,
2131 "variable at namespace scope is not name-independent");
2132 else if (VAR_P (newdecl) && TREE_STATIC (newdecl))
2133 inform (newdecl_loc,
2134 "static variable is not name-independent");
2135 else if (VAR_P (newdecl) && DECL_EXTERNAL (newdecl))
2136 inform (newdecl_loc,
2137 "extern variable is not name-independent");
2139 return error_mark_node;
2141 else if (TREE_CODE (olddecl) == FUNCTION_DECL
2142 && DECL_INITIAL (olddecl) != NULL_TREE
2143 && !prototype_p (TREE_TYPE (olddecl))
2144 && prototype_p (TREE_TYPE (newdecl)))
2146 /* Prototype decl follows defn w/o prototype. */
2147 auto_diagnostic_group d;
2148 if (warning_at (newdecl_loc, 0,
2149 "prototype specified for %q#D", newdecl))
2150 inform (olddecl_loc,
2151 "previous non-prototype definition here");
2153 else if (VAR_OR_FUNCTION_DECL_P (olddecl)
2154 && DECL_LANGUAGE (newdecl) != DECL_LANGUAGE (olddecl))
2156 /* [dcl.link]
2157 If two declarations of the same function or object
2158 specify different linkage-specifications ..., the program
2159 is ill-formed.... Except for functions with C++ linkage,
2160 a function declaration without a linkage specification
2161 shall not precede the first linkage specification for
2162 that function. A function can be declared without a
2163 linkage specification after an explicit linkage
2164 specification has been seen; the linkage explicitly
2165 specified in the earlier declaration is not affected by
2166 such a function declaration.
2168 DR 563 raises the question why the restrictions on
2169 functions should not also apply to objects. Older
2170 versions of G++ silently ignore the linkage-specification
2171 for this example:
2173 namespace N {
2174 extern int i;
2175 extern "C" int i;
2178 which is clearly wrong. Therefore, we now treat objects
2179 like functions. */
2180 if (current_lang_depth () == 0)
2182 /* There is no explicit linkage-specification, so we use
2183 the linkage from the previous declaration. */
2184 retrofit_lang_decl (newdecl);
2185 SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
2187 else
2189 auto_diagnostic_group d;
2190 error_at (newdecl_loc,
2191 "conflicting declaration of %q#D with %qL linkage",
2192 newdecl, DECL_LANGUAGE (newdecl));
2193 inform (olddecl_loc,
2194 "previous declaration with %qL linkage",
2195 DECL_LANGUAGE (olddecl));
2199 if (DECL_LANG_SPECIFIC (olddecl) && DECL_USE_TEMPLATE (olddecl))
2201 else if (TREE_CODE (olddecl) == FUNCTION_DECL)
2203 /* Note: free functions, as TEMPLATE_DECLs, are handled below. */
2204 if (DECL_FUNCTION_MEMBER_P (olddecl)
2205 && (/* grokfndecl passes member function templates too
2206 as FUNCTION_DECLs. */
2207 DECL_TEMPLATE_INFO (olddecl)
2208 /* C++11 8.3.6/6.
2209 Default arguments for a member function of a class
2210 template shall be specified on the initial declaration
2211 of the member function within the class template. */
2212 || CLASSTYPE_TEMPLATE_INFO (CP_DECL_CONTEXT (olddecl))))
2214 check_redeclaration_no_default_args (newdecl);
2216 if (DECL_TEMPLATE_INFO (olddecl)
2217 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (olddecl)))
2219 tree new_parms = DECL_TEMPLATE_INFO (newdecl)
2220 ? DECL_INNERMOST_TEMPLATE_PARMS (DECL_TI_TEMPLATE (newdecl))
2221 : INNERMOST_TEMPLATE_PARMS (current_template_parms);
2222 tree old_parms
2223 = DECL_INNERMOST_TEMPLATE_PARMS (DECL_TI_TEMPLATE (olddecl));
2224 merge_default_template_args (new_parms, old_parms,
2225 /*class_p=*/false);
2228 else
2230 tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl);
2231 tree t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
2232 int i = 1;
2234 for (; t1 && t1 != void_list_node;
2235 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2), i++)
2236 if (TREE_PURPOSE (t1) && TREE_PURPOSE (t2))
2238 if (simple_cst_equal (TREE_PURPOSE (t1),
2239 TREE_PURPOSE (t2)) == 1)
2241 auto_diagnostic_group d;
2242 if (permerror (newdecl_loc,
2243 "default argument given for parameter "
2244 "%d of %q#D", i, newdecl))
2245 inform (olddecl_loc,
2246 "previous specification in %q#D here",
2247 olddecl);
2249 else
2251 auto_diagnostic_group d;
2252 error_at (newdecl_loc,
2253 "default argument given for parameter %d "
2254 "of %q#D", i, newdecl);
2255 inform (olddecl_loc,
2256 "previous specification in %q#D here",
2257 olddecl);
2261 /* C++17 11.3.6/4: "If a friend declaration specifies a default
2262 argument expression, that declaration... shall be the only
2263 declaration of the function or function template in the
2264 translation unit." */
2265 check_no_redeclaration_friend_default_args (olddecl, newdecl);
2270 /* Do not merge an implicit typedef with an explicit one. In:
2272 class A;
2274 typedef class A A __attribute__ ((foo));
2276 the attribute should apply only to the typedef. */
2277 if (TREE_CODE (olddecl) == TYPE_DECL
2278 && (DECL_IMPLICIT_TYPEDEF_P (olddecl)
2279 || DECL_IMPLICIT_TYPEDEF_P (newdecl)))
2280 return NULL_TREE;
2282 if (DECL_TEMPLATE_PARM_P (olddecl) != DECL_TEMPLATE_PARM_P (newdecl))
2283 return NULL_TREE;
2285 if (!validate_constexpr_redeclaration (olddecl, newdecl))
2286 return error_mark_node;
2288 if (modules_p ()
2289 && TREE_CODE (CP_DECL_CONTEXT (olddecl)) == NAMESPACE_DECL
2290 && TREE_CODE (olddecl) != NAMESPACE_DECL)
2292 if (!module_may_redeclare (olddecl, newdecl))
2293 return error_mark_node;
2295 if (!hiding)
2297 /* The old declaration should match the exportingness of the new
2298 declaration. But hidden friend declarations just keep the
2299 exportingness of the old declaration; see CWG2588. */
2300 tree not_tmpl = STRIP_TEMPLATE (olddecl);
2301 if (DECL_LANG_SPECIFIC (not_tmpl)
2302 && DECL_MODULE_ATTACH_P (not_tmpl)
2303 /* Typedefs are not entities and so are OK to be redeclared
2304 as exported: see [module.interface]/p6. */
2305 && TREE_CODE (olddecl) != TYPE_DECL)
2307 if (DECL_MODULE_EXPORT_P (newdecl)
2308 && !DECL_MODULE_EXPORT_P (not_tmpl))
2310 auto_diagnostic_group d;
2311 error ("conflicting exporting for declaration %qD", newdecl);
2312 inform (olddecl_loc,
2313 "previously declared here without exporting");
2316 else if (DECL_MODULE_EXPORT_P (newdecl))
2317 DECL_MODULE_EXPORT_P (not_tmpl) = true;
2321 /* We have committed to returning OLDDECL at this point. */
2323 /* If new decl is `static' and an `extern' was seen previously,
2324 warn about it. */
2325 warn_extern_redeclared_static (newdecl, olddecl);
2327 /* True to merge attributes between the declarations, false to
2328 set OLDDECL's attributes to those of NEWDECL (for template
2329 explicit specializations that specify their own attributes
2330 independent of those specified for the primary template). */
2331 const bool merge_attr = (TREE_CODE (newdecl) != FUNCTION_DECL
2332 || !DECL_TEMPLATE_SPECIALIZATION (newdecl)
2333 || DECL_TEMPLATE_SPECIALIZATION (olddecl));
2335 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2337 if (merge_attr)
2340 auto_diagnostic_group d;
2341 if (diagnose_mismatched_attributes (olddecl, newdecl))
2342 inform (olddecl_loc, DECL_INITIAL (olddecl)
2343 ? G_("previous definition of %qD here")
2344 : G_("previous declaration of %qD here"), olddecl);
2347 /* [dcl.attr.noreturn]: The first declaration of a function shall
2348 specify the noreturn attribute if any declaration of that function
2349 specifies the noreturn attribute. */
2350 tree a;
2351 if (TREE_THIS_VOLATILE (newdecl)
2352 && !TREE_THIS_VOLATILE (olddecl)
2353 /* This applies to [[noreturn]] only, not its GNU variants. */
2354 && (a = lookup_attribute ("noreturn", DECL_ATTRIBUTES (newdecl)))
2355 && cxx11_attribute_p (a)
2356 && get_attribute_namespace (a) == NULL_TREE)
2358 auto_diagnostic_group d;
2359 error_at (newdecl_loc, "function %qD declared %<[[noreturn]]%> "
2360 "but its first declaration was not", newdecl);
2361 inform (olddecl_loc, "previous declaration of %qD", olddecl);
2365 /* Now that functions must hold information normally held
2366 by field decls, there is extra work to do so that
2367 declaration information does not get destroyed during
2368 definition. */
2369 if (DECL_VINDEX (olddecl))
2370 DECL_VINDEX (newdecl) = DECL_VINDEX (olddecl);
2371 if (DECL_CONTEXT (olddecl))
2372 DECL_CONTEXT (newdecl) = DECL_CONTEXT (olddecl);
2373 DECL_STATIC_CONSTRUCTOR (newdecl) |= DECL_STATIC_CONSTRUCTOR (olddecl);
2374 DECL_STATIC_DESTRUCTOR (newdecl) |= DECL_STATIC_DESTRUCTOR (olddecl);
2375 DECL_PURE_VIRTUAL_P (newdecl) |= DECL_PURE_VIRTUAL_P (olddecl);
2376 DECL_VIRTUAL_P (newdecl) |= DECL_VIRTUAL_P (olddecl);
2377 DECL_INVALID_OVERRIDER_P (newdecl) |= DECL_INVALID_OVERRIDER_P (olddecl);
2378 DECL_FINAL_P (newdecl) |= DECL_FINAL_P (olddecl);
2379 DECL_OVERRIDE_P (newdecl) |= DECL_OVERRIDE_P (olddecl);
2380 DECL_THIS_STATIC (newdecl) |= DECL_THIS_STATIC (olddecl);
2381 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (newdecl)
2382 |= DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (olddecl);
2383 if (DECL_OVERLOADED_OPERATOR_P (olddecl))
2384 DECL_OVERLOADED_OPERATOR_CODE_RAW (newdecl)
2385 = DECL_OVERLOADED_OPERATOR_CODE_RAW (olddecl);
2386 new_defines_function = DECL_INITIAL (newdecl) != NULL_TREE;
2388 duplicate_contracts (newdecl, olddecl);
2390 /* Optionally warn about more than one declaration for the same
2391 name, but don't warn about a function declaration followed by a
2392 definition. */
2393 if (warn_redundant_decls && ! DECL_ARTIFICIAL (olddecl)
2394 && !(new_defines_function && DECL_INITIAL (olddecl) == NULL_TREE)
2395 /* Don't warn about extern decl followed by definition. */
2396 && !(DECL_EXTERNAL (olddecl) && ! DECL_EXTERNAL (newdecl))
2397 /* Don't warn if at least one is/was hidden. */
2398 && !(hiding || was_hidden)
2399 /* Don't warn about declaration followed by specialization. */
2400 && (! DECL_TEMPLATE_SPECIALIZATION (newdecl)
2401 || DECL_TEMPLATE_SPECIALIZATION (olddecl)))
2403 auto_diagnostic_group d;
2404 if (warning_at (newdecl_loc,
2405 OPT_Wredundant_decls,
2406 "redundant redeclaration of %qD in same scope",
2407 newdecl))
2408 inform (olddecl_loc,
2409 "previous declaration of %qD", olddecl);
2412 /* [dcl.fct.def.delete] A deleted definition of a function shall be the
2413 first declaration of the function or, for an explicit specialization
2414 of a function template, the first declaration of that
2415 specialization. */
2416 if (!(DECL_TEMPLATE_INSTANTIATION (olddecl)
2417 && DECL_TEMPLATE_SPECIALIZATION (newdecl)))
2419 if (DECL_DELETED_FN (newdecl))
2421 auto_diagnostic_group d;
2422 if (pedwarn (newdecl_loc, 0, "deleted definition of %qD "
2423 "is not first declaration", newdecl))
2424 inform (olddecl_loc,
2425 "previous declaration of %qD", olddecl);
2427 DECL_DELETED_FN (newdecl) |= DECL_DELETED_FN (olddecl);
2428 if (DECL_DELETED_FN (olddecl)
2429 && DECL_INITIAL (olddecl)
2430 && TREE_CODE (DECL_INITIAL (olddecl)) == STRING_CST)
2431 DECL_INITIAL (newdecl) = DECL_INITIAL (olddecl);
2435 /* Deal with C++: must preserve virtual function table size. */
2436 if (TREE_CODE (olddecl) == TYPE_DECL)
2438 tree newtype = TREE_TYPE (newdecl);
2439 tree oldtype = TREE_TYPE (olddecl);
2441 if (newtype != error_mark_node && oldtype != error_mark_node
2442 && TYPE_LANG_SPECIFIC (newtype) && TYPE_LANG_SPECIFIC (oldtype))
2443 CLASSTYPE_FRIEND_CLASSES (newtype)
2444 = CLASSTYPE_FRIEND_CLASSES (oldtype);
2446 DECL_ORIGINAL_TYPE (newdecl) = DECL_ORIGINAL_TYPE (olddecl);
2449 /* Copy all the DECL_... slots specified in the new decl except for
2450 any that we copy here from the old type. */
2451 if (merge_attr)
2452 DECL_ATTRIBUTES (newdecl)
2453 = (*targetm.merge_decl_attributes) (olddecl, newdecl);
2454 else
2455 DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
2457 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
2459 tree old_result = DECL_TEMPLATE_RESULT (olddecl);
2460 tree new_result = DECL_TEMPLATE_RESULT (newdecl);
2461 TREE_TYPE (olddecl) = TREE_TYPE (old_result);
2463 /* The new decl should not already have gathered any
2464 specializations. */
2465 gcc_assert (!DECL_TEMPLATE_SPECIALIZATIONS (newdecl));
2467 /* Make sure the contracts are equivalent. */
2468 duplicate_contracts (newdecl, olddecl);
2470 /* Remove contracts from old_result so they aren't appended to
2471 old_result by the merge function. */
2472 remove_contract_attributes (old_result);
2474 DECL_ATTRIBUTES (old_result)
2475 = (*targetm.merge_decl_attributes) (old_result, new_result);
2477 if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2479 if (DECL_SOURCE_LOCATION (newdecl)
2480 != DECL_SOURCE_LOCATION (olddecl))
2482 /* Per C++11 8.3.6/4, default arguments cannot be added in
2483 later declarations of a function template. */
2484 check_redeclaration_no_default_args (newdecl);
2485 /* C++17 11.3.6/4: "If a friend declaration specifies a default
2486 argument expression, that declaration... shall be the only
2487 declaration of the function or function template in the
2488 translation unit." */
2489 check_no_redeclaration_friend_default_args
2490 (old_result, new_result);
2492 tree new_parms = DECL_INNERMOST_TEMPLATE_PARMS (newdecl);
2493 tree old_parms = DECL_INNERMOST_TEMPLATE_PARMS (olddecl);
2494 merge_default_template_args (new_parms, old_parms,
2495 /*class_p=*/false);
2497 if (!DECL_UNIQUE_FRIEND_P (new_result))
2498 DECL_UNIQUE_FRIEND_P (old_result) = false;
2500 check_default_args (newdecl);
2502 if (GNU_INLINE_P (old_result) != GNU_INLINE_P (new_result)
2503 && DECL_INITIAL (new_result))
2505 if (DECL_INITIAL (old_result))
2506 DECL_UNINLINABLE (old_result) = 1;
2507 else
2508 DECL_UNINLINABLE (old_result) = DECL_UNINLINABLE (new_result);
2509 DECL_EXTERNAL (old_result) = DECL_EXTERNAL (new_result);
2510 DECL_NOT_REALLY_EXTERN (old_result)
2511 = DECL_NOT_REALLY_EXTERN (new_result);
2512 DECL_INTERFACE_KNOWN (old_result)
2513 = DECL_INTERFACE_KNOWN (new_result);
2514 DECL_DECLARED_INLINE_P (old_result)
2515 = DECL_DECLARED_INLINE_P (new_result);
2516 DECL_DISREGARD_INLINE_LIMITS (old_result)
2517 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2519 else
2521 DECL_DECLARED_INLINE_P (old_result)
2522 |= DECL_DECLARED_INLINE_P (new_result);
2523 DECL_DISREGARD_INLINE_LIMITS (old_result)
2524 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2525 check_redeclaration_exception_specification (newdecl, olddecl);
2527 merge_attribute_bits (new_result, old_result);
2531 /* Propagate purviewness and importingness as with
2532 set_instantiating_module. */
2533 if (modules_p ())
2535 if (DECL_MODULE_PURVIEW_P (new_result))
2536 DECL_MODULE_PURVIEW_P (old_result) = true;
2537 if (!DECL_MODULE_IMPORT_P (new_result))
2538 DECL_MODULE_IMPORT_P (old_result) = false;
2541 /* If the new declaration is a definition, update the file and
2542 line information on the declaration, and also make
2543 the old declaration the same definition. */
2544 if (DECL_INITIAL (new_result) != NULL_TREE)
2546 DECL_SOURCE_LOCATION (olddecl)
2547 = DECL_SOURCE_LOCATION (old_result)
2548 = DECL_SOURCE_LOCATION (newdecl);
2549 DECL_INITIAL (old_result) = DECL_INITIAL (new_result);
2550 if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2552 DECL_ARGUMENTS (old_result) = DECL_ARGUMENTS (new_result);
2553 for (tree p = DECL_ARGUMENTS (old_result); p; p = DECL_CHAIN (p))
2554 DECL_CONTEXT (p) = old_result;
2556 if (tree fc = DECL_FRIEND_CONTEXT (new_result))
2557 SET_DECL_FRIEND_CONTEXT (old_result, fc);
2561 return olddecl;
2564 if (types_match)
2566 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2567 check_redeclaration_exception_specification (newdecl, olddecl);
2569 /* Automatically handles default parameters. */
2570 tree oldtype = TREE_TYPE (olddecl);
2571 tree newtype;
2573 /* For typedefs use the old type, as the new type's DECL_NAME points
2574 at newdecl, which will be ggc_freed. */
2575 if (TREE_CODE (newdecl) == TYPE_DECL)
2577 /* But NEWTYPE might have an attribute, honor that. */
2578 tree tem = TREE_TYPE (newdecl);
2579 newtype = oldtype;
2581 if (TYPE_USER_ALIGN (tem))
2583 if (TYPE_ALIGN (tem) > TYPE_ALIGN (newtype))
2584 SET_TYPE_ALIGN (newtype, TYPE_ALIGN (tem));
2585 TYPE_USER_ALIGN (newtype) = true;
2588 /* And remove the new type from the variants list. */
2589 if (TYPE_NAME (TREE_TYPE (newdecl)) == newdecl)
2591 tree remove = TREE_TYPE (newdecl);
2592 if (TYPE_MAIN_VARIANT (remove) == remove)
2594 gcc_assert (TYPE_NEXT_VARIANT (remove) == NULL_TREE);
2595 /* If remove is the main variant, no need to remove that
2596 from the list. One of the DECL_ORIGINAL_TYPE
2597 variants, e.g. created for aligned attribute, might still
2598 refer to the newdecl TYPE_DECL though, so remove that one
2599 in that case. */
2600 if (tree orig = DECL_ORIGINAL_TYPE (newdecl))
2601 if (orig != remove)
2602 for (tree t = TYPE_MAIN_VARIANT (orig); t;
2603 t = TYPE_MAIN_VARIANT (t))
2604 if (TYPE_NAME (TYPE_NEXT_VARIANT (t)) == newdecl)
2606 TYPE_NEXT_VARIANT (t)
2607 = TYPE_NEXT_VARIANT (TYPE_NEXT_VARIANT (t));
2608 break;
2611 else
2612 for (tree t = TYPE_MAIN_VARIANT (remove); ;
2613 t = TYPE_NEXT_VARIANT (t))
2614 if (TYPE_NEXT_VARIANT (t) == remove)
2616 TYPE_NEXT_VARIANT (t) = TYPE_NEXT_VARIANT (remove);
2617 break;
2621 else if (merge_attr)
2622 newtype = merge_types (TREE_TYPE (newdecl), TREE_TYPE (olddecl));
2623 else
2624 newtype = TREE_TYPE (newdecl);
2626 if (VAR_P (newdecl))
2628 DECL_THIS_EXTERN (newdecl) |= DECL_THIS_EXTERN (olddecl);
2629 /* For already initialized vars, TREE_READONLY could have been
2630 cleared in cp_finish_decl, because the var needs runtime
2631 initialization or destruction. Make sure not to set
2632 TREE_READONLY on it again. */
2633 if (DECL_INITIALIZED_P (olddecl)
2634 && !DECL_EXTERNAL (olddecl)
2635 && !TREE_READONLY (olddecl))
2636 TREE_READONLY (newdecl) = 0;
2637 DECL_INITIALIZED_P (newdecl) |= DECL_INITIALIZED_P (olddecl);
2638 DECL_NONTRIVIALLY_INITIALIZED_P (newdecl)
2639 |= DECL_NONTRIVIALLY_INITIALIZED_P (olddecl);
2640 if (DECL_DEPENDENT_INIT_P (olddecl))
2641 SET_DECL_DEPENDENT_INIT_P (newdecl, true);
2642 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (newdecl)
2643 |= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (olddecl);
2644 DECL_DECLARED_CONSTEXPR_P (newdecl)
2645 |= DECL_DECLARED_CONSTEXPR_P (olddecl);
2646 DECL_DECLARED_CONSTINIT_P (newdecl)
2647 |= DECL_DECLARED_CONSTINIT_P (olddecl);
2649 /* Merge the threadprivate attribute from OLDDECL into NEWDECL. */
2650 if (DECL_LANG_SPECIFIC (olddecl)
2651 && CP_DECL_THREADPRIVATE_P (olddecl))
2653 /* Allocate a LANG_SPECIFIC structure for NEWDECL, if needed. */
2654 retrofit_lang_decl (newdecl);
2655 CP_DECL_THREADPRIVATE_P (newdecl) = 1;
2659 /* An explicit specialization of a function template or of a member
2660 function of a class template can be declared transaction_safe
2661 independently of whether the corresponding template entity is declared
2662 transaction_safe. */
2663 if (flag_tm && TREE_CODE (newdecl) == FUNCTION_DECL
2664 && DECL_TEMPLATE_INSTANTIATION (olddecl)
2665 && DECL_TEMPLATE_SPECIALIZATION (newdecl)
2666 && tx_safe_fn_type_p (newtype)
2667 && !tx_safe_fn_type_p (TREE_TYPE (newdecl)))
2668 newtype = tx_unsafe_fn_variant (newtype);
2670 TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = newtype;
2672 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2673 check_default_args (newdecl);
2675 /* Lay the type out, unless already done. */
2676 if (! same_type_p (newtype, oldtype)
2677 && TREE_TYPE (newdecl) != error_mark_node
2678 && !(processing_template_decl && uses_template_parms (newdecl)))
2679 layout_type (TREE_TYPE (newdecl));
2681 if ((VAR_P (newdecl)
2682 || TREE_CODE (newdecl) == PARM_DECL
2683 || TREE_CODE (newdecl) == RESULT_DECL
2684 || TREE_CODE (newdecl) == FIELD_DECL
2685 || TREE_CODE (newdecl) == TYPE_DECL)
2686 && !(processing_template_decl && uses_template_parms (newdecl)))
2687 layout_decl (newdecl, 0);
2689 /* Merge deprecatedness. */
2690 if (TREE_DEPRECATED (newdecl))
2691 TREE_DEPRECATED (olddecl) = 1;
2693 /* Merge unavailability. */
2694 if (TREE_UNAVAILABLE (newdecl))
2695 TREE_UNAVAILABLE (olddecl) = 1;
2697 /* Preserve function specific target and optimization options */
2698 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2700 if (DECL_FUNCTION_SPECIFIC_TARGET (olddecl)
2701 && !DECL_FUNCTION_SPECIFIC_TARGET (newdecl))
2702 DECL_FUNCTION_SPECIFIC_TARGET (newdecl)
2703 = DECL_FUNCTION_SPECIFIC_TARGET (olddecl);
2705 if (DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl)
2706 && !DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl))
2707 DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl)
2708 = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl);
2710 if (!DECL_UNIQUE_FRIEND_P (olddecl))
2711 DECL_UNIQUE_FRIEND_P (newdecl) = false;
2713 else
2715 /* Merge the const type qualifier. */
2716 if (TREE_READONLY (newdecl))
2717 TREE_READONLY (olddecl) = 1;
2718 /* Merge the volatile type qualifier. */
2719 if (TREE_THIS_VOLATILE (newdecl))
2720 TREE_THIS_VOLATILE (olddecl) = 1;
2723 /* Merge the initialization information. */
2724 if (DECL_INITIAL (newdecl) == NULL_TREE
2725 && DECL_INITIAL (olddecl) != NULL_TREE)
2727 DECL_INITIAL (newdecl) = DECL_INITIAL (olddecl);
2728 DECL_SOURCE_LOCATION (newdecl) = DECL_SOURCE_LOCATION (olddecl);
2729 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2731 DECL_SAVED_TREE (newdecl) = DECL_SAVED_TREE (olddecl);
2732 DECL_STRUCT_FUNCTION (newdecl) = DECL_STRUCT_FUNCTION (olddecl);
2736 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2738 DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (newdecl)
2739 |= DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (olddecl);
2740 DECL_NO_LIMIT_STACK (newdecl) |= DECL_NO_LIMIT_STACK (olddecl);
2741 if (DECL_IS_OPERATOR_NEW_P (olddecl))
2742 DECL_SET_IS_OPERATOR_NEW (newdecl, true);
2743 DECL_LOOPING_CONST_OR_PURE_P (newdecl)
2744 |= DECL_LOOPING_CONST_OR_PURE_P (olddecl);
2745 DECL_IS_REPLACEABLE_OPERATOR (newdecl)
2746 |= DECL_IS_REPLACEABLE_OPERATOR (olddecl);
2748 if (merge_attr)
2749 merge_attribute_bits (newdecl, olddecl);
2750 else
2752 /* Merge the noreturn bit. */
2753 TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2754 TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2755 TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2756 DECL_IS_MALLOC (olddecl) = DECL_IS_MALLOC (newdecl);
2757 DECL_PURE_P (olddecl) = DECL_PURE_P (newdecl);
2759 /* Keep the old RTL. */
2760 COPY_DECL_RTL (olddecl, newdecl);
2762 else if (VAR_P (newdecl)
2763 && (DECL_SIZE (olddecl) || !DECL_SIZE (newdecl)))
2765 /* Keep the old RTL. We cannot keep the old RTL if the old
2766 declaration was for an incomplete object and the new
2767 declaration is not since many attributes of the RTL will
2768 change. */
2769 COPY_DECL_RTL (olddecl, newdecl);
2772 /* If cannot merge, then use the new type and qualifiers,
2773 and don't preserve the old rtl. */
2774 else
2776 /* Clean out any memory we had of the old declaration. */
2777 tree oldstatic = value_member (olddecl, static_aggregates);
2778 if (oldstatic)
2779 TREE_VALUE (oldstatic) = error_mark_node;
2781 TREE_TYPE (olddecl) = TREE_TYPE (newdecl);
2782 TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2783 TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2784 TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2785 TREE_SIDE_EFFECTS (olddecl) = TREE_SIDE_EFFECTS (newdecl);
2788 /* Merge the storage class information. */
2789 merge_weak (newdecl, olddecl);
2791 DECL_DEFER_OUTPUT (newdecl) |= DECL_DEFER_OUTPUT (olddecl);
2792 TREE_PUBLIC (newdecl) = TREE_PUBLIC (olddecl);
2793 TREE_STATIC (olddecl) = TREE_STATIC (newdecl) |= TREE_STATIC (olddecl);
2794 if (! DECL_EXTERNAL (olddecl))
2795 DECL_EXTERNAL (newdecl) = 0;
2796 if (! DECL_COMDAT (olddecl))
2797 DECL_COMDAT (newdecl) = 0;
2799 if (VAR_OR_FUNCTION_DECL_P (newdecl) && DECL_LOCAL_DECL_P (newdecl))
2801 if (!DECL_LOCAL_DECL_P (olddecl))
2802 /* This can happen if olddecl was brought in from the
2803 enclosing namespace via a using-decl. The new decl is
2804 then not a block-scope extern at all. */
2805 DECL_LOCAL_DECL_P (newdecl) = false;
2806 else
2808 retrofit_lang_decl (newdecl);
2809 tree alias = DECL_LOCAL_DECL_ALIAS (newdecl)
2810 = DECL_LOCAL_DECL_ALIAS (olddecl);
2811 if (alias != error_mark_node)
2813 DECL_ATTRIBUTES (alias)
2814 = (*targetm.merge_decl_attributes) (alias, newdecl);
2815 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2816 merge_attribute_bits (newdecl, alias);
2821 new_template_info = NULL_TREE;
2822 if (DECL_LANG_SPECIFIC (newdecl) && DECL_LANG_SPECIFIC (olddecl))
2824 bool new_redefines_gnu_inline = false;
2826 if (new_defines_function
2827 && ((DECL_INTERFACE_KNOWN (olddecl)
2828 && TREE_CODE (olddecl) == FUNCTION_DECL)
2829 || (TREE_CODE (olddecl) == TEMPLATE_DECL
2830 && (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl))
2831 == FUNCTION_DECL))))
2832 new_redefines_gnu_inline = GNU_INLINE_P (STRIP_TEMPLATE (olddecl));
2834 if (!new_redefines_gnu_inline)
2836 DECL_INTERFACE_KNOWN (newdecl) |= DECL_INTERFACE_KNOWN (olddecl);
2837 DECL_NOT_REALLY_EXTERN (newdecl) |= DECL_NOT_REALLY_EXTERN (olddecl);
2838 DECL_COMDAT (newdecl) |= DECL_COMDAT (olddecl);
2841 if (TREE_CODE (newdecl) != TYPE_DECL)
2843 DECL_TEMPLATE_INSTANTIATED (newdecl)
2844 |= DECL_TEMPLATE_INSTANTIATED (olddecl);
2845 DECL_ODR_USED (newdecl) |= DECL_ODR_USED (olddecl);
2847 /* If the OLDDECL is an instantiation and/or specialization,
2848 then the NEWDECL must be too. But, it may not yet be marked
2849 as such if the caller has created NEWDECL, but has not yet
2850 figured out that it is a redeclaration. */
2851 if (!DECL_USE_TEMPLATE (newdecl))
2852 DECL_USE_TEMPLATE (newdecl) = DECL_USE_TEMPLATE (olddecl);
2854 if (!DECL_TEMPLATE_SPECIALIZATION (newdecl))
2855 DECL_INITIALIZED_IN_CLASS_P (newdecl)
2856 |= DECL_INITIALIZED_IN_CLASS_P (olddecl);
2859 /* Don't really know how much of the language-specific
2860 values we should copy from old to new. */
2861 DECL_IN_AGGR_P (newdecl) = DECL_IN_AGGR_P (olddecl);
2863 if (LANG_DECL_HAS_MIN (newdecl))
2865 DECL_ACCESS (newdecl) = DECL_ACCESS (olddecl);
2866 if (DECL_TEMPLATE_INFO (newdecl))
2868 new_template_info = DECL_TEMPLATE_INFO (newdecl);
2869 if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2870 && DECL_TEMPLATE_SPECIALIZATION (newdecl))
2871 /* Remember the presence of explicit specialization args. */
2872 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (olddecl))
2873 = TINFO_USED_TEMPLATE_ID (new_template_info);
2876 /* We don't want to copy template info from a non-templated friend
2877 (PR105761), but these shouldn't have DECL_TEMPLATE_INFO now. */
2878 gcc_checking_assert (!DECL_TEMPLATE_INFO (olddecl)
2879 || !non_templated_friend_p (olddecl));
2880 DECL_TEMPLATE_INFO (newdecl) = DECL_TEMPLATE_INFO (olddecl);
2883 if (DECL_DECLARES_FUNCTION_P (newdecl))
2885 /* Only functions have these fields. */
2886 DECL_NONCONVERTING_P (newdecl) = DECL_NONCONVERTING_P (olddecl);
2887 DECL_BEFRIENDING_CLASSES (newdecl)
2888 = chainon (DECL_BEFRIENDING_CLASSES (newdecl),
2889 DECL_BEFRIENDING_CLASSES (olddecl));
2890 /* DECL_THUNKS is only valid for virtual functions,
2891 otherwise it is a DECL_FRIEND_CONTEXT. */
2892 if (DECL_VIRTUAL_P (newdecl))
2893 SET_DECL_THUNKS (newdecl, DECL_THUNKS (olddecl));
2894 else if (tree fc = DECL_FRIEND_CONTEXT (newdecl))
2895 SET_DECL_FRIEND_CONTEXT (olddecl, fc);
2897 else if (VAR_P (newdecl))
2899 /* Only variables have this field. */
2900 if (VAR_HAD_UNKNOWN_BOUND (olddecl))
2901 SET_VAR_HAD_UNKNOWN_BOUND (newdecl);
2905 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2907 tree parm;
2909 /* Merge parameter attributes. */
2910 tree oldarg, newarg;
2911 for (oldarg = DECL_ARGUMENTS(olddecl), newarg = DECL_ARGUMENTS(newdecl);
2912 oldarg && newarg;
2913 oldarg = DECL_CHAIN(oldarg), newarg = DECL_CHAIN(newarg))
2915 DECL_ATTRIBUTES (newarg)
2916 = (*targetm.merge_decl_attributes) (oldarg, newarg);
2917 DECL_ATTRIBUTES (oldarg) = DECL_ATTRIBUTES (newarg);
2920 if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2921 && !DECL_TEMPLATE_INSTANTIATION (newdecl))
2923 /* If newdecl is not a specialization, then it is not a
2924 template-related function at all. And that means that we
2925 should have exited above, returning 0. */
2926 gcc_assert (DECL_TEMPLATE_SPECIALIZATION (newdecl));
2928 if (DECL_ODR_USED (olddecl))
2929 /* From [temp.expl.spec]:
2931 If a template, a member template or the member of a class
2932 template is explicitly specialized then that
2933 specialization shall be declared before the first use of
2934 that specialization that would cause an implicit
2935 instantiation to take place, in every translation unit in
2936 which such a use occurs. */
2937 error ("explicit specialization of %qD after first use",
2938 olddecl);
2940 SET_DECL_TEMPLATE_SPECIALIZATION (olddecl);
2941 DECL_COMDAT (newdecl) = (TREE_PUBLIC (newdecl)
2942 && DECL_DECLARED_INLINE_P (newdecl));
2944 /* Don't propagate visibility from the template to the
2945 specialization here. We'll do that in determine_visibility if
2946 appropriate. */
2947 DECL_VISIBILITY_SPECIFIED (olddecl) = 0;
2949 /* [temp.expl.spec/14] We don't inline explicit specialization
2950 just because the primary template says so. */
2951 gcc_assert (!merge_attr);
2953 DECL_DECLARED_INLINE_P (olddecl)
2954 = DECL_DECLARED_INLINE_P (newdecl);
2956 DECL_DISREGARD_INLINE_LIMITS (olddecl)
2957 = DECL_DISREGARD_INLINE_LIMITS (newdecl);
2959 DECL_UNINLINABLE (olddecl) = DECL_UNINLINABLE (newdecl);
2961 else if (new_defines_function && DECL_INITIAL (olddecl))
2963 /* Never inline re-defined extern inline functions.
2964 FIXME: this could be better handled by keeping both
2965 function as separate declarations. */
2966 DECL_UNINLINABLE (newdecl) = 1;
2968 else
2970 if (DECL_PENDING_INLINE_P (olddecl))
2972 DECL_PENDING_INLINE_P (newdecl) = 1;
2973 DECL_PENDING_INLINE_INFO (newdecl)
2974 = DECL_PENDING_INLINE_INFO (olddecl);
2976 else if (DECL_PENDING_INLINE_P (newdecl))
2978 else if (DECL_SAVED_AUTO_RETURN_TYPE (newdecl) == NULL)
2979 DECL_SAVED_AUTO_RETURN_TYPE (newdecl)
2980 = DECL_SAVED_AUTO_RETURN_TYPE (olddecl);
2982 DECL_DECLARED_INLINE_P (newdecl) |= DECL_DECLARED_INLINE_P (olddecl);
2984 DECL_UNINLINABLE (newdecl) = DECL_UNINLINABLE (olddecl)
2985 = (DECL_UNINLINABLE (newdecl) || DECL_UNINLINABLE (olddecl));
2987 DECL_DISREGARD_INLINE_LIMITS (newdecl)
2988 = DECL_DISREGARD_INLINE_LIMITS (olddecl)
2989 = (DECL_DISREGARD_INLINE_LIMITS (newdecl)
2990 || DECL_DISREGARD_INLINE_LIMITS (olddecl));
2993 /* Preserve abstractness on cloned [cd]tors. */
2994 DECL_ABSTRACT_P (newdecl) = DECL_ABSTRACT_P (olddecl);
2996 /* Update newdecl's parms to point at olddecl. */
2997 for (parm = DECL_ARGUMENTS (newdecl); parm;
2998 parm = DECL_CHAIN (parm))
2999 DECL_CONTEXT (parm) = olddecl;
3001 if (! types_match)
3003 SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
3004 COPY_DECL_ASSEMBLER_NAME (newdecl, olddecl);
3005 COPY_DECL_RTL (newdecl, olddecl);
3007 if (! types_match || new_defines_function)
3009 /* These are the final DECL_ARGUMENTS that will be used within the
3010 body; update any references to old DECL_ARGUMENTS in the
3011 contracts, if present. */
3012 if (tree contracts = DECL_CONTRACTS (newdecl))
3013 remap_contracts (olddecl, newdecl, contracts, true);
3015 /* These need to be copied so that the names are available.
3016 Note that if the types do match, we'll preserve inline
3017 info and other bits, but if not, we won't. */
3018 DECL_ARGUMENTS (olddecl) = DECL_ARGUMENTS (newdecl);
3019 DECL_RESULT (olddecl) = DECL_RESULT (newdecl);
3021 /* In some cases, duplicate_contracts will remove contracts from
3022 OLDDECL, to avoid duplications. Sometimes, the contracts end up
3023 shared. If we removed them, re-add them. */
3024 if (!DECL_CONTRACTS (olddecl))
3025 copy_contract_attributes (olddecl, newdecl);
3027 /* If redeclaring a builtin function, it stays built in
3028 if newdecl is a gnu_inline definition, or if newdecl is just
3029 a declaration. */
3030 if (fndecl_built_in_p (olddecl)
3031 && (new_defines_function ? GNU_INLINE_P (newdecl) : types_match))
3033 copy_decl_built_in_function (newdecl, olddecl);
3034 /* If we're keeping the built-in definition, keep the rtl,
3035 regardless of declaration matches. */
3036 COPY_DECL_RTL (olddecl, newdecl);
3037 if (DECL_BUILT_IN_CLASS (newdecl) == BUILT_IN_NORMAL)
3039 enum built_in_function fncode = DECL_FUNCTION_CODE (newdecl);
3040 if (builtin_decl_explicit_p (fncode))
3042 /* A compatible prototype of these builtin functions
3043 is seen, assume the runtime implements it with
3044 the expected semantics. */
3045 switch (fncode)
3047 case BUILT_IN_STPCPY:
3048 set_builtin_decl_implicit_p (fncode, true);
3049 break;
3050 default:
3051 set_builtin_decl_declared_p (fncode, true);
3052 break;
3056 copy_attributes_to_builtin (newdecl);
3059 if (new_defines_function)
3060 /* If defining a function declared with other language
3061 linkage, use the previously declared language linkage. */
3062 SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
3063 else if (types_match)
3065 DECL_RESULT (newdecl) = DECL_RESULT (olddecl);
3066 /* Don't clear out the arguments if we're just redeclaring a
3067 function. */
3068 if (DECL_ARGUMENTS (olddecl))
3070 /* If we removed contracts from previous definition, re-attach
3071 them. Otherwise, rewrite the contracts so they match the
3072 parameters of the new declaration. */
3073 if (DECL_INITIAL (olddecl)
3074 && DECL_CONTRACTS (newdecl)
3075 && !DECL_CONTRACTS (olddecl))
3076 copy_contract_attributes (olddecl, newdecl);
3077 else
3079 /* Temporarily undo the re-contexting of parameters so we can
3080 actually remap parameters. The inliner won't replace
3081 parameters if we don't do this. */
3082 tree args = DECL_ARGUMENTS (newdecl);
3083 for (tree p = args; p; p = DECL_CHAIN (p))
3084 DECL_CONTEXT (p) = newdecl;
3086 /* Save new argument names for use in contracts parsing,
3087 unless we've already started parsing the body of olddecl
3088 (particular issues arise when newdecl is from a prior
3089 friend decl with no argument names, see
3090 modules/contracts-tpl-friend-1). */
3091 if (tree contracts = DECL_CONTRACTS (olddecl))
3092 remap_contracts (newdecl, olddecl, contracts, true);
3094 /* And reverse this operation again. */
3095 for (tree p = args; p; p = DECL_CHAIN (p))
3096 DECL_CONTEXT (p) = olddecl;
3099 DECL_ARGUMENTS (newdecl) = DECL_ARGUMENTS (olddecl);
3103 else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
3104 NAMESPACE_LEVEL (newdecl) = NAMESPACE_LEVEL (olddecl);
3106 /* Now preserve various other info from the definition. */
3107 TREE_ADDRESSABLE (newdecl) = TREE_ADDRESSABLE (olddecl);
3108 TREE_ASM_WRITTEN (newdecl) = TREE_ASM_WRITTEN (olddecl);
3109 DECL_COMMON (newdecl) = DECL_COMMON (olddecl);
3110 COPY_DECL_ASSEMBLER_NAME (olddecl, newdecl);
3112 /* Warn about conflicting visibility specifications. */
3113 if (DECL_VISIBILITY_SPECIFIED (olddecl)
3114 && DECL_VISIBILITY_SPECIFIED (newdecl)
3115 && DECL_VISIBILITY (newdecl) != DECL_VISIBILITY (olddecl))
3117 auto_diagnostic_group d;
3118 if (warning_at (newdecl_loc, OPT_Wattributes,
3119 "%qD: visibility attribute ignored because it "
3120 "conflicts with previous declaration", newdecl))
3121 inform (olddecl_loc,
3122 "previous declaration of %qD", olddecl);
3124 /* Choose the declaration which specified visibility. */
3125 if (DECL_VISIBILITY_SPECIFIED (olddecl))
3127 DECL_VISIBILITY (newdecl) = DECL_VISIBILITY (olddecl);
3128 DECL_VISIBILITY_SPECIFIED (newdecl) = 1;
3130 /* Init priority used to be merged from newdecl to olddecl by the memcpy,
3131 so keep this behavior. */
3132 if (VAR_P (newdecl) && DECL_HAS_INIT_PRIORITY_P (newdecl))
3134 SET_DECL_INIT_PRIORITY (olddecl, DECL_INIT_PRIORITY (newdecl));
3135 DECL_HAS_INIT_PRIORITY_P (olddecl) = 1;
3137 /* Likewise for DECL_ALIGN, DECL_USER_ALIGN and DECL_PACKED. */
3138 if (DECL_ALIGN (olddecl) > DECL_ALIGN (newdecl))
3140 SET_DECL_ALIGN (newdecl, DECL_ALIGN (olddecl));
3141 DECL_USER_ALIGN (newdecl) |= DECL_USER_ALIGN (olddecl);
3143 else if (DECL_ALIGN (olddecl) == DECL_ALIGN (newdecl)
3144 && DECL_USER_ALIGN (olddecl) != DECL_USER_ALIGN (newdecl))
3145 DECL_USER_ALIGN (newdecl) = 1;
3147 DECL_USER_ALIGN (olddecl) = DECL_USER_ALIGN (newdecl);
3148 if (DECL_WARN_IF_NOT_ALIGN (olddecl)
3149 > DECL_WARN_IF_NOT_ALIGN (newdecl))
3150 SET_DECL_WARN_IF_NOT_ALIGN (newdecl,
3151 DECL_WARN_IF_NOT_ALIGN (olddecl));
3152 if (TREE_CODE (newdecl) == FIELD_DECL)
3153 DECL_PACKED (olddecl) = DECL_PACKED (newdecl);
3155 /* Merge module entity mapping information. */
3156 if (DECL_LANG_SPECIFIC (olddecl)
3157 && (DECL_MODULE_ENTITY_P (olddecl)
3158 || DECL_MODULE_KEYED_DECLS_P (olddecl)))
3160 retrofit_lang_decl (newdecl);
3161 DECL_MODULE_ENTITY_P (newdecl) = DECL_MODULE_ENTITY_P (olddecl);
3162 DECL_MODULE_KEYED_DECLS_P (newdecl) = DECL_MODULE_KEYED_DECLS_P (olddecl);
3165 /* The DECL_LANG_SPECIFIC information in OLDDECL will be replaced
3166 with that from NEWDECL below. */
3167 if (DECL_LANG_SPECIFIC (olddecl))
3169 gcc_checking_assert (DECL_LANG_SPECIFIC (olddecl)
3170 != DECL_LANG_SPECIFIC (newdecl));
3171 ggc_free (DECL_LANG_SPECIFIC (olddecl));
3174 /* Merge the USED information. */
3175 if (TREE_USED (olddecl))
3176 TREE_USED (newdecl) = 1;
3177 else if (TREE_USED (newdecl))
3178 TREE_USED (olddecl) = 1;
3180 if (VAR_P (newdecl))
3182 if (DECL_READ_P (olddecl))
3183 DECL_READ_P (newdecl) = 1;
3184 else if (DECL_READ_P (newdecl))
3185 DECL_READ_P (olddecl) = 1;
3188 if (DECL_PRESERVE_P (olddecl))
3189 DECL_PRESERVE_P (newdecl) = 1;
3190 else if (DECL_PRESERVE_P (newdecl))
3191 DECL_PRESERVE_P (olddecl) = 1;
3193 /* Merge the DECL_FUNCTION_VERSIONED information. newdecl will be copied
3194 to olddecl and deleted. */
3195 if (TREE_CODE (newdecl) == FUNCTION_DECL
3196 && DECL_FUNCTION_VERSIONED (olddecl))
3198 /* Set the flag for newdecl so that it gets copied to olddecl. */
3199 DECL_FUNCTION_VERSIONED (newdecl) = 1;
3200 /* newdecl will be purged after copying to olddecl and is no longer
3201 a version. */
3202 cgraph_node::delete_function_version_by_decl (newdecl);
3205 if (TREE_CODE (newdecl) == FUNCTION_DECL)
3207 int function_size;
3208 struct symtab_node *snode = symtab_node::get (olddecl);
3210 function_size = sizeof (struct tree_decl_common);
3212 memcpy ((char *) olddecl + sizeof (struct tree_common),
3213 (char *) newdecl + sizeof (struct tree_common),
3214 function_size - sizeof (struct tree_common));
3216 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3217 (char *) newdecl + sizeof (struct tree_decl_common),
3218 sizeof (struct tree_function_decl) - sizeof (struct tree_decl_common));
3220 /* Preserve symtab node mapping. */
3221 olddecl->decl_with_vis.symtab_node = snode;
3223 if (new_template_info)
3224 /* If newdecl is a template instantiation, it is possible that
3225 the following sequence of events has occurred:
3227 o A friend function was declared in a class template. The
3228 class template was instantiated.
3230 o The instantiation of the friend declaration was
3231 recorded on the instantiation list, and is newdecl.
3233 o Later, however, instantiate_class_template called pushdecl
3234 on the newdecl to perform name injection. But, pushdecl in
3235 turn called duplicate_decls when it discovered that another
3236 declaration of a global function with the same name already
3237 existed.
3239 o Here, in duplicate_decls, we decided to clobber newdecl.
3241 If we're going to do that, we'd better make sure that
3242 olddecl, and not newdecl, is on the list of
3243 instantiations so that if we try to do the instantiation
3244 again we won't get the clobbered declaration. */
3245 reregister_specialization (newdecl,
3246 new_template_info,
3247 olddecl);
3249 else
3251 size_t size = tree_code_size (TREE_CODE (newdecl));
3253 memcpy ((char *) olddecl + sizeof (struct tree_common),
3254 (char *) newdecl + sizeof (struct tree_common),
3255 sizeof (struct tree_decl_common) - sizeof (struct tree_common));
3257 switch (TREE_CODE (newdecl))
3259 case LABEL_DECL:
3260 case VAR_DECL:
3261 case RESULT_DECL:
3262 case PARM_DECL:
3263 case FIELD_DECL:
3264 case TYPE_DECL:
3265 case CONST_DECL:
3267 struct symtab_node *snode = NULL;
3269 if (VAR_P (newdecl)
3270 && (TREE_STATIC (olddecl) || TREE_PUBLIC (olddecl)
3271 || DECL_EXTERNAL (olddecl)))
3272 snode = symtab_node::get (olddecl);
3273 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3274 (char *) newdecl + sizeof (struct tree_decl_common),
3275 size - sizeof (struct tree_decl_common)
3276 + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
3277 if (VAR_P (newdecl))
3278 olddecl->decl_with_vis.symtab_node = snode;
3280 break;
3281 default:
3282 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3283 (char *) newdecl + sizeof (struct tree_decl_common),
3284 sizeof (struct tree_decl_non_common) - sizeof (struct tree_decl_common)
3285 + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
3286 break;
3290 if (VAR_OR_FUNCTION_DECL_P (newdecl))
3292 if (DECL_EXTERNAL (olddecl)
3293 || TREE_PUBLIC (olddecl)
3294 || TREE_STATIC (olddecl))
3296 /* Merge the section attribute.
3297 We want to issue an error if the sections conflict but that must be
3298 done later in decl_attributes since we are called before attributes
3299 are assigned. */
3300 if (DECL_SECTION_NAME (newdecl) != NULL)
3301 set_decl_section_name (olddecl, newdecl);
3303 if (DECL_ONE_ONLY (newdecl))
3305 struct symtab_node *oldsym, *newsym;
3306 if (TREE_CODE (olddecl) == FUNCTION_DECL)
3307 oldsym = cgraph_node::get_create (olddecl);
3308 else
3309 oldsym = varpool_node::get_create (olddecl);
3310 newsym = symtab_node::get (newdecl);
3311 oldsym->set_comdat_group (newsym->get_comdat_group ());
3315 if (VAR_P (newdecl)
3316 && CP_DECL_THREAD_LOCAL_P (newdecl))
3318 CP_DECL_THREAD_LOCAL_P (olddecl) = true;
3319 if (!processing_template_decl)
3320 set_decl_tls_model (olddecl, DECL_TLS_MODEL (newdecl));
3324 DECL_UID (olddecl) = olddecl_uid;
3326 /* NEWDECL contains the merged attribute lists.
3327 Update OLDDECL to be the same. */
3328 DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
3330 /* If OLDDECL had its DECL_RTL instantiated, re-invoke make_decl_rtl
3331 so that encode_section_info has a chance to look at the new decl
3332 flags and attributes. */
3333 if (DECL_RTL_SET_P (olddecl)
3334 && (TREE_CODE (olddecl) == FUNCTION_DECL
3335 || (VAR_P (olddecl)
3336 && TREE_STATIC (olddecl))))
3337 make_decl_rtl (olddecl);
3339 /* The NEWDECL will no longer be needed. Because every out-of-class
3340 declaration of a member results in a call to duplicate_decls,
3341 freeing these nodes represents in a significant savings.
3343 Before releasing the node, be sore to remove function from symbol
3344 table that might have been inserted there to record comdat group.
3345 Be sure to however do not free DECL_STRUCT_FUNCTION because this
3346 structure is shared in between newdecl and oldecl. */
3347 if (TREE_CODE (newdecl) == FUNCTION_DECL)
3348 DECL_STRUCT_FUNCTION (newdecl) = NULL;
3349 if (VAR_OR_FUNCTION_DECL_P (newdecl))
3351 struct symtab_node *snode = symtab_node::get (newdecl);
3352 if (snode)
3353 snode->remove ();
3356 if (TREE_CODE (olddecl) == FUNCTION_DECL)
3358 tree clone;
3359 FOR_EACH_CLONE (clone, olddecl)
3361 DECL_ATTRIBUTES (clone) = DECL_ATTRIBUTES (olddecl);
3362 DECL_PRESERVE_P (clone) |= DECL_PRESERVE_P (olddecl);
3366 /* Remove the associated constraints for newdecl, if any, before
3367 reclaiming memory. */
3368 if (flag_concepts)
3369 remove_constraints (newdecl);
3371 /* And similarly for any module tracking data. */
3372 if (modules_p ())
3373 remove_defining_module (newdecl);
3375 ggc_free (newdecl);
3377 return olddecl;
3380 /* Return zero if the declaration NEWDECL is valid
3381 when the declaration OLDDECL (assumed to be for the same name)
3382 has already been seen.
3383 Otherwise return an error message format string with a %s
3384 where the identifier should go. */
3386 static const char *
3387 redeclaration_error_message (tree newdecl, tree olddecl)
3389 if (TREE_CODE (newdecl) == TYPE_DECL)
3391 /* Because C++ can put things into name space for free,
3392 constructs like "typedef struct foo { ... } foo"
3393 would look like an erroneous redeclaration. */
3394 if (same_type_p (TREE_TYPE (newdecl), TREE_TYPE (olddecl)))
3395 return NULL;
3396 else
3397 return G_("redefinition of %q#D");
3399 else if (TREE_CODE (newdecl) == FUNCTION_DECL)
3401 /* If this is a pure function, its olddecl will actually be
3402 the original initialization to `0' (which we force to call
3403 abort()). Don't complain about redefinition in this case. */
3404 if (DECL_LANG_SPECIFIC (olddecl) && DECL_PURE_VIRTUAL_P (olddecl)
3405 && DECL_INITIAL (olddecl) == NULL_TREE)
3406 return NULL;
3408 /* If both functions come from different namespaces, this is not
3409 a redeclaration - this is a conflict with a used function. */
3410 if (DECL_NAMESPACE_SCOPE_P (olddecl)
3411 && DECL_CONTEXT (olddecl) != DECL_CONTEXT (newdecl)
3412 && ! decls_match (olddecl, newdecl))
3413 return G_("%qD conflicts with used function");
3415 /* We'll complain about linkage mismatches in
3416 warn_extern_redeclared_static. */
3418 /* Defining the same name twice is no good. */
3419 if (decl_defined_p (olddecl)
3420 && decl_defined_p (newdecl))
3422 if (DECL_NAME (olddecl) == NULL_TREE)
3423 return G_("%q#D not declared in class");
3424 else if (!GNU_INLINE_P (olddecl)
3425 || GNU_INLINE_P (newdecl))
3426 return G_("redefinition of %q#D");
3429 if (DECL_DECLARED_INLINE_P (olddecl) && DECL_DECLARED_INLINE_P (newdecl))
3431 bool olda = GNU_INLINE_P (olddecl);
3432 bool newa = GNU_INLINE_P (newdecl);
3434 if (olda != newa)
3436 if (newa)
3437 return G_("%q+D redeclared inline with "
3438 "%<gnu_inline%> attribute");
3439 else
3440 return G_("%q+D redeclared inline without "
3441 "%<gnu_inline%> attribute");
3445 /* [class.compare.default]: A definition of a comparison operator as
3446 defaulted that appears in a class shall be the first declaration of
3447 that function. */
3448 special_function_kind sfk = special_function_p (olddecl);
3449 if (sfk == sfk_comparison && DECL_DEFAULTED_FN (newdecl))
3450 return G_("comparison operator %q+D defaulted after "
3451 "its first declaration");
3453 check_abi_tag_redeclaration
3454 (olddecl, lookup_attribute ("abi_tag", DECL_ATTRIBUTES (olddecl)),
3455 lookup_attribute ("abi_tag", DECL_ATTRIBUTES (newdecl)));
3457 return NULL;
3459 else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
3461 tree nt, ot;
3463 if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == CONCEPT_DECL)
3464 return G_("redefinition of %q#D");
3466 if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) != FUNCTION_DECL)
3467 return redeclaration_error_message (DECL_TEMPLATE_RESULT (newdecl),
3468 DECL_TEMPLATE_RESULT (olddecl));
3470 if (DECL_TEMPLATE_RESULT (newdecl) == DECL_TEMPLATE_RESULT (olddecl))
3471 return NULL;
3473 nt = DECL_TEMPLATE_RESULT (newdecl);
3474 if (DECL_TEMPLATE_INFO (nt))
3475 nt = DECL_TEMPLATE_RESULT (template_for_substitution (nt));
3476 ot = DECL_TEMPLATE_RESULT (olddecl);
3477 if (DECL_TEMPLATE_INFO (ot))
3478 ot = DECL_TEMPLATE_RESULT (template_for_substitution (ot));
3479 if (DECL_INITIAL (nt) && DECL_INITIAL (ot)
3480 && (!GNU_INLINE_P (ot) || GNU_INLINE_P (nt)))
3481 return G_("redefinition of %q#D");
3483 if (DECL_DECLARED_INLINE_P (ot) && DECL_DECLARED_INLINE_P (nt))
3485 bool olda = GNU_INLINE_P (ot);
3486 bool newa = GNU_INLINE_P (nt);
3488 if (olda != newa)
3490 if (newa)
3491 return G_("%q+D redeclared inline with "
3492 "%<gnu_inline%> attribute");
3493 else
3494 return G_("%q+D redeclared inline without "
3495 "%<gnu_inline%> attribute");
3499 /* Core issue #226 (C++11):
3501 If a friend function template declaration specifies a
3502 default template-argument, that declaration shall be a
3503 definition and shall be the only declaration of the
3504 function template in the translation unit. */
3505 if ((cxx_dialect != cxx98)
3506 && TREE_CODE (ot) == FUNCTION_DECL && DECL_UNIQUE_FRIEND_P (ot)
3507 && !check_default_tmpl_args (nt, DECL_TEMPLATE_PARMS (newdecl),
3508 /*is_primary=*/true,
3509 /*is_partial=*/false,
3510 /*is_friend_decl=*/2))
3511 return G_("redeclaration of friend %q#D "
3512 "may not have default template arguments");
3514 return NULL;
3516 else if (VAR_P (newdecl)
3517 && (CP_DECL_THREAD_LOCAL_P (newdecl)
3518 != CP_DECL_THREAD_LOCAL_P (olddecl))
3519 && (! DECL_LANG_SPECIFIC (olddecl)
3520 || ! CP_DECL_THREADPRIVATE_P (olddecl)
3521 || CP_DECL_THREAD_LOCAL_P (newdecl)))
3523 /* Only variables can be thread-local, and all declarations must
3524 agree on this property. */
3525 if (CP_DECL_THREAD_LOCAL_P (newdecl))
3526 return G_("thread-local declaration of %q#D follows "
3527 "non-thread-local declaration");
3528 else
3529 return G_("non-thread-local declaration of %q#D follows "
3530 "thread-local declaration");
3532 else if (toplevel_bindings_p () || DECL_NAMESPACE_SCOPE_P (newdecl))
3534 /* The objects have been declared at namespace scope. If either
3535 is a member of an anonymous union, then this is an invalid
3536 redeclaration. For example:
3538 int i;
3539 union { int i; };
3541 is invalid. */
3542 if ((VAR_P (newdecl) && DECL_ANON_UNION_VAR_P (newdecl))
3543 || (VAR_P (olddecl) && DECL_ANON_UNION_VAR_P (olddecl)))
3544 return G_("redeclaration of %q#D");
3545 /* If at least one declaration is a reference, there is no
3546 conflict. For example:
3548 int i = 3;
3549 extern int i;
3551 is valid. */
3552 if (DECL_EXTERNAL (newdecl) || DECL_EXTERNAL (olddecl))
3553 return NULL;
3555 /* Static data member declared outside a class definition
3556 if the variable is defined within the class with constexpr
3557 specifier is declaration rather than definition (and
3558 deprecated). */
3559 if (cxx_dialect >= cxx17
3560 && VAR_P (olddecl)
3561 && DECL_CLASS_SCOPE_P (olddecl)
3562 && DECL_DECLARED_CONSTEXPR_P (olddecl)
3563 && !DECL_INITIAL (newdecl))
3565 DECL_EXTERNAL (newdecl) = 1;
3566 /* For now, only warn with explicit -Wdeprecated. */
3567 if (OPTION_SET_P (warn_deprecated))
3569 auto_diagnostic_group d;
3570 if (warning_at (DECL_SOURCE_LOCATION (newdecl), OPT_Wdeprecated,
3571 "redundant redeclaration of %<constexpr%> "
3572 "static data member %qD", newdecl))
3573 inform (DECL_SOURCE_LOCATION (olddecl),
3574 "previous declaration of %qD", olddecl);
3576 return NULL;
3579 /* Reject two definitions. */
3580 return G_("redefinition of %q#D");
3582 else
3584 /* Objects declared with block scope: */
3585 /* Reject two definitions, and reject a definition
3586 together with an external reference. */
3587 if (!(DECL_EXTERNAL (newdecl) && DECL_EXTERNAL (olddecl)))
3588 return G_("redeclaration of %q#D");
3589 return NULL;
3594 /* Hash and equality functions for the named_label table. */
3596 hashval_t
3597 named_label_hash::hash (const value_type entry)
3599 return IDENTIFIER_HASH_VALUE (entry->name);
3602 bool
3603 named_label_hash::equal (const value_type entry, compare_type name)
3605 return name == entry->name;
3608 /* Look for a label named ID in the current function. If one cannot
3609 be found, create one. Return the named_label_entry, or NULL on
3610 failure. */
3612 static named_label_entry *
3613 lookup_label_1 (tree id, bool making_local_p)
3615 auto_cond_timevar tv (TV_NAME_LOOKUP);
3617 /* You can't use labels at global scope. */
3618 if (current_function_decl == NULL_TREE)
3620 error ("label %qE referenced outside of any function", id);
3621 return NULL;
3624 if (!named_labels)
3625 named_labels = hash_table<named_label_hash>::create_ggc (13);
3627 hashval_t hash = IDENTIFIER_HASH_VALUE (id);
3628 named_label_entry **slot
3629 = named_labels->find_slot_with_hash (id, hash, INSERT);
3630 named_label_entry *old = *slot;
3632 if (old && old->label_decl)
3634 if (!making_local_p)
3635 return old;
3637 if (old->binding_level == current_binding_level)
3639 auto_diagnostic_group d;
3640 error ("local label %qE conflicts with existing label", id);
3641 inform (DECL_SOURCE_LOCATION (old->label_decl), "previous label");
3642 return NULL;
3646 /* We are making a new decl, create or reuse the named_label_entry */
3647 named_label_entry *ent = NULL;
3648 if (old && !old->label_decl)
3649 ent = old;
3650 else
3652 ent = ggc_cleared_alloc<named_label_entry> ();
3653 ent->name = id;
3654 ent->outer = old;
3655 *slot = ent;
3658 /* Now create the LABEL_DECL. */
3659 tree decl = build_decl (input_location, LABEL_DECL, id, void_type_node);
3661 DECL_CONTEXT (decl) = current_function_decl;
3662 SET_DECL_MODE (decl, VOIDmode);
3663 if (making_local_p)
3665 C_DECLARED_LABEL_FLAG (decl) = true;
3666 DECL_CHAIN (decl) = current_binding_level->names;
3667 current_binding_level->names = decl;
3670 ent->label_decl = decl;
3672 return ent;
3675 /* Wrapper for lookup_label_1. */
3677 tree
3678 lookup_label (tree id)
3680 named_label_entry *ent = lookup_label_1 (id, false);
3681 return ent ? ent->label_decl : NULL_TREE;
3684 /* Remember that we've seen &&ID. */
3686 void
3687 mark_label_addressed (tree id)
3689 named_label_entry *ent = lookup_label_1 (id, false);
3690 ent->addressed = true;
3693 tree
3694 declare_local_label (tree id)
3696 named_label_entry *ent = lookup_label_1 (id, true);
3697 return ent ? ent->label_decl : NULL_TREE;
3700 /* Returns true if it is ill-formed to jump past the declaration of DECL. */
3702 static bool
3703 decl_jump_unsafe (tree decl)
3705 /* [stmt.dcl]/3: A program that jumps from a point where a local variable
3706 with automatic storage duration is not in scope to a point where it is
3707 in scope is ill-formed unless the variable has scalar type, class type
3708 with a trivial default constructor and a trivial destructor, a
3709 cv-qualified version of one of these types, or an array of one of the
3710 preceding types and is declared without an initializer (8.5). */
3711 tree type = TREE_TYPE (decl);
3713 return (type != error_mark_node
3714 && VAR_P (decl)
3715 && !TREE_STATIC (decl)
3716 && (DECL_NONTRIVIALLY_INITIALIZED_P (decl)
3717 || variably_modified_type_p (type, NULL_TREE)));
3720 /* A subroutine of check_previous_goto_1 and check_goto to identify a branch
3721 to the user. */
3723 static bool
3724 identify_goto (tree decl, location_t loc, const location_t *locus,
3725 diagnostic_t diag_kind, bool computed)
3727 if (computed)
3728 diag_kind = DK_WARNING;
3729 bool complained
3730 = emit_diagnostic (diag_kind, loc, 0,
3731 decl ? G_("jump to label %qD")
3732 : G_("jump to case label"), decl);
3733 if (complained && locus)
3735 if (computed)
3736 inform (*locus, " as a possible target of computed goto");
3737 else
3738 inform (*locus, " from here");
3740 return complained;
3743 /* Check that a single previously seen jump to a newly defined label
3744 is OK. DECL is the LABEL_DECL or 0; LEVEL is the binding_level for
3745 the jump context; NAMES are the names in scope in LEVEL at the jump
3746 context; LOCUS is the source position of the jump or 0. COMPUTED
3747 is a vec of decls if the jump is a computed goto. Returns
3748 true if all is well. */
3750 static bool
3751 check_previous_goto_1 (tree decl, cp_binding_level* level, tree names,
3752 bool exited_omp, const location_t *locus,
3753 vec<tree,va_gc> *computed)
3755 auto_diagnostic_group d;
3756 cp_binding_level *b;
3757 bool complained = false;
3758 int identified = 0;
3759 bool saw_eh = false, saw_omp = false, saw_tm = false, saw_cxif = false;
3760 bool saw_ceif = false, saw_se = false;
3762 if (exited_omp)
3764 complained = identify_goto (decl, input_location, locus, DK_ERROR,
3765 computed);
3766 if (complained)
3767 inform (input_location, " exits OpenMP structured block");
3768 saw_omp = true;
3769 identified = 2;
3772 for (b = current_binding_level; b ; b = b->level_chain)
3774 tree new_decls, old_decls = (b == level ? names : NULL_TREE);
3776 for (new_decls = b->names; new_decls != old_decls;
3777 new_decls = (DECL_P (new_decls) ? DECL_CHAIN (new_decls)
3778 : TREE_CHAIN (new_decls)))
3780 bool problem = decl_jump_unsafe (new_decls);
3781 if (! problem)
3782 continue;
3784 if (!identified)
3786 complained = identify_goto (decl, input_location, locus, DK_ERROR,
3787 computed);
3788 identified = 2;
3790 if (complained)
3791 inform (DECL_SOURCE_LOCATION (new_decls),
3792 " crosses initialization of %q#D", new_decls);
3795 if (b == level)
3796 break;
3798 const char *inf = NULL;
3799 location_t loc = input_location;
3800 switch (b->kind)
3802 case sk_try:
3803 if (!saw_eh)
3804 inf = G_(" enters %<try%> block");
3805 saw_eh = true;
3806 break;
3808 case sk_catch:
3809 if (!saw_eh)
3810 inf = G_(" enters %<catch%> block");
3811 saw_eh = true;
3812 break;
3814 case sk_omp:
3815 if (!saw_omp)
3816 inf = G_(" enters OpenMP structured block");
3817 saw_omp = true;
3818 break;
3820 case sk_transaction:
3821 if (!saw_tm)
3822 inf = G_(" enters synchronized or atomic statement");
3823 saw_tm = true;
3824 break;
3826 case sk_stmt_expr:
3827 if (!saw_se)
3828 inf = G_(" enters statement expression");
3829 saw_se = true;
3830 break;
3832 case sk_block:
3833 if (!saw_cxif && level_for_constexpr_if (b->level_chain))
3835 inf = G_(" enters %<constexpr if%> statement");
3836 loc = EXPR_LOCATION (b->level_chain->this_entity);
3837 saw_cxif = true;
3839 else if (!saw_ceif && level_for_consteval_if (b->level_chain))
3841 inf = G_(" enters %<consteval if%> statement");
3842 loc = EXPR_LOCATION (b->level_chain->this_entity);
3843 saw_ceif = true;
3845 break;
3847 default:
3848 break;
3851 if (inf)
3853 if (identified < 2)
3854 complained = identify_goto (decl, input_location, locus, DK_ERROR,
3855 computed);
3856 identified = 2;
3857 if (complained)
3858 inform (loc, inf);
3862 if (!vec_safe_is_empty (computed))
3864 if (!identified)
3865 complained = identify_goto (decl, input_location, locus, DK_ERROR,
3866 computed);
3867 identified = 2;
3868 if (complained)
3869 for (tree d : computed)
3871 if (DECL_P (d))
3872 inform (DECL_SOURCE_LOCATION (d), " does not destroy %qD", d);
3873 else if (d == get_identifier ("catch"))
3874 inform (*locus, " does not clean up handled exception");
3878 return !identified;
3881 static void
3882 check_previous_goto (tree decl, struct named_label_use_entry *use)
3884 check_previous_goto_1 (decl, use->binding_level,
3885 use->names_in_scope, use->in_omp_scope,
3886 &use->o_goto_locus, use->computed_goto);
3889 static bool
3890 check_switch_goto (cp_binding_level* level)
3892 return check_previous_goto_1 (NULL_TREE, level, level->names,
3893 false, NULL, nullptr);
3896 /* Check that a new jump to a label ENT is OK. COMPUTED is true
3897 if this is a possible target of a computed goto. */
3899 void
3900 check_goto_1 (named_label_entry *ent, bool computed)
3902 auto_diagnostic_group d;
3903 tree decl = ent->label_decl;
3905 /* If the label hasn't been defined yet, defer checking. */
3906 if (! DECL_INITIAL (decl))
3908 /* Don't bother creating another use if the last goto had the
3909 same data, and will therefore create the same set of errors. */
3910 if (ent->uses
3911 && ent->uses->names_in_scope == current_binding_level->names)
3912 return;
3914 named_label_use_entry *new_use
3915 = ggc_alloc<named_label_use_entry> ();
3916 new_use->binding_level = current_binding_level;
3917 new_use->names_in_scope = current_binding_level->names;
3918 new_use->o_goto_locus = input_location;
3919 new_use->in_omp_scope = false;
3920 new_use->computed_goto = computed ? make_tree_vector () : nullptr;
3922 new_use->next = ent->uses;
3923 ent->uses = new_use;
3924 return;
3927 bool saw_catch = false, complained = false;
3928 int identified = 0;
3929 tree bad;
3930 unsigned ix;
3932 if (ent->in_try_scope || ent->in_catch_scope || ent->in_transaction_scope
3933 || ent->in_constexpr_if || ent->in_consteval_if
3934 || ent->in_omp_scope || ent->in_stmt_expr
3935 || !vec_safe_is_empty (ent->bad_decls))
3937 diagnostic_t diag_kind = DK_PERMERROR;
3938 if (ent->in_try_scope || ent->in_catch_scope || ent->in_constexpr_if
3939 || ent->in_consteval_if || ent->in_transaction_scope
3940 || ent->in_omp_scope || ent->in_stmt_expr)
3941 diag_kind = DK_ERROR;
3942 complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3943 &input_location, diag_kind, computed);
3944 identified = 1 + (diag_kind == DK_ERROR);
3947 FOR_EACH_VEC_SAFE_ELT (ent->bad_decls, ix, bad)
3949 bool problem = decl_jump_unsafe (bad);
3951 if (problem && DECL_ARTIFICIAL (bad))
3953 /* Can't skip init of __exception_info. */
3954 if (identified == 1)
3956 complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3957 &input_location, DK_ERROR, computed);
3958 identified = 2;
3960 if (complained)
3961 inform (DECL_SOURCE_LOCATION (bad), " enters %<catch%> block");
3962 saw_catch = true;
3964 else if (complained)
3965 inform (DECL_SOURCE_LOCATION (bad),
3966 " skips initialization of %q#D", bad);
3969 if (complained)
3971 if (ent->in_try_scope)
3972 inform (input_location, " enters %<try%> block");
3973 else if (ent->in_catch_scope && !saw_catch)
3974 inform (input_location, " enters %<catch%> block");
3975 else if (ent->in_transaction_scope)
3976 inform (input_location, " enters synchronized or atomic statement");
3977 else if (ent->in_constexpr_if)
3978 inform (input_location, " enters %<constexpr if%> statement");
3979 else if (ent->in_consteval_if)
3980 inform (input_location, " enters %<consteval if%> statement");
3981 else if (ent->in_stmt_expr)
3982 inform (input_location, " enters statement expression");
3985 if (ent->in_omp_scope)
3987 if (complained)
3988 inform (input_location, " enters OpenMP structured block");
3990 else if (flag_openmp)
3991 for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3993 if (b == ent->binding_level)
3994 break;
3995 if (b->kind == sk_omp)
3997 if (identified < 2)
3999 complained = identify_goto (decl,
4000 DECL_SOURCE_LOCATION (decl),
4001 &input_location, DK_ERROR,
4002 computed);
4003 identified = 2;
4005 if (complained)
4006 inform (input_location, " exits OpenMP structured block");
4007 break;
4011 /* Warn if a computed goto might involve a local variable going out of scope
4012 without being cleaned up. */
4013 if (computed)
4015 auto level = ent->binding_level;
4016 auto names = ent->names_in_scope;
4017 for (auto b = current_binding_level; ; b = b->level_chain)
4019 if (b->kind == sk_catch)
4021 if (!identified)
4023 complained
4024 = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
4025 &input_location, DK_ERROR, computed);
4026 identified = 2;
4028 if (complained)
4029 inform (input_location,
4030 " does not clean up handled exception");
4032 tree end = b == level ? names : NULL_TREE;
4033 for (tree d = b->names; d != end; d = DECL_CHAIN (d))
4035 if (automatic_var_with_nontrivial_dtor_p (d))
4037 if (!identified)
4039 complained
4040 = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
4041 &input_location, DK_ERROR, computed);
4042 identified = 2;
4044 if (complained)
4045 inform (DECL_SOURCE_LOCATION (d),
4046 " does not destroy %qD", d);
4049 if (b == level)
4050 break;
4055 /* Check that a new jump to a label DECL is OK. Called by
4056 finish_goto_stmt. */
4058 void
4059 check_goto (tree decl)
4061 if (!named_labels)
4062 return;
4063 if (TREE_CODE (decl) != LABEL_DECL)
4065 /* We don't know where a computed goto is jumping,
4066 so check all addressable labels. */
4067 for (auto iter = named_labels->begin ();
4068 iter != named_labels->end ();
4069 ++iter)
4071 auto ent = *iter;
4072 if (ent->addressed)
4073 check_goto_1 (ent, true);
4076 else
4078 hashval_t hash = IDENTIFIER_HASH_VALUE (DECL_NAME (decl));
4079 named_label_entry **slot
4080 = named_labels->find_slot_with_hash (DECL_NAME (decl), hash, NO_INSERT);
4081 named_label_entry *ent = *slot;
4082 check_goto_1 (ent, false);
4086 /* Check that a return is ok wrt OpenMP structured blocks.
4087 Called by finish_return_stmt. Returns true if all is well. */
4089 bool
4090 check_omp_return (void)
4092 for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
4093 if (b->kind == sk_omp)
4095 error ("invalid exit from OpenMP structured block");
4096 return false;
4098 else if (b->kind == sk_function_parms)
4099 break;
4100 return true;
4103 /* Define a label, specifying the location in the source file.
4104 Return the LABEL_DECL node for the label. */
4106 tree
4107 define_label (location_t location, tree name)
4109 auto_cond_timevar tv (TV_NAME_LOOKUP);
4111 /* After labels, make any new cleanups in the function go into their
4112 own new (temporary) binding contour. */
4113 for (cp_binding_level *p = current_binding_level;
4114 p->kind != sk_function_parms;
4115 p = p->level_chain)
4116 p->more_cleanups_ok = 0;
4118 named_label_entry *ent = lookup_label_1 (name, false);
4119 tree decl = ent->label_decl;
4121 if (DECL_INITIAL (decl) != NULL_TREE)
4123 error ("duplicate label %qD", decl);
4124 return error_mark_node;
4126 else
4128 /* Mark label as having been defined. */
4129 DECL_INITIAL (decl) = error_mark_node;
4130 /* Say where in the source. */
4131 DECL_SOURCE_LOCATION (decl) = location;
4133 ent->binding_level = current_binding_level;
4134 ent->names_in_scope = current_binding_level->names;
4136 for (named_label_use_entry *use = ent->uses; use; use = use->next)
4137 check_previous_goto (decl, use);
4138 ent->uses = NULL;
4141 return decl;
4144 struct cp_switch
4146 cp_binding_level *level;
4147 struct cp_switch *next;
4148 /* The SWITCH_STMT being built. */
4149 tree switch_stmt;
4150 /* A splay-tree mapping the low element of a case range to the high
4151 element, or NULL_TREE if there is no high element. Used to
4152 determine whether or not a new case label duplicates an old case
4153 label. We need a tree, rather than simply a hash table, because
4154 of the GNU case range extension. */
4155 splay_tree cases;
4156 /* Remember whether a default: case label has been seen. */
4157 bool has_default_p;
4158 /* Remember whether a BREAK_STMT has been seen in this SWITCH_STMT. */
4159 bool break_stmt_seen_p;
4160 /* Set if inside of {FOR,DO,WHILE}_BODY nested inside of a switch,
4161 where BREAK_STMT doesn't belong to the SWITCH_STMT. */
4162 bool in_loop_body_p;
4165 /* A stack of the currently active switch statements. The innermost
4166 switch statement is on the top of the stack. There is no need to
4167 mark the stack for garbage collection because it is only active
4168 during the processing of the body of a function, and we never
4169 collect at that point. */
4171 static struct cp_switch *switch_stack;
4173 /* Called right after a switch-statement condition is parsed.
4174 SWITCH_STMT is the switch statement being parsed. */
4176 void
4177 push_switch (tree switch_stmt)
4179 struct cp_switch *p = XNEW (struct cp_switch);
4180 p->level = current_binding_level;
4181 p->next = switch_stack;
4182 p->switch_stmt = switch_stmt;
4183 p->cases = splay_tree_new (case_compare, NULL, NULL);
4184 p->has_default_p = false;
4185 p->break_stmt_seen_p = false;
4186 p->in_loop_body_p = false;
4187 switch_stack = p;
4190 void
4191 pop_switch (void)
4193 struct cp_switch *cs = switch_stack;
4195 /* Emit warnings as needed. */
4196 location_t switch_location = cp_expr_loc_or_input_loc (cs->switch_stmt);
4197 tree cond = SWITCH_STMT_COND (cs->switch_stmt);
4198 const bool bool_cond_p
4199 = (SWITCH_STMT_TYPE (cs->switch_stmt)
4200 && TREE_CODE (SWITCH_STMT_TYPE (cs->switch_stmt)) == BOOLEAN_TYPE);
4201 if (!processing_template_decl)
4202 c_do_switch_warnings (cs->cases, switch_location,
4203 SWITCH_STMT_TYPE (cs->switch_stmt), cond,
4204 bool_cond_p);
4206 /* For the benefit of block_may_fallthru remember if the switch body
4207 case labels cover all possible values and if there are break; stmts. */
4208 if (cs->has_default_p
4209 || (!processing_template_decl
4210 && c_switch_covers_all_cases_p (cs->cases,
4211 SWITCH_STMT_TYPE (cs->switch_stmt))))
4212 SWITCH_STMT_ALL_CASES_P (cs->switch_stmt) = 1;
4213 if (!cs->break_stmt_seen_p)
4214 SWITCH_STMT_NO_BREAK_P (cs->switch_stmt) = 1;
4215 /* Now that we're done with the switch warnings, set the switch type
4216 to the type of the condition if the index type was of scoped enum type.
4217 (Such types don't participate in the integer promotions.) We do this
4218 because of bit-fields whose declared type is a scoped enum type:
4219 gimplification will use the lowered index type, but convert the
4220 case values to SWITCH_STMT_TYPE, which would have been the declared type
4221 and verify_gimple_switch doesn't accept that. */
4222 if (is_bitfield_expr_with_lowered_type (cond))
4223 SWITCH_STMT_TYPE (cs->switch_stmt) = TREE_TYPE (cond);
4224 gcc_assert (!cs->in_loop_body_p);
4225 splay_tree_delete (cs->cases);
4226 switch_stack = switch_stack->next;
4227 free (cs);
4230 /* Note that a BREAK_STMT is about to be added. If it is inside of
4231 a SWITCH_STMT and not inside of a loop body inside of it, note
4232 in switch_stack we've seen a BREAK_STMT. */
4234 void
4235 note_break_stmt (void)
4237 if (switch_stack && !switch_stack->in_loop_body_p)
4238 switch_stack->break_stmt_seen_p = true;
4241 /* Note the start of processing of an iteration statement's body.
4242 The note_break_stmt function will do nothing while processing it.
4243 Return a flag that should be passed to note_iteration_stmt_body_end. */
4245 bool
4246 note_iteration_stmt_body_start (void)
4248 if (!switch_stack)
4249 return false;
4250 bool ret = switch_stack->in_loop_body_p;
4251 switch_stack->in_loop_body_p = true;
4252 return ret;
4255 /* Note the end of processing of an iteration statement's body. */
4257 void
4258 note_iteration_stmt_body_end (bool prev)
4260 if (switch_stack)
4261 switch_stack->in_loop_body_p = prev;
4264 /* Convert a case constant VALUE in a switch to the type TYPE of the switch
4265 condition. Note that if TYPE and VALUE are already integral we don't
4266 really do the conversion because the language-independent
4267 warning/optimization code will work better that way. */
4269 static tree
4270 case_conversion (tree type, tree value)
4272 if (value == NULL_TREE)
4273 return value;
4275 value = mark_rvalue_use (value);
4277 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
4278 type = type_promotes_to (type);
4280 tree ovalue = value;
4281 /* The constant-expression VALUE shall be a converted constant expression
4282 of the adjusted type of the switch condition, which doesn't allow
4283 narrowing conversions. */
4284 value = build_converted_constant_expr (type, value, tf_warning_or_error);
4286 if (cxx_dialect >= cxx11
4287 && (SCOPED_ENUM_P (type)
4288 || !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ovalue))))
4289 /* Use the converted value. */;
4290 else
4291 /* The already integral case. */
4292 value = ovalue;
4294 return cxx_constant_value (value);
4297 /* Note that we've seen a definition of a case label, and complain if this
4298 is a bad place for one. */
4300 tree
4301 finish_case_label (location_t loc, tree low_value, tree high_value)
4303 tree cond, r;
4304 cp_binding_level *p;
4305 tree type;
4307 if (low_value == NULL_TREE && high_value == NULL_TREE)
4308 switch_stack->has_default_p = true;
4310 if (processing_template_decl)
4312 tree label;
4314 /* For templates, just add the case label; we'll do semantic
4315 analysis at instantiation-time. */
4316 label = build_decl (loc, LABEL_DECL, NULL_TREE, void_type_node);
4317 return add_stmt (build_case_label (low_value, high_value, label));
4320 /* Find the condition on which this switch statement depends. */
4321 cond = SWITCH_STMT_COND (switch_stack->switch_stmt);
4322 if (cond && TREE_CODE (cond) == TREE_LIST)
4323 cond = TREE_VALUE (cond);
4325 if (!check_switch_goto (switch_stack->level))
4326 return error_mark_node;
4328 type = SWITCH_STMT_TYPE (switch_stack->switch_stmt);
4329 if (type == error_mark_node)
4330 return error_mark_node;
4332 low_value = case_conversion (type, low_value);
4333 high_value = case_conversion (type, high_value);
4335 r = c_add_case_label (loc, switch_stack->cases, cond, low_value, high_value);
4337 /* After labels, make any new cleanups in the function go into their
4338 own new (temporary) binding contour. */
4339 for (p = current_binding_level;
4340 p->kind != sk_function_parms;
4341 p = p->level_chain)
4342 p->more_cleanups_ok = 0;
4344 return r;
4347 struct typename_info {
4348 tree scope;
4349 tree name;
4350 tree template_id;
4351 bool enum_p;
4352 bool class_p;
4355 struct typename_hasher : ggc_ptr_hash<tree_node>
4357 typedef typename_info *compare_type;
4359 /* Hash a TYPENAME_TYPE. */
4361 static hashval_t
4362 hash (tree context, tree fullname)
4364 hashval_t hash = 0;
4365 hash = iterative_hash_object (context, hash);
4366 hash = iterative_hash_object (fullname, hash);
4367 return hash;
4370 static hashval_t
4371 hash (const typename_info *ti)
4373 return typename_hasher::hash (ti->scope, ti->template_id);
4376 static hashval_t
4377 hash (tree t)
4379 return typename_hasher::hash (TYPE_CONTEXT (t), TYPENAME_TYPE_FULLNAME (t));
4382 /* Compare two TYPENAME_TYPEs. */
4384 static bool
4385 equal (tree t1, const typename_info *t2)
4387 return (TYPE_IDENTIFIER (t1) == t2->name
4388 && TYPE_CONTEXT (t1) == t2->scope
4389 && TYPENAME_TYPE_FULLNAME (t1) == t2->template_id
4390 && TYPENAME_IS_ENUM_P (t1) == t2->enum_p
4391 && TYPENAME_IS_CLASS_P (t1) == t2->class_p);
4395 /* Build a TYPENAME_TYPE. If the type is `typename T::t', CONTEXT is
4396 the type of `T', NAME is the IDENTIFIER_NODE for `t'.
4398 Returns the new TYPENAME_TYPE. */
4400 static GTY (()) hash_table<typename_hasher> *typename_htab;
4402 tree
4403 build_typename_type (tree context, tree name, tree fullname,
4404 enum tag_types tag_type)
4406 typename_info ti;
4408 if (typename_htab == NULL)
4409 typename_htab = hash_table<typename_hasher>::create_ggc (61);
4411 ti.scope = FROB_CONTEXT (context);
4412 ti.name = name;
4413 ti.template_id = fullname;
4414 ti.enum_p = tag_type == enum_type;
4415 ti.class_p = (tag_type == class_type
4416 || tag_type == record_type
4417 || tag_type == union_type);
4418 hashval_t hash = typename_hasher::hash (&ti);
4420 /* See if we already have this type. */
4421 tree *e = typename_htab->find_slot_with_hash (&ti, hash, INSERT);
4422 tree t = *e;
4423 if (*e)
4424 t = *e;
4425 else
4427 /* Build the TYPENAME_TYPE. */
4428 t = cxx_make_type (TYPENAME_TYPE);
4429 TYPE_CONTEXT (t) = ti.scope;
4430 TYPENAME_TYPE_FULLNAME (t) = ti.template_id;
4431 TYPENAME_IS_ENUM_P (t) = ti.enum_p;
4432 TYPENAME_IS_CLASS_P (t) = ti.class_p;
4434 /* Build the corresponding TYPE_DECL. */
4435 tree d = build_decl (input_location, TYPE_DECL, name, t);
4436 TYPE_NAME (t) = d;
4437 TYPE_STUB_DECL (t) = d;
4438 DECL_CONTEXT (d) = ti.scope;
4439 DECL_ARTIFICIAL (d) = 1;
4441 /* Store it in the hash table. */
4442 *e = t;
4444 /* TYPENAME_TYPEs must always be compared structurally, because
4445 they may or may not resolve down to another type depending on
4446 the currently open classes. */
4447 SET_TYPE_STRUCTURAL_EQUALITY (t);
4450 return t;
4453 /* Resolve `typename CONTEXT::NAME'. TAG_TYPE indicates the tag
4454 provided to name the type. Returns an appropriate type, unless an
4455 error occurs, in which case error_mark_node is returned. If we
4456 locate a non-artificial TYPE_DECL and TF_KEEP_TYPE_DECL is set, we
4457 return that, rather than the _TYPE it corresponds to, in other
4458 cases we look through the type decl. If TF_ERROR is set, complain
4459 about errors, otherwise be quiet. */
4461 tree
4462 make_typename_type (tree context, tree name, enum tag_types tag_type,
4463 tsubst_flags_t complain)
4465 tree fullname;
4466 tree t;
4467 bool want_template;
4469 if (name == error_mark_node
4470 || context == NULL_TREE
4471 || context == error_mark_node)
4472 return error_mark_node;
4474 if (TYPE_P (name))
4476 if (!(TYPE_LANG_SPECIFIC (name)
4477 && (CLASSTYPE_IS_TEMPLATE (name)
4478 || CLASSTYPE_USE_TEMPLATE (name))))
4479 name = TYPE_IDENTIFIER (name);
4480 else
4481 /* Create a TEMPLATE_ID_EXPR for the type. */
4482 name = build_nt (TEMPLATE_ID_EXPR,
4483 CLASSTYPE_TI_TEMPLATE (name),
4484 CLASSTYPE_TI_ARGS (name));
4486 else if (TREE_CODE (name) == TYPE_DECL)
4487 name = DECL_NAME (name);
4489 fullname = name;
4491 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
4493 name = TREE_OPERAND (name, 0);
4494 if (DECL_TYPE_TEMPLATE_P (name))
4495 name = TREE_OPERAND (fullname, 0) = DECL_NAME (name);
4496 if (TREE_CODE (name) != IDENTIFIER_NODE)
4498 if (complain & tf_error)
4499 error ("%qD is not a type", name);
4500 return error_mark_node;
4503 if (TREE_CODE (name) == TEMPLATE_DECL)
4505 if (complain & tf_error)
4506 error ("%qD used without template arguments", name);
4507 return error_mark_node;
4509 else if (is_overloaded_fn (name))
4511 if (complain & tf_error)
4512 error ("%qD is a function, not a type", name);
4513 return error_mark_node;
4515 gcc_assert (identifier_p (name));
4516 gcc_assert (TYPE_P (context));
4518 if (TREE_CODE (context) == TYPE_PACK_EXPANSION)
4519 /* This can happen for C++17 variadic using (c++/88986). */;
4520 else if (!MAYBE_CLASS_TYPE_P (context))
4522 if (complain & tf_error)
4523 error ("%q#T is not a class", context);
4524 return error_mark_node;
4527 /* When the CONTEXT is a dependent type, NAME could refer to a
4528 dependent base class of CONTEXT. But look inside it anyway
4529 if CONTEXT is a currently open scope, in case it refers to a
4530 member of the current instantiation or a non-dependent base;
4531 lookup will stop when we hit a dependent base. */
4532 if (!dependent_scope_p (context))
4534 /* We generally don't ignore non-types during TYPENAME_TYPE lookup
4535 (as per [temp.res.general]/3), unless
4536 - the tag corresponds to a class-key or 'enum' so
4537 [basic.lookup.elab] applies, or
4538 - the tag corresponds to scope_type or tf_qualifying_scope is
4539 set so [basic.lookup.qual]/1 applies.
4540 TODO: If we'd set/track the scope_type tag thoroughly on all
4541 TYPENAME_TYPEs that are followed by :: then we wouldn't need the
4542 tf_qualifying_scope flag. */
4543 bool want_type = (tag_type != none_type && tag_type != typename_type)
4544 || (complain & tf_qualifying_scope);
4545 t = lookup_member (context, name, /*protect=*/2, want_type, complain);
4547 else
4548 t = NULL_TREE;
4550 if ((!t || TREE_CODE (t) == TREE_LIST) && dependentish_scope_p (context))
4551 return build_typename_type (context, name, fullname, tag_type);
4553 want_template = TREE_CODE (fullname) == TEMPLATE_ID_EXPR;
4555 if (!t)
4557 if (complain & tf_error)
4559 if (!COMPLETE_TYPE_P (context))
4560 cxx_incomplete_type_error (NULL_TREE, context);
4561 else
4562 error (want_template ? G_("no class template named %q#T in %q#T")
4563 : G_("no type named %q#T in %q#T"), name, context);
4565 return error_mark_node;
4568 /* Pull out the template from an injected-class-name (or multiple). */
4569 if (want_template)
4570 t = maybe_get_template_decl_from_type_decl (t);
4572 if (TREE_CODE (t) == TREE_LIST)
4574 if (complain & tf_error)
4576 auto_diagnostic_group d;
4577 error ("lookup of %qT in %qT is ambiguous", name, context);
4578 print_candidates (t);
4580 return error_mark_node;
4583 if (want_template && !DECL_TYPE_TEMPLATE_P (t))
4585 if (complain & tf_error)
4586 error ("%<typename %T::%D%> names %q#T, which is not a class template",
4587 context, name, t);
4588 return error_mark_node;
4590 if (!want_template && TREE_CODE (t) != TYPE_DECL)
4592 if ((complain & tf_tst_ok) && cxx_dialect >= cxx17
4593 && DECL_TYPE_TEMPLATE_P (t))
4594 /* The caller permits this typename-specifier to name a template
4595 (because it appears in a CTAD-enabled context). */;
4596 else
4598 if (complain & tf_error)
4599 error ("%<typename %T::%D%> names %q#D, which is not a type",
4600 context, name, t);
4601 return error_mark_node;
4605 if (!check_accessibility_of_qualified_id (t, /*object_type=*/NULL_TREE,
4606 context, complain))
4607 return error_mark_node;
4609 if (!want_template && DECL_TYPE_TEMPLATE_P (t))
4610 return make_template_placeholder (t);
4612 if (want_template)
4614 t = lookup_template_class (t, TREE_OPERAND (fullname, 1),
4615 NULL_TREE, context,
4616 complain | tf_user);
4617 if (t == error_mark_node)
4618 return error_mark_node;
4619 t = TYPE_NAME (t);
4622 if (DECL_ARTIFICIAL (t) || !(complain & tf_keep_type_decl))
4623 t = TREE_TYPE (t);
4625 maybe_record_typedef_use (t);
4627 return t;
4630 /* Resolve `CONTEXT::template NAME'. Returns a TEMPLATE_DECL if the name
4631 can be resolved or an UNBOUND_CLASS_TEMPLATE, unless an error occurs,
4632 in which case error_mark_node is returned.
4634 If PARM_LIST is non-NULL, also make sure that the template parameter
4635 list of TEMPLATE_DECL matches.
4637 If COMPLAIN zero, don't complain about any errors that occur. */
4639 tree
4640 make_unbound_class_template (tree context, tree name, tree parm_list,
4641 tsubst_flags_t complain)
4643 if (TYPE_P (name))
4644 name = TYPE_IDENTIFIER (name);
4645 else if (DECL_P (name))
4646 name = DECL_NAME (name);
4647 gcc_assert (identifier_p (name));
4649 if (!dependent_type_p (context)
4650 || currently_open_class (context))
4652 tree tmpl = NULL_TREE;
4654 if (MAYBE_CLASS_TYPE_P (context))
4655 tmpl = lookup_field (context, name, 0, false);
4657 if (tmpl && TREE_CODE (tmpl) == TYPE_DECL)
4658 tmpl = maybe_get_template_decl_from_type_decl (tmpl);
4660 if (!tmpl || !DECL_TYPE_TEMPLATE_P (tmpl))
4662 if (complain & tf_error)
4663 error ("no class template named %q#T in %q#T", name, context);
4664 return error_mark_node;
4667 if (parm_list
4668 && !comp_template_parms (DECL_TEMPLATE_PARMS (tmpl), parm_list))
4670 if (complain & tf_error)
4672 auto_diagnostic_group d;
4673 error ("template parameters do not match template %qD", tmpl);
4674 inform (DECL_SOURCE_LOCATION (tmpl),
4675 "%qD declared here", tmpl);
4677 return error_mark_node;
4680 if (!perform_or_defer_access_check (TYPE_BINFO (context), tmpl, tmpl,
4681 complain))
4682 return error_mark_node;
4684 return tmpl;
4687 return make_unbound_class_template_raw (context, name, parm_list);
4690 /* Build an UNBOUND_CLASS_TEMPLATE. */
4692 tree
4693 make_unbound_class_template_raw (tree context, tree name, tree parm_list)
4695 /* Build the UNBOUND_CLASS_TEMPLATE. */
4696 tree t = cxx_make_type (UNBOUND_CLASS_TEMPLATE);
4697 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
4698 TREE_TYPE (t) = NULL_TREE;
4699 SET_TYPE_STRUCTURAL_EQUALITY (t);
4701 /* Build the corresponding TEMPLATE_DECL. */
4702 tree d = build_decl (input_location, TEMPLATE_DECL, name, t);
4703 TYPE_NAME (t) = d;
4704 TYPE_STUB_DECL (t) = d;
4705 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
4706 DECL_ARTIFICIAL (d) = 1;
4707 DECL_TEMPLATE_PARMS (d) = parm_list;
4709 return t;
4714 /* Push the declarations of builtin types into the global namespace.
4715 RID_INDEX is the index of the builtin type in the array
4716 RID_POINTERS. NAME is the name used when looking up the builtin
4717 type. TYPE is the _TYPE node for the builtin type.
4719 The calls to set_global_binding below should be
4720 eliminated. Built-in types should not be looked up name; their
4721 names are keywords that the parser can recognize. However, there
4722 is code in c-common.cc that uses identifier_global_value to look up
4723 built-in types by name. */
4725 void
4726 record_builtin_type (enum rid rid_index,
4727 const char* name,
4728 tree type)
4730 tree decl = NULL_TREE;
4732 if (name)
4734 tree tname = get_identifier (name);
4735 tree tdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, tname, type);
4736 DECL_ARTIFICIAL (tdecl) = 1;
4737 set_global_binding (tdecl);
4738 decl = tdecl;
4741 if ((int) rid_index < (int) RID_MAX)
4742 if (tree rname = ridpointers[(int) rid_index])
4743 if (!decl || DECL_NAME (decl) != rname)
4745 tree rdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, rname, type);
4746 DECL_ARTIFICIAL (rdecl) = 1;
4747 set_global_binding (rdecl);
4748 if (!decl)
4749 decl = rdecl;
4752 if (decl)
4754 if (!TYPE_NAME (type))
4755 TYPE_NAME (type) = decl;
4756 debug_hooks->type_decl (decl, 0);
4760 /* Push a type into the namespace so that the back ends ignore it. */
4762 static void
4763 record_unknown_type (tree type, const char* name)
4765 tree decl = pushdecl (build_decl (UNKNOWN_LOCATION,
4766 TYPE_DECL, get_identifier (name), type));
4767 /* Make sure the "unknown type" typedecl gets ignored for debug info. */
4768 DECL_IGNORED_P (decl) = 1;
4769 TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
4770 TYPE_SIZE (type) = TYPE_SIZE (void_type_node);
4771 SET_TYPE_ALIGN (type, 1);
4772 TYPE_USER_ALIGN (type) = 0;
4773 SET_TYPE_MODE (type, TYPE_MODE (void_type_node));
4776 /* Create all the predefined identifiers. */
4778 static void
4779 initialize_predefined_identifiers (void)
4781 struct predefined_identifier
4783 const char *name; /* Name. */
4784 tree *node; /* Node to store it in. */
4785 cp_identifier_kind kind; /* Kind of identifier. */
4788 /* A table of identifiers to create at startup. */
4789 static const predefined_identifier predefined_identifiers[] = {
4790 {"C++", &lang_name_cplusplus, cik_normal},
4791 {"C", &lang_name_c, cik_normal},
4792 /* Some of these names have a trailing space so that it is
4793 impossible for them to conflict with names written by users. */
4794 {"__ct ", &ctor_identifier, cik_ctor},
4795 {"__ct_base ", &base_ctor_identifier, cik_ctor},
4796 {"__ct_comp ", &complete_ctor_identifier, cik_ctor},
4797 {"__dt ", &dtor_identifier, cik_dtor},
4798 {"__dt_base ", &base_dtor_identifier, cik_dtor},
4799 {"__dt_comp ", &complete_dtor_identifier, cik_dtor},
4800 {"__dt_del ", &deleting_dtor_identifier, cik_dtor},
4801 {"__conv_op ", &conv_op_identifier, cik_conv_op},
4802 {"__in_chrg", &in_charge_identifier, cik_normal},
4803 {"__as_base ", &as_base_identifier, cik_normal},
4804 {"this", &this_identifier, cik_normal},
4805 {"__delta", &delta_identifier, cik_normal},
4806 {"__pfn", &pfn_identifier, cik_normal},
4807 {"_vptr", &vptr_identifier, cik_normal},
4808 {"__vtt_parm", &vtt_parm_identifier, cik_normal},
4809 {"::", &global_identifier, cik_normal},
4810 /* The demangler expects anonymous namespaces to be called
4811 something starting with '_GLOBAL__N_'. It no longer needs
4812 to be unique to the TU. */
4813 {"_GLOBAL__N_1", &anon_identifier, cik_normal},
4814 {"auto", &auto_identifier, cik_normal},
4815 {"decltype(auto)", &decltype_auto_identifier, cik_normal},
4816 {"initializer_list", &init_list_identifier, cik_normal},
4817 {"__for_range ", &for_range__identifier, cik_normal},
4818 {"__for_begin ", &for_begin__identifier, cik_normal},
4819 {"__for_end ", &for_end__identifier, cik_normal},
4820 {"__for_range", &for_range_identifier, cik_normal},
4821 {"__for_begin", &for_begin_identifier, cik_normal},
4822 {"__for_end", &for_end_identifier, cik_normal},
4823 {"abi_tag", &abi_tag_identifier, cik_normal},
4824 {"aligned", &aligned_identifier, cik_normal},
4825 {"begin", &begin_identifier, cik_normal},
4826 {"end", &end_identifier, cik_normal},
4827 {"get", &get__identifier, cik_normal},
4828 {"gnu", &gnu_identifier, cik_normal},
4829 {"tuple_element", &tuple_element_identifier, cik_normal},
4830 {"tuple_size", &tuple_size_identifier, cik_normal},
4831 {"type", &type_identifier, cik_normal},
4832 {"value", &value_identifier, cik_normal},
4833 {"_FUN", &fun_identifier, cik_normal},
4834 {"__closure", &closure_identifier, cik_normal},
4835 {"heap uninit", &heap_uninit_identifier, cik_normal},
4836 {"heap ", &heap_identifier, cik_normal},
4837 {"heap deleted", &heap_deleted_identifier, cik_normal},
4838 {"heap [] uninit", &heap_vec_uninit_identifier, cik_normal},
4839 {"heap []", &heap_vec_identifier, cik_normal},
4840 {"omp", &omp_identifier, cik_normal},
4841 {NULL, NULL, cik_normal}
4844 for (const predefined_identifier *pid = predefined_identifiers;
4845 pid->name; ++pid)
4847 *pid->node = get_identifier (pid->name);
4848 /* Some of these identifiers already have a special kind. */
4849 if (pid->kind != cik_normal)
4850 set_identifier_kind (*pid->node, pid->kind);
4854 /* Create the predefined scalar types of C,
4855 and some nodes representing standard constants (0, 1, (void *)0).
4856 Initialize the global binding level.
4857 Make definitions for built-in primitive functions. */
4859 void
4860 cxx_init_decl_processing (void)
4862 tree void_ftype;
4863 tree void_ftype_ptr;
4865 /* Create all the identifiers we need. */
4866 initialize_predefined_identifiers ();
4868 /* Create the global variables. */
4869 push_to_top_level ();
4871 current_function_decl = NULL_TREE;
4872 current_binding_level = NULL;
4873 /* Enter the global namespace. */
4874 gcc_assert (global_namespace == NULL_TREE);
4875 global_namespace = build_lang_decl (NAMESPACE_DECL, global_identifier,
4876 void_type_node);
4877 TREE_PUBLIC (global_namespace) = true;
4878 DECL_MODULE_EXPORT_P (global_namespace) = true;
4879 DECL_CONTEXT (global_namespace)
4880 = build_translation_unit_decl (get_identifier (main_input_filename));
4881 /* Remember whether we want the empty class passing ABI change warning
4882 in this TU. */
4883 TRANSLATION_UNIT_WARN_EMPTY_P (DECL_CONTEXT (global_namespace))
4884 = warn_abi && abi_version_crosses (12);
4885 debug_hooks->register_main_translation_unit
4886 (DECL_CONTEXT (global_namespace));
4887 begin_scope (sk_namespace, global_namespace);
4888 current_namespace = global_namespace;
4890 if (flag_visibility_ms_compat)
4891 default_visibility = VISIBILITY_HIDDEN;
4893 /* Initially, C. */
4894 current_lang_name = lang_name_c;
4896 /* Create the `std' namespace. */
4897 push_namespace (get_identifier ("std"));
4898 std_node = current_namespace;
4899 pop_namespace ();
4901 flag_noexcept_type = (cxx_dialect >= cxx17);
4903 c_common_nodes_and_builtins ();
4905 tree bool_ftype = build_function_type_list (boolean_type_node, NULL_TREE);
4906 tree decl
4907 = add_builtin_function ("__builtin_is_constant_evaluated",
4908 bool_ftype, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
4909 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4910 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4912 /* The concrete return type of __builtin_source_location is
4913 const std::source_location::__impl*, but we can't form the type
4914 at this point. So we initially declare it with an auto return
4915 type which we then "deduce" from require_deduced_type upon first use. */
4916 tree auto_ftype = build_function_type_list (make_auto (), NULL_TREE);
4917 decl = add_builtin_function ("__builtin_source_location",
4918 auto_ftype, CP_BUILT_IN_SOURCE_LOCATION,
4919 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4920 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4922 tree bool_vaftype = build_varargs_function_type_list (boolean_type_node,
4923 NULL_TREE);
4924 decl
4925 = add_builtin_function ("__builtin_is_corresponding_member",
4926 bool_vaftype,
4927 CP_BUILT_IN_IS_CORRESPONDING_MEMBER,
4928 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4929 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4931 decl
4932 = add_builtin_function ("__builtin_is_pointer_interconvertible_with_class",
4933 bool_vaftype,
4934 CP_BUILT_IN_IS_POINTER_INTERCONVERTIBLE_WITH_CLASS,
4935 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4936 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4938 integer_two_node = build_int_cst (NULL_TREE, 2);
4940 /* Guess at the initial static decls size. */
4941 vec_alloc (static_decls, 500);
4943 /* ... and keyed classes. */
4944 vec_alloc (keyed_classes, 100);
4946 record_builtin_type (RID_BOOL, "bool", boolean_type_node);
4947 truthvalue_type_node = boolean_type_node;
4948 truthvalue_false_node = boolean_false_node;
4949 truthvalue_true_node = boolean_true_node;
4951 empty_except_spec = build_tree_list (NULL_TREE, NULL_TREE);
4952 noexcept_true_spec = build_tree_list (boolean_true_node, NULL_TREE);
4953 noexcept_false_spec = build_tree_list (boolean_false_node, NULL_TREE);
4954 noexcept_deferred_spec = build_tree_list (make_node (DEFERRED_NOEXCEPT),
4955 NULL_TREE);
4957 #if 0
4958 record_builtin_type (RID_MAX, NULL, string_type_node);
4959 #endif
4961 delta_type_node = ptrdiff_type_node;
4962 vtable_index_type = ptrdiff_type_node;
4964 vtt_parm_type = build_pointer_type (const_ptr_type_node);
4965 void_ftype = build_function_type_list (void_type_node, NULL_TREE);
4966 void_ftype_ptr = build_function_type_list (void_type_node,
4967 ptr_type_node, NULL_TREE);
4968 void_ftype_ptr
4969 = build_exception_variant (void_ftype_ptr, empty_except_spec);
4971 /* Create the conversion operator marker. This operator's DECL_NAME
4972 is in the identifier table, so we can use identifier equality to
4973 find it. */
4974 conv_op_marker = build_lang_decl (FUNCTION_DECL, conv_op_identifier,
4975 void_ftype);
4977 /* C++ extensions */
4979 unknown_type_node = make_node (LANG_TYPE);
4980 record_unknown_type (unknown_type_node, "unknown type");
4982 /* Indirecting an UNKNOWN_TYPE node yields an UNKNOWN_TYPE node. */
4983 TREE_TYPE (unknown_type_node) = unknown_type_node;
4985 /* Looking up TYPE_POINTER_TO and TYPE_REFERENCE_TO yield the same
4986 result. */
4987 TYPE_POINTER_TO (unknown_type_node) = unknown_type_node;
4988 TYPE_REFERENCE_TO (unknown_type_node) = unknown_type_node;
4990 init_list_type_node = make_node (LANG_TYPE);
4991 record_unknown_type (init_list_type_node, "init list");
4993 /* Used when parsing to distinguish parameter-lists () and (void). */
4994 explicit_void_list_node = build_tree_list (NULL_TREE, void_type_node);
4997 /* Make sure we get a unique function type, so we can give
4998 its pointer type a name. (This wins for gdb.) */
4999 tree vfunc_type = make_node (FUNCTION_TYPE);
5000 TREE_TYPE (vfunc_type) = integer_type_node;
5001 TYPE_ARG_TYPES (vfunc_type) = NULL_TREE;
5002 layout_type (vfunc_type);
5004 vtable_entry_type = build_pointer_type (vfunc_type);
5006 record_builtin_type (RID_MAX, "__vtbl_ptr_type", vtable_entry_type);
5008 vtbl_type_node
5009 = build_cplus_array_type (vtable_entry_type, NULL_TREE);
5010 layout_type (vtbl_type_node);
5011 vtbl_type_node = cp_build_qualified_type (vtbl_type_node, TYPE_QUAL_CONST);
5012 record_builtin_type (RID_MAX, NULL, vtbl_type_node);
5013 vtbl_ptr_type_node = build_pointer_type (vtable_entry_type);
5014 layout_type (vtbl_ptr_type_node);
5015 record_builtin_type (RID_MAX, NULL, vtbl_ptr_type_node);
5017 push_namespace (get_identifier ("__cxxabiv1"));
5018 abi_node = current_namespace;
5019 pop_namespace ();
5021 any_targ_node = make_node (LANG_TYPE);
5022 record_unknown_type (any_targ_node, "any type");
5024 /* Now, C++. */
5025 current_lang_name = lang_name_cplusplus;
5027 if (aligned_new_threshold > 1
5028 && !pow2p_hwi (aligned_new_threshold))
5030 error ("%<-faligned-new=%d%> is not a power of two",
5031 aligned_new_threshold);
5032 aligned_new_threshold = 1;
5034 if (aligned_new_threshold == -1)
5035 aligned_new_threshold = (cxx_dialect >= cxx17) ? 1 : 0;
5036 if (aligned_new_threshold == 1)
5037 aligned_new_threshold = malloc_alignment () / BITS_PER_UNIT;
5040 tree newattrs, extvisattr;
5041 tree newtype, deltype;
5042 tree ptr_ftype_sizetype;
5043 tree new_eh_spec;
5045 ptr_ftype_sizetype
5046 = build_function_type_list (ptr_type_node, size_type_node, NULL_TREE);
5047 if (cxx_dialect == cxx98)
5049 tree bad_alloc_id;
5050 tree bad_alloc_type_node;
5051 tree bad_alloc_decl;
5053 push_nested_namespace (std_node);
5054 bad_alloc_id = get_identifier ("bad_alloc");
5055 bad_alloc_type_node = make_class_type (RECORD_TYPE);
5056 TYPE_CONTEXT (bad_alloc_type_node) = current_namespace;
5057 bad_alloc_decl
5058 = create_implicit_typedef (bad_alloc_id, bad_alloc_type_node);
5059 DECL_CONTEXT (bad_alloc_decl) = current_namespace;
5060 pop_nested_namespace (std_node);
5062 new_eh_spec
5063 = add_exception_specifier (NULL_TREE, bad_alloc_type_node, -1);
5065 else
5066 new_eh_spec = noexcept_false_spec;
5068 /* Ensure attribs.cc is initialized. */
5069 init_attributes ();
5071 extvisattr = build_tree_list (get_identifier ("externally_visible"),
5072 NULL_TREE);
5073 newattrs = tree_cons (get_identifier ("alloc_size"),
5074 build_tree_list (NULL_TREE, integer_one_node),
5075 extvisattr);
5076 newtype = cp_build_type_attribute_variant (ptr_ftype_sizetype, newattrs);
5077 newtype = build_exception_variant (newtype, new_eh_spec);
5078 deltype = cp_build_type_attribute_variant (void_ftype_ptr, extvisattr);
5079 deltype = build_exception_variant (deltype, empty_except_spec);
5080 tree opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
5081 DECL_IS_MALLOC (opnew) = 1;
5082 DECL_SET_IS_OPERATOR_NEW (opnew, true);
5083 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
5084 opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
5085 DECL_IS_MALLOC (opnew) = 1;
5086 DECL_SET_IS_OPERATOR_NEW (opnew, true);
5087 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
5088 tree opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
5089 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5090 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5091 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
5092 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5093 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5094 if (flag_sized_deallocation)
5096 /* Also push the sized deallocation variants:
5097 void operator delete(void*, std::size_t) throw();
5098 void operator delete[](void*, std::size_t) throw(); */
5099 tree void_ftype_ptr_size
5100 = build_function_type_list (void_type_node, ptr_type_node,
5101 size_type_node, NULL_TREE);
5102 deltype = cp_build_type_attribute_variant (void_ftype_ptr_size,
5103 extvisattr);
5104 deltype = build_exception_variant (deltype, empty_except_spec);
5105 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
5106 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5107 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5108 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
5109 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5110 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5113 if (aligned_new_threshold)
5115 push_nested_namespace (std_node);
5116 tree align_id = get_identifier ("align_val_t");
5117 align_type_node = start_enum (align_id, NULL_TREE, size_type_node,
5118 NULL_TREE, /*scoped*/true, NULL);
5119 pop_nested_namespace (std_node);
5121 /* operator new (size_t, align_val_t); */
5122 newtype = build_function_type_list (ptr_type_node, size_type_node,
5123 align_type_node, NULL_TREE);
5124 newtype = cp_build_type_attribute_variant (newtype, newattrs);
5125 newtype = build_exception_variant (newtype, new_eh_spec);
5126 opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
5127 DECL_IS_MALLOC (opnew) = 1;
5128 DECL_SET_IS_OPERATOR_NEW (opnew, true);
5129 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
5130 opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
5131 DECL_IS_MALLOC (opnew) = 1;
5132 DECL_SET_IS_OPERATOR_NEW (opnew, true);
5133 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
5135 /* operator delete (void *, align_val_t); */
5136 deltype = build_function_type_list (void_type_node, ptr_type_node,
5137 align_type_node, NULL_TREE);
5138 deltype = cp_build_type_attribute_variant (deltype, extvisattr);
5139 deltype = build_exception_variant (deltype, empty_except_spec);
5140 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
5141 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5142 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5143 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
5144 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5145 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5147 if (flag_sized_deallocation)
5149 /* operator delete (void *, size_t, align_val_t); */
5150 deltype = build_function_type_list (void_type_node, ptr_type_node,
5151 size_type_node, align_type_node,
5152 NULL_TREE);
5153 deltype = cp_build_type_attribute_variant (deltype, extvisattr);
5154 deltype = build_exception_variant (deltype, empty_except_spec);
5155 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
5156 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5157 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5158 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
5159 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5160 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5164 /* C++-specific nullptr initialization. */
5165 if (abi_version_at_least (9))
5166 SET_TYPE_ALIGN (nullptr_type_node, GET_MODE_ALIGNMENT (ptr_mode));
5167 record_builtin_type (RID_MAX, "decltype(nullptr)", nullptr_type_node);
5170 if (! supports_one_only ())
5171 flag_weak = 0;
5173 abort_fndecl
5174 = build_library_fn_ptr ("__cxa_pure_virtual", void_ftype,
5175 ECF_NORETURN | ECF_NOTHROW | ECF_COLD);
5176 if (flag_weak)
5177 /* If no definition is available, resolve references to NULL. */
5178 declare_weak (abort_fndecl);
5180 /* Perform other language dependent initializations. */
5181 init_class_processing ();
5182 init_rtti_processing ();
5183 init_template_processing ();
5185 if (flag_exceptions)
5186 init_exception_processing ();
5188 if (flag_contracts)
5189 init_terminate_fn ();
5191 if (modules_p ())
5192 init_modules (parse_in);
5194 make_fname_decl = cp_make_fname_decl;
5195 start_fname_decls ();
5197 /* Show we use EH for cleanups. */
5198 if (flag_exceptions)
5199 using_eh_for_cleanups ();
5201 /* Check that the hardware interference sizes are at least
5202 alignof(max_align_t), as required by the standard. */
5203 const int max_align = max_align_t_align () / BITS_PER_UNIT;
5204 if (OPTION_SET_P (param_destruct_interfere_size))
5206 if (param_destruct_interfere_size < max_align)
5207 error ("%<--param destructive-interference-size=%d%> is less than "
5208 "%d", param_destruct_interfere_size, max_align);
5209 else if (param_destruct_interfere_size < param_l1_cache_line_size)
5210 warning (OPT_Winterference_size,
5211 "%<--param destructive-interference-size=%d%> "
5212 "is less than %<--param l1-cache-line-size=%d%>",
5213 param_destruct_interfere_size, param_l1_cache_line_size);
5215 else if (param_destruct_interfere_size)
5216 /* Assume the internal value is OK. */;
5217 else if (param_l1_cache_line_size >= max_align)
5218 param_destruct_interfere_size = param_l1_cache_line_size;
5219 /* else leave it unset. */
5221 if (OPTION_SET_P (param_construct_interfere_size))
5223 if (param_construct_interfere_size < max_align)
5224 error ("%<--param constructive-interference-size=%d%> is less than "
5225 "%d", param_construct_interfere_size, max_align);
5226 else if (param_construct_interfere_size > param_l1_cache_line_size
5227 && param_l1_cache_line_size >= max_align)
5228 warning (OPT_Winterference_size,
5229 "%<--param constructive-interference-size=%d%> "
5230 "is greater than %<--param l1-cache-line-size=%d%>",
5231 param_construct_interfere_size, param_l1_cache_line_size);
5233 else if (param_construct_interfere_size)
5234 /* Assume the internal value is OK. */;
5235 else if (param_l1_cache_line_size >= max_align)
5236 param_construct_interfere_size = param_l1_cache_line_size;
5239 /* Enter an abi node in global-module context. returns a cookie to
5240 give to pop_abi_namespace. */
5242 unsigned
5243 push_abi_namespace (tree node)
5245 push_nested_namespace (node);
5246 push_visibility ("default", 2);
5247 unsigned flags = module_kind;
5248 module_kind = 0;
5249 return flags;
5252 /* Pop an abi namespace, FLAGS is the cookie push_abi_namespace gave
5253 you. */
5255 void
5256 pop_abi_namespace (unsigned flags, tree node)
5258 module_kind = flags;
5259 pop_visibility (2);
5260 pop_nested_namespace (node);
5263 /* Create the VAR_DECL for __FUNCTION__ etc. ID is the name to give
5264 the decl, LOC is the location to give the decl, NAME is the
5265 initialization string and TYPE_DEP indicates whether NAME depended
5266 on the type of the function. We make use of that to detect
5267 __PRETTY_FUNCTION__ inside a template fn. This is being done lazily
5268 at the point of first use, so we mustn't push the decl now. */
5270 static tree
5271 cp_make_fname_decl (location_t loc, tree id, int type_dep)
5273 tree domain = NULL_TREE;
5274 tree init = NULL_TREE;
5276 if (!(type_dep && current_function_decl && in_template_context))
5278 const char *name = NULL;
5279 bool release_name = false;
5281 if (current_function_decl == NULL_TREE)
5282 name = "top level";
5283 else if (type_dep == 0)
5285 /* __FUNCTION__ */
5286 name = fname_as_string (type_dep);
5287 release_name = true;
5289 else
5291 /* __PRETTY_FUNCTION__ */
5292 gcc_checking_assert (type_dep == 1);
5293 name = cxx_printable_name (current_function_decl, 2);
5296 size_t length = strlen (name);
5297 domain = build_index_type (size_int (length));
5298 init = build_string (length + 1, name);
5299 if (release_name)
5300 free (const_cast<char *> (name));
5303 tree type = cp_build_qualified_type (char_type_node, TYPE_QUAL_CONST);
5304 type = build_cplus_array_type (type, domain);
5306 if (init)
5307 TREE_TYPE (init) = type;
5308 else
5309 init = error_mark_node;
5311 tree decl = build_decl (loc, VAR_DECL, id, type);
5313 TREE_READONLY (decl) = 1;
5314 DECL_ARTIFICIAL (decl) = 1;
5315 DECL_DECLARED_CONSTEXPR_P (decl) = 1;
5316 TREE_STATIC (decl) = 1;
5318 TREE_USED (decl) = 1;
5320 SET_DECL_VALUE_EXPR (decl, init);
5321 DECL_HAS_VALUE_EXPR_P (decl) = 1;
5322 /* For decl_constant_var_p. */
5323 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
5325 if (current_function_decl)
5327 DECL_CONTEXT (decl) = current_function_decl;
5328 decl = pushdecl_outermost_localscope (decl);
5329 if (decl != error_mark_node)
5330 add_decl_expr (decl);
5332 else
5334 DECL_THIS_STATIC (decl) = true;
5335 decl = pushdecl_top_level_and_finish (decl, NULL_TREE);
5338 return decl;
5341 /* Install DECL as a builtin function at current global scope. Return
5342 the new decl (if we found an existing version). Also installs it
5343 into ::std, if it's not '_*'. */
5345 tree
5346 cxx_builtin_function (tree decl)
5348 retrofit_lang_decl (decl);
5350 DECL_ARTIFICIAL (decl) = 1;
5351 SET_DECL_LANGUAGE (decl, lang_c);
5352 /* Runtime library routines are, by definition, available in an
5353 external shared object. */
5354 DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
5355 DECL_VISIBILITY_SPECIFIED (decl) = 1;
5357 tree id = DECL_NAME (decl);
5358 const char *name = IDENTIFIER_POINTER (id);
5359 bool hiding = false;
5360 if (name[0] != '_' || name[1] != '_')
5361 /* In the user's namespace, it must be declared before use. */
5362 hiding = true;
5363 else if (IDENTIFIER_LENGTH (id) > strlen ("___chk")
5364 && !startswith (name + 2, "builtin_")
5365 && 0 == memcmp (name + IDENTIFIER_LENGTH (id) - strlen ("_chk"),
5366 "_chk", strlen ("_chk") + 1))
5367 /* Treat __*_chk fortification functions as anticipated as well,
5368 unless they are __builtin_*_chk. */
5369 hiding = true;
5371 /* All builtins that don't begin with an '_' should additionally
5372 go in the 'std' namespace. */
5373 if (name[0] != '_')
5375 tree std_decl = copy_decl (decl);
5377 push_nested_namespace (std_node);
5378 DECL_CONTEXT (std_decl) = FROB_CONTEXT (std_node);
5379 pushdecl (std_decl, hiding);
5380 pop_nested_namespace (std_node);
5383 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5384 decl = pushdecl (decl, hiding);
5386 return decl;
5389 /* Like cxx_builtin_function, but guarantee the function is added to the global
5390 scope. This is to allow function specific options to add new machine
5391 dependent builtins when the target ISA changes via attribute((target(...)))
5392 which saves space on program startup if the program does not use non-generic
5393 ISAs. */
5395 tree
5396 cxx_builtin_function_ext_scope (tree decl)
5398 push_nested_namespace (global_namespace);
5399 decl = cxx_builtin_function (decl);
5400 pop_nested_namespace (global_namespace);
5402 return decl;
5405 /* Implement LANG_HOOKS_SIMULATE_BUILTIN_FUNCTION_DECL. */
5407 tree
5408 cxx_simulate_builtin_function_decl (tree decl)
5410 retrofit_lang_decl (decl);
5412 DECL_ARTIFICIAL (decl) = 1;
5413 SET_DECL_LANGUAGE (decl, lang_cplusplus);
5414 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5415 return pushdecl (decl);
5418 /* Generate a FUNCTION_DECL with the typical flags for a runtime library
5419 function. Not called directly. */
5421 static tree
5422 build_library_fn (tree name, enum tree_code operator_code, tree type,
5423 int ecf_flags)
5425 tree fn = build_lang_decl (FUNCTION_DECL, name, type);
5426 DECL_EXTERNAL (fn) = 1;
5427 TREE_PUBLIC (fn) = 1;
5428 DECL_ARTIFICIAL (fn) = 1;
5429 DECL_OVERLOADED_OPERATOR_CODE_RAW (fn)
5430 = OVL_OP_INFO (false, operator_code)->ovl_op_code;
5431 SET_DECL_LANGUAGE (fn, lang_c);
5432 /* Runtime library routines are, by definition, available in an
5433 external shared object. */
5434 DECL_VISIBILITY (fn) = VISIBILITY_DEFAULT;
5435 DECL_VISIBILITY_SPECIFIED (fn) = 1;
5436 set_call_expr_flags (fn, ecf_flags);
5437 return fn;
5440 /* Returns the _DECL for a library function with C++ linkage. */
5442 static tree
5443 build_cp_library_fn (tree name, enum tree_code operator_code, tree type,
5444 int ecf_flags)
5446 tree fn = build_library_fn (name, operator_code, type, ecf_flags);
5447 DECL_CONTEXT (fn) = FROB_CONTEXT (current_namespace);
5448 SET_DECL_LANGUAGE (fn, lang_cplusplus);
5449 return fn;
5452 /* Like build_library_fn, but takes a C string instead of an
5453 IDENTIFIER_NODE. */
5455 tree
5456 build_library_fn_ptr (const char* name, tree type, int ecf_flags)
5458 return build_library_fn (get_identifier (name), ERROR_MARK, type, ecf_flags);
5461 /* Like build_cp_library_fn, but takes a C string instead of an
5462 IDENTIFIER_NODE. */
5464 tree
5465 build_cp_library_fn_ptr (const char* name, tree type, int ecf_flags)
5467 return build_cp_library_fn (get_identifier (name), ERROR_MARK, type,
5468 ecf_flags);
5471 /* Like build_library_fn, but also pushes the function so that we will
5472 be able to find it via get_global_binding. Also, the function
5473 may throw exceptions listed in RAISES. */
5475 tree
5476 push_library_fn (tree name, tree type, tree raises, int ecf_flags)
5478 if (raises)
5479 type = build_exception_variant (type, raises);
5481 tree fn = build_library_fn (name, ERROR_MARK, type, ecf_flags);
5482 return pushdecl_top_level (fn);
5485 /* Like build_cp_library_fn, but also pushes the function so that it
5486 will be found by normal lookup. */
5488 static tree
5489 push_cp_library_fn (enum tree_code operator_code, tree type,
5490 int ecf_flags)
5492 tree fn = build_cp_library_fn (ovl_op_identifier (false, operator_code),
5493 operator_code, type, ecf_flags);
5494 pushdecl (fn);
5495 if (flag_tm)
5496 apply_tm_attr (fn, get_identifier ("transaction_safe"));
5497 return fn;
5500 /* Like push_library_fn, but also note that this function throws
5501 and does not return. Used for __throw_foo and the like. */
5503 tree
5504 push_throw_library_fn (tree name, tree type)
5506 tree fn = push_library_fn (name, type, NULL_TREE,
5507 ECF_NORETURN | ECF_XTHROW | ECF_COLD);
5508 return fn;
5511 /* When we call finish_struct for an anonymous union, we create
5512 default copy constructors and such. But, an anonymous union
5513 shouldn't have such things; this function undoes the damage to the
5514 anonymous union type T.
5516 (The reason that we create the synthesized methods is that we don't
5517 distinguish `union { int i; }' from `typedef union { int i; } U'.
5518 The first is an anonymous union; the second is just an ordinary
5519 union type.) */
5521 void
5522 fixup_anonymous_aggr (tree t)
5524 /* Wipe out memory of synthesized methods. */
5525 TYPE_HAS_USER_CONSTRUCTOR (t) = 0;
5526 TYPE_HAS_DEFAULT_CONSTRUCTOR (t) = 0;
5527 TYPE_HAS_COPY_CTOR (t) = 0;
5528 TYPE_HAS_CONST_COPY_CTOR (t) = 0;
5529 TYPE_HAS_COPY_ASSIGN (t) = 0;
5530 TYPE_HAS_CONST_COPY_ASSIGN (t) = 0;
5532 /* Splice the implicitly generated functions out of TYPE_FIELDS and diagnose
5533 invalid members. */
5534 for (tree probe, *prev_p = &TYPE_FIELDS (t); (probe = *prev_p);)
5536 if (TREE_CODE (probe) == FUNCTION_DECL && DECL_ARTIFICIAL (probe))
5537 *prev_p = DECL_CHAIN (probe);
5538 else
5539 prev_p = &DECL_CHAIN (probe);
5541 if (DECL_ARTIFICIAL (probe)
5542 && (!DECL_IMPLICIT_TYPEDEF_P (probe)
5543 || TYPE_ANON_P (TREE_TYPE (probe))))
5544 continue;
5546 if (TREE_CODE (probe) != FIELD_DECL
5547 || (TREE_PRIVATE (probe) || TREE_PROTECTED (probe)))
5549 /* We already complained about static data members in
5550 finish_static_data_member_decl. */
5551 if (!VAR_P (probe))
5553 auto_diagnostic_group d;
5554 if (permerror (DECL_SOURCE_LOCATION (probe),
5555 TREE_CODE (t) == UNION_TYPE
5556 ? "%q#D invalid; an anonymous union may "
5557 "only have public non-static data members"
5558 : "%q#D invalid; an anonymous struct may "
5559 "only have public non-static data members", probe))
5561 static bool hint;
5562 if (flag_permissive && !hint)
5564 hint = true;
5565 inform (DECL_SOURCE_LOCATION (probe),
5566 "this flexibility is deprecated and will be "
5567 "removed");
5574 /* Splice all functions out of CLASSTYPE_MEMBER_VEC. */
5575 vec<tree,va_gc>* vec = CLASSTYPE_MEMBER_VEC (t);
5576 unsigned store = 0;
5577 for (tree elt : vec)
5578 if (!is_overloaded_fn (elt))
5579 (*vec)[store++] = elt;
5580 vec_safe_truncate (vec, store);
5582 /* Wipe RTTI info. */
5583 CLASSTYPE_TYPEINFO_VAR (t) = NULL_TREE;
5585 /* Anonymous aggregates cannot have fields with ctors, dtors or complex
5586 assignment operators (because they cannot have these methods themselves).
5587 For anonymous unions this is already checked because they are not allowed
5588 in any union, otherwise we have to check it. */
5589 if (TREE_CODE (t) != UNION_TYPE)
5591 tree field, type;
5593 if (BINFO_N_BASE_BINFOS (TYPE_BINFO (t)))
5595 error_at (location_of (t), "anonymous struct with base classes");
5596 /* Avoid ICE after error on anon-struct9.C. */
5597 TYPE_NEEDS_CONSTRUCTING (t) = false;
5600 for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
5601 if (TREE_CODE (field) == FIELD_DECL)
5603 type = TREE_TYPE (field);
5604 if (CLASS_TYPE_P (type))
5606 if (TYPE_NEEDS_CONSTRUCTING (type))
5607 error ("member %q+#D with constructor not allowed "
5608 "in anonymous aggregate", field);
5609 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
5610 error ("member %q+#D with destructor not allowed "
5611 "in anonymous aggregate", field);
5612 if (TYPE_HAS_COMPLEX_COPY_ASSIGN (type))
5613 error ("member %q+#D with copy assignment operator "
5614 "not allowed in anonymous aggregate", field);
5620 /* Warn for an attribute located at LOCATION that appertains to the
5621 class type CLASS_TYPE that has not been properly placed after its
5622 class-key, in it class-specifier. */
5624 void
5625 warn_misplaced_attr_for_class_type (location_t location,
5626 tree class_type)
5628 gcc_assert (OVERLOAD_TYPE_P (class_type));
5630 auto_diagnostic_group d;
5631 if (warning_at (location, OPT_Wattributes,
5632 "attribute ignored in declaration "
5633 "of %q#T", class_type))
5634 inform (location,
5635 "attribute for %q#T must follow the %qs keyword",
5636 class_type, class_key_or_enum_as_string (class_type));
5639 /* Returns the cv-qualifiers that apply to the type specified
5640 by the DECLSPECS. */
5642 static int
5643 get_type_quals (const cp_decl_specifier_seq *declspecs)
5645 int type_quals = TYPE_UNQUALIFIED;
5647 if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5648 type_quals |= TYPE_QUAL_CONST;
5649 if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5650 type_quals |= TYPE_QUAL_VOLATILE;
5651 if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5652 type_quals |= TYPE_QUAL_RESTRICT;
5654 return type_quals;
5657 /* Make sure that a declaration with no declarator is well-formed, i.e.
5658 just declares a tagged type or anonymous union.
5660 Returns the type declared; or NULL_TREE if none. */
5662 tree
5663 check_tag_decl (cp_decl_specifier_seq *declspecs,
5664 bool explicit_type_instantiation_p)
5666 int saw_friend = decl_spec_seq_has_spec_p (declspecs, ds_friend);
5667 int saw_typedef = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
5668 /* If a class, struct, or enum type is declared by the DECLSPECS
5669 (i.e, if a class-specifier, enum-specifier, or non-typename
5670 elaborated-type-specifier appears in the DECLSPECS),
5671 DECLARED_TYPE is set to the corresponding type. */
5672 tree declared_type = NULL_TREE;
5673 bool error_p = false;
5675 if (declspecs->multiple_types_p)
5676 error_at (smallest_type_location (declspecs),
5677 "multiple types in one declaration");
5678 else if (declspecs->redefined_builtin_type)
5680 location_t loc = declspecs->locations[ds_redefined_builtin_type_spec];
5681 if (!in_system_header_at (loc))
5682 permerror (loc, "redeclaration of C++ built-in type %qT",
5683 declspecs->redefined_builtin_type);
5684 return NULL_TREE;
5687 if (declspecs->type
5688 && TYPE_P (declspecs->type)
5689 && ((TREE_CODE (declspecs->type) != TYPENAME_TYPE
5690 && MAYBE_CLASS_TYPE_P (declspecs->type))
5691 || TREE_CODE (declspecs->type) == ENUMERAL_TYPE))
5692 declared_type = declspecs->type;
5693 else if (declspecs->type == error_mark_node)
5694 error_p = true;
5696 if (type_uses_auto (declared_type))
5698 error_at (declspecs->locations[ds_type_spec],
5699 "%<auto%> can only be specified for variables "
5700 "or function declarations");
5701 return error_mark_node;
5704 if (declared_type && !OVERLOAD_TYPE_P (declared_type))
5705 declared_type = NULL_TREE;
5707 if (!declared_type && !saw_friend && !error_p)
5708 permerror (input_location, "declaration does not declare anything");
5709 /* Check for an anonymous union. */
5710 else if (declared_type && RECORD_OR_UNION_CODE_P (TREE_CODE (declared_type))
5711 && TYPE_UNNAMED_P (declared_type))
5713 /* 7/3 In a simple-declaration, the optional init-declarator-list
5714 can be omitted only when declaring a class (clause 9) or
5715 enumeration (7.2), that is, when the decl-specifier-seq contains
5716 either a class-specifier, an elaborated-type-specifier with
5717 a class-key (9.1), or an enum-specifier. In these cases and
5718 whenever a class-specifier or enum-specifier is present in the
5719 decl-specifier-seq, the identifiers in these specifiers are among
5720 the names being declared by the declaration (as class-name,
5721 enum-names, or enumerators, depending on the syntax). In such
5722 cases, and except for the declaration of an unnamed bit-field (9.6),
5723 the decl-specifier-seq shall introduce one or more names into the
5724 program, or shall redeclare a name introduced by a previous
5725 declaration. [Example:
5726 enum { }; // ill-formed
5727 typedef class { }; // ill-formed
5728 --end example] */
5729 if (saw_typedef)
5731 error_at (declspecs->locations[ds_typedef],
5732 "missing type-name in typedef-declaration");
5733 return NULL_TREE;
5735 /* Anonymous unions are objects, so they can have specifiers. */;
5736 SET_ANON_AGGR_TYPE_P (declared_type);
5738 if (TREE_CODE (declared_type) != UNION_TYPE)
5739 pedwarn (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (declared_type)),
5740 OPT_Wpedantic, "ISO C++ prohibits anonymous structs");
5743 else
5745 if (decl_spec_seq_has_spec_p (declspecs, ds_inline))
5746 error_at (declspecs->locations[ds_inline],
5747 "%<inline%> can only be specified for functions");
5748 else if (decl_spec_seq_has_spec_p (declspecs, ds_virtual))
5749 error_at (declspecs->locations[ds_virtual],
5750 "%<virtual%> can only be specified for functions");
5751 else if (saw_friend
5752 && (!current_class_type
5753 || current_scope () != current_class_type))
5754 error_at (declspecs->locations[ds_friend],
5755 "%<friend%> can only be specified inside a class");
5756 else if (decl_spec_seq_has_spec_p (declspecs, ds_explicit))
5757 error_at (declspecs->locations[ds_explicit],
5758 "%<explicit%> can only be specified for constructors");
5759 else if (declspecs->storage_class)
5760 error_at (declspecs->locations[ds_storage_class],
5761 "a storage class can only be specified for objects "
5762 "and functions");
5763 else if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5764 error_at (declspecs->locations[ds_const],
5765 "%<const%> can only be specified for objects and "
5766 "functions");
5767 else if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5768 error_at (declspecs->locations[ds_volatile],
5769 "%<volatile%> can only be specified for objects and "
5770 "functions");
5771 else if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5772 error_at (declspecs->locations[ds_restrict],
5773 "%<__restrict%> can only be specified for objects and "
5774 "functions");
5775 else if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
5776 error_at (declspecs->locations[ds_thread],
5777 "%<__thread%> can only be specified for objects "
5778 "and functions");
5779 else if (saw_typedef)
5780 warning_at (declspecs->locations[ds_typedef], 0,
5781 "%<typedef%> was ignored in this declaration");
5782 else if (decl_spec_seq_has_spec_p (declspecs, ds_constexpr))
5783 error_at (declspecs->locations[ds_constexpr],
5784 "%qs cannot be used for type declarations", "constexpr");
5785 else if (decl_spec_seq_has_spec_p (declspecs, ds_constinit))
5786 error_at (declspecs->locations[ds_constinit],
5787 "%qs cannot be used for type declarations", "constinit");
5788 else if (decl_spec_seq_has_spec_p (declspecs, ds_consteval))
5789 error_at (declspecs->locations[ds_consteval],
5790 "%qs cannot be used for type declarations", "consteval");
5793 if (declspecs->attributes && warn_attributes && declared_type)
5795 location_t loc;
5796 if (!CLASS_TYPE_P (declared_type)
5797 || !CLASSTYPE_TEMPLATE_INSTANTIATION (declared_type))
5798 /* For a non-template class, use the name location. */
5799 loc = location_of (declared_type);
5800 else
5801 /* For a template class (an explicit instantiation), use the
5802 current location. */
5803 loc = input_location;
5805 if (explicit_type_instantiation_p)
5806 /* [dcl.attr.grammar]/4:
5808 No attribute-specifier-seq shall appertain to an explicit
5809 instantiation. */
5811 auto_diagnostic_group d;
5812 if (warning_at (loc, OPT_Wattributes,
5813 "attribute ignored in explicit instantiation %q#T",
5814 declared_type))
5815 inform (loc,
5816 "no attribute can be applied to "
5817 "an explicit instantiation");
5819 else
5820 warn_misplaced_attr_for_class_type (loc, declared_type);
5823 /* Diagnose invalid application of contracts, if any. */
5824 if (find_contract (declspecs->attributes))
5825 diagnose_misapplied_contracts (declspecs->attributes);
5826 else
5827 diagnose_misapplied_contracts (declspecs->std_attributes);
5829 return declared_type;
5832 /* Called when a declaration is seen that contains no names to declare.
5833 If its type is a reference to a structure, union or enum inherited
5834 from a containing scope, shadow that tag name for the current scope
5835 with a forward reference.
5836 If its type defines a new named structure or union
5837 or defines an enum, it is valid but we need not do anything here.
5838 Otherwise, it is an error.
5840 C++: may have to grok the declspecs to learn about static,
5841 complain for anonymous unions.
5843 Returns the TYPE declared -- or NULL_TREE if none. */
5845 tree
5846 shadow_tag (cp_decl_specifier_seq *declspecs)
5848 tree t = check_tag_decl (declspecs,
5849 /*explicit_type_instantiation_p=*/false);
5851 if (!t)
5852 return NULL_TREE;
5854 t = maybe_process_partial_specialization (t);
5855 if (t == error_mark_node)
5856 return NULL_TREE;
5858 /* This is where the variables in an anonymous union are
5859 declared. An anonymous union declaration looks like:
5860 union { ... } ;
5861 because there is no declarator after the union, the parser
5862 sends that declaration here. */
5863 if (ANON_AGGR_TYPE_P (t))
5865 fixup_anonymous_aggr (t);
5867 if (TYPE_FIELDS (t))
5869 tree decl = grokdeclarator (/*declarator=*/NULL,
5870 declspecs, NORMAL, 0, NULL);
5871 finish_anon_union (decl);
5875 return t;
5878 /* Decode a "typename", such as "int **", returning a ..._TYPE node. */
5880 tree
5881 groktypename (cp_decl_specifier_seq *type_specifiers,
5882 const cp_declarator *declarator,
5883 bool is_template_arg)
5885 tree attrs;
5886 tree type;
5887 enum decl_context context
5888 = is_template_arg ? TEMPLATE_TYPE_ARG : TYPENAME;
5889 attrs = type_specifiers->attributes;
5890 type_specifiers->attributes = NULL_TREE;
5891 type = grokdeclarator (declarator, type_specifiers, context, 0, &attrs);
5892 if (attrs && type != error_mark_node)
5894 if (CLASS_TYPE_P (type))
5895 warning (OPT_Wattributes, "ignoring attributes applied to class type %qT "
5896 "outside of definition", type);
5897 else if (MAYBE_CLASS_TYPE_P (type))
5898 /* A template type parameter or other dependent type. */
5899 warning (OPT_Wattributes, "ignoring attributes applied to dependent "
5900 "type %qT without an associated declaration", type);
5901 else
5902 cplus_decl_attributes (&type, attrs, 0);
5904 return type;
5907 /* Process a DECLARATOR for a function-scope or namespace-scope
5908 variable or function declaration.
5909 (Function definitions go through start_function; class member
5910 declarations appearing in the body of the class go through
5911 grokfield.) The DECL corresponding to the DECLARATOR is returned.
5912 If an error occurs, the error_mark_node is returned instead.
5914 DECLSPECS are the decl-specifiers for the declaration. INITIALIZED is
5915 SD_INITIALIZED if an explicit initializer is present, or SD_DEFAULTED
5916 for an explicitly defaulted function, or SD_DELETED for an explicitly
5917 deleted function, but 0 (SD_UNINITIALIZED) if this is a variable
5918 implicitly initialized via a default constructor. It can also be
5919 SD_DECOMPOSITION which behaves much like SD_INITIALIZED, but we also
5920 mark the new decl as DECL_DECOMPOSITION_P.
5922 ATTRIBUTES and PREFIX_ATTRIBUTES are GNU attributes associated with this
5923 declaration.
5925 The scope represented by the context of the returned DECL is pushed
5926 (if it is not the global namespace) and is assigned to
5927 *PUSHED_SCOPE_P. The caller is then responsible for calling
5928 pop_scope on *PUSHED_SCOPE_P if it is set. */
5930 tree
5931 start_decl (const cp_declarator *declarator,
5932 cp_decl_specifier_seq *declspecs,
5933 int initialized,
5934 tree attributes,
5935 tree prefix_attributes,
5936 tree *pushed_scope_p)
5938 tree decl;
5939 tree context;
5940 bool was_public;
5941 int flags;
5942 bool alias;
5943 tree initial;
5945 *pushed_scope_p = NULL_TREE;
5947 if (prefix_attributes != error_mark_node)
5948 attributes = attr_chainon (attributes, prefix_attributes);
5950 decl = grokdeclarator (declarator, declspecs, NORMAL, initialized,
5951 &attributes);
5953 if (decl == NULL_TREE || VOID_TYPE_P (decl)
5954 || decl == error_mark_node
5955 || prefix_attributes == error_mark_node)
5956 return error_mark_node;
5958 context = CP_DECL_CONTEXT (decl);
5959 if (context != global_namespace)
5960 *pushed_scope_p = push_scope (context);
5962 if (initialized && TREE_CODE (decl) == TYPE_DECL)
5964 error_at (DECL_SOURCE_LOCATION (decl),
5965 "typedef %qD is initialized (use %qs instead)",
5966 decl, "decltype");
5967 return error_mark_node;
5970 /* Save the DECL_INITIAL value in case it gets clobbered to assist
5971 with attribute validation. */
5972 initial = DECL_INITIAL (decl);
5974 if (initialized)
5976 if (! toplevel_bindings_p ()
5977 && DECL_EXTERNAL (decl))
5978 warning (0, "declaration of %q#D has %<extern%> and is initialized",
5979 decl);
5980 DECL_EXTERNAL (decl) = 0;
5981 if (toplevel_bindings_p ())
5982 TREE_STATIC (decl) = 1;
5983 /* Tell 'cplus_decl_attributes' this is an initialized decl,
5984 even though we might not yet have the initializer expression. */
5985 if (!DECL_INITIAL (decl))
5986 DECL_INITIAL (decl) = error_mark_node;
5988 alias = lookup_attribute ("alias", DECL_ATTRIBUTES (decl)) != 0;
5990 if (alias && TREE_CODE (decl) == FUNCTION_DECL)
5991 record_key_method_defined (decl);
5993 /* If this is a typedef that names the class for linkage purposes
5994 (7.1.3p8), apply any attributes directly to the type. */
5995 if (TREE_CODE (decl) == TYPE_DECL
5996 && OVERLOAD_TYPE_P (TREE_TYPE (decl))
5997 && decl == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (decl))))
5998 flags = ATTR_FLAG_TYPE_IN_PLACE;
5999 else
6000 flags = 0;
6002 /* Set attributes here so if duplicate decl, will have proper attributes. */
6003 cplus_decl_attributes (&decl, attributes, flags);
6005 /* Restore the original DECL_INITIAL that we may have clobbered earlier to
6006 assist with attribute validation. */
6007 DECL_INITIAL (decl) = initial;
6009 /* Dllimported symbols cannot be defined. Static data members (which
6010 can be initialized in-class and dllimported) go through grokfield,
6011 not here, so we don't need to exclude those decls when checking for
6012 a definition. */
6013 if (initialized && DECL_DLLIMPORT_P (decl))
6015 error_at (DECL_SOURCE_LOCATION (decl),
6016 "definition of %q#D is marked %<dllimport%>", decl);
6017 DECL_DLLIMPORT_P (decl) = 0;
6020 /* If #pragma weak was used, mark the decl weak now. */
6021 if (!processing_template_decl && !DECL_DECOMPOSITION_P (decl))
6022 maybe_apply_pragma_weak (decl);
6024 if (TREE_CODE (decl) == FUNCTION_DECL
6025 && DECL_DECLARED_INLINE_P (decl)
6026 && DECL_UNINLINABLE (decl)
6027 && lookup_attribute ("noinline", DECL_ATTRIBUTES (decl)))
6028 warning_at (DECL_SOURCE_LOCATION (decl), 0,
6029 "inline function %qD given attribute %qs", decl, "noinline");
6031 if (TYPE_P (context) && COMPLETE_TYPE_P (complete_type (context)))
6033 bool this_tmpl = (current_template_depth
6034 > template_class_depth (context));
6035 if (VAR_P (decl))
6037 tree field = lookup_field (context, DECL_NAME (decl), 0, false);
6038 if (field == NULL_TREE
6039 || !(VAR_P (field) || variable_template_p (field)))
6040 error ("%q+#D is not a static data member of %q#T", decl, context);
6041 else if (variable_template_p (field)
6042 && (DECL_LANG_SPECIFIC (decl)
6043 && DECL_TEMPLATE_SPECIALIZATION (decl)))
6044 /* OK, specialization was already checked. */;
6045 else if (variable_template_p (field) && !this_tmpl)
6047 auto_diagnostic_group d;
6048 error_at (DECL_SOURCE_LOCATION (decl),
6049 "non-member-template declaration of %qD", decl);
6050 inform (DECL_SOURCE_LOCATION (field), "does not match "
6051 "member template declaration here");
6052 return error_mark_node;
6054 else
6056 if (variable_template_p (field))
6057 field = DECL_TEMPLATE_RESULT (field);
6059 if (DECL_CONTEXT (field) != context)
6061 if (!same_type_p (DECL_CONTEXT (field), context))
6062 permerror (input_location, "ISO C++ does not permit %<%T::%D%> "
6063 "to be defined as %<%T::%D%>",
6064 DECL_CONTEXT (field), DECL_NAME (decl),
6065 context, DECL_NAME (decl));
6066 DECL_CONTEXT (decl) = DECL_CONTEXT (field);
6068 /* Static data member are tricky; an in-class initialization
6069 still doesn't provide a definition, so the in-class
6070 declaration will have DECL_EXTERNAL set, but will have an
6071 initialization. Thus, duplicate_decls won't warn
6072 about this situation, and so we check here. */
6073 if (initialized && DECL_INITIALIZED_IN_CLASS_P (field))
6074 error ("duplicate initialization of %qD", decl);
6075 field = duplicate_decls (decl, field);
6076 if (field == error_mark_node)
6077 return error_mark_node;
6078 else if (field)
6079 decl = field;
6082 else
6084 tree field = check_classfn (context, decl,
6085 this_tmpl
6086 ? current_template_parms
6087 : NULL_TREE);
6088 if (field && field != error_mark_node
6089 && duplicate_decls (decl, field))
6090 decl = field;
6093 /* cp_finish_decl sets DECL_EXTERNAL if DECL_IN_AGGR_P is set. */
6094 DECL_IN_AGGR_P (decl) = 0;
6095 /* Do not mark DECL as an explicit specialization if it was not
6096 already marked as an instantiation; a declaration should
6097 never be marked as a specialization unless we know what
6098 template is being specialized. */
6099 if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
6101 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
6102 if (TREE_CODE (decl) == FUNCTION_DECL)
6103 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
6104 && DECL_DECLARED_INLINE_P (decl));
6105 else
6106 DECL_COMDAT (decl) = false;
6108 /* [temp.expl.spec] An explicit specialization of a static data
6109 member of a template is a definition if the declaration
6110 includes an initializer; otherwise, it is a declaration.
6112 We check for processing_specialization so this only applies
6113 to the new specialization syntax. */
6114 if (!initialized && processing_specialization)
6115 DECL_EXTERNAL (decl) = 1;
6118 if (DECL_EXTERNAL (decl) && ! DECL_TEMPLATE_SPECIALIZATION (decl)
6119 /* Aliases are definitions. */
6120 && !alias)
6122 if (DECL_VIRTUAL_P (decl) || !flag_contracts)
6123 permerror (declarator->id_loc,
6124 "declaration of %q#D outside of class is not definition",
6125 decl);
6126 else if (flag_contract_strict_declarations)
6127 warning_at (declarator->id_loc, OPT_fcontract_strict_declarations_,
6128 "declaration of %q#D outside of class is not definition",
6129 decl);
6133 /* Create a DECL_LANG_SPECIFIC so that DECL_DECOMPOSITION_P works. */
6134 if (initialized == SD_DECOMPOSITION)
6135 fit_decomposition_lang_decl (decl, NULL_TREE);
6137 was_public = TREE_PUBLIC (decl);
6139 if ((DECL_EXTERNAL (decl) || TREE_CODE (decl) == FUNCTION_DECL)
6140 && current_function_decl)
6142 /* A function-scope decl of some namespace-scope decl. */
6143 DECL_LOCAL_DECL_P (decl) = true;
6144 if (named_module_attach_p ())
6145 error_at (declarator->id_loc,
6146 "block-scope extern declaration %q#D must not be"
6147 " attached to a named module", decl);
6150 /* Enter this declaration into the symbol table. Don't push the plain
6151 VAR_DECL for a variable template. */
6152 if (!template_parm_scope_p ()
6153 || !VAR_P (decl))
6154 decl = maybe_push_decl (decl);
6156 if (processing_template_decl)
6157 decl = push_template_decl (decl);
6159 if (decl == error_mark_node)
6160 return error_mark_node;
6162 if (VAR_P (decl)
6163 && DECL_NAMESPACE_SCOPE_P (decl) && !TREE_PUBLIC (decl) && !was_public
6164 && !DECL_THIS_STATIC (decl) && !DECL_ARTIFICIAL (decl)
6165 /* But not templated variables. */
6166 && !(DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)))
6168 /* This is a const variable with implicit 'static'. Set
6169 DECL_THIS_STATIC so we can tell it from variables that are
6170 !TREE_PUBLIC because of the anonymous namespace. */
6171 gcc_assert (CP_TYPE_CONST_P (TREE_TYPE (decl)) || errorcount);
6172 DECL_THIS_STATIC (decl) = 1;
6175 if (current_function_decl && VAR_P (decl)
6176 && DECL_DECLARED_CONSTEXPR_P (current_function_decl)
6177 && cxx_dialect < cxx23)
6179 bool ok = false;
6180 if (CP_DECL_THREAD_LOCAL_P (decl) && !DECL_REALLY_EXTERN (decl))
6181 error_at (DECL_SOURCE_LOCATION (decl),
6182 "%qD defined %<thread_local%> in %qs function only "
6183 "available with %<-std=c++2b%> or %<-std=gnu++2b%>", decl,
6184 DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
6185 ? "consteval" : "constexpr");
6186 else if (TREE_STATIC (decl))
6187 error_at (DECL_SOURCE_LOCATION (decl),
6188 "%qD defined %<static%> in %qs function only available "
6189 "with %<-std=c++2b%> or %<-std=gnu++2b%>", decl,
6190 DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
6191 ? "consteval" : "constexpr");
6192 else
6193 ok = true;
6194 if (!ok)
6195 cp_function_chain->invalid_constexpr = true;
6198 if (!processing_template_decl && VAR_P (decl))
6199 start_decl_1 (decl, initialized);
6201 return decl;
6204 /* Process the declaration of a variable DECL. INITIALIZED is true
6205 iff DECL is explicitly initialized. (INITIALIZED is false if the
6206 variable is initialized via an implicitly-called constructor.)
6207 This function must be called for ordinary variables (including, for
6208 example, implicit instantiations of templates), but must not be
6209 called for template declarations. */
6211 void
6212 start_decl_1 (tree decl, bool initialized)
6214 gcc_checking_assert (!processing_template_decl);
6216 if (error_operand_p (decl))
6217 return;
6219 gcc_checking_assert (VAR_P (decl));
6221 tree type = TREE_TYPE (decl);
6222 bool complete_p = COMPLETE_TYPE_P (type);
6223 bool aggregate_definition_p
6224 = MAYBE_CLASS_TYPE_P (type) && !DECL_EXTERNAL (decl);
6226 /* If an explicit initializer is present, or if this is a definition
6227 of an aggregate, then we need a complete type at this point.
6228 (Scalars are always complete types, so there is nothing to
6229 check.) This code just sets COMPLETE_P; errors (if necessary)
6230 are issued below. */
6231 if ((initialized || aggregate_definition_p)
6232 && !complete_p
6233 && COMPLETE_TYPE_P (complete_type (type)))
6235 complete_p = true;
6236 /* We will not yet have set TREE_READONLY on DECL if the type
6237 was "const", but incomplete, before this point. But, now, we
6238 have a complete type, so we can try again. */
6239 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
6242 if (initialized)
6243 /* Is it valid for this decl to have an initializer at all? */
6245 /* Don't allow initializations for incomplete types except for
6246 arrays which might be completed by the initialization. */
6247 if (complete_p)
6248 ; /* A complete type is ok. */
6249 else if (type_uses_auto (type))
6250 ; /* An auto type is ok. */
6251 else if (TREE_CODE (type) != ARRAY_TYPE)
6253 auto_diagnostic_group d;
6254 error ("variable %q#D has initializer but incomplete type", decl);
6255 maybe_suggest_missing_header (input_location,
6256 TYPE_IDENTIFIER (type),
6257 CP_TYPE_CONTEXT (type));
6258 type = TREE_TYPE (decl) = error_mark_node;
6260 else if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (type))))
6262 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
6263 error ("elements of array %q#D have incomplete type", decl);
6264 /* else we already gave an error in start_decl. */
6267 else if (aggregate_definition_p && !complete_p)
6269 if (type_uses_auto (type))
6270 gcc_assert (CLASS_PLACEHOLDER_TEMPLATE (type));
6271 else
6273 auto_diagnostic_group d;
6274 error ("aggregate %q#D has incomplete type and cannot be defined",
6275 decl);
6276 maybe_suggest_missing_header (input_location,
6277 TYPE_IDENTIFIER (type),
6278 CP_TYPE_CONTEXT (type));
6279 /* Change the type so that assemble_variable will give
6280 DECL an rtl we can live with: (mem (const_int 0)). */
6281 type = TREE_TYPE (decl) = error_mark_node;
6285 /* Create a new scope to hold this declaration if necessary.
6286 Whether or not a new scope is necessary cannot be determined
6287 until after the type has been completed; if the type is a
6288 specialization of a class template it is not until after
6289 instantiation has occurred that TYPE_HAS_NONTRIVIAL_DESTRUCTOR
6290 will be set correctly. */
6291 maybe_push_cleanup_level (type);
6294 /* Given a parenthesized list of values INIT, create a CONSTRUCTOR to handle
6295 C++20 P0960. TYPE is the type of the object we're initializing. */
6297 tree
6298 do_aggregate_paren_init (tree init, tree type)
6300 tree val = TREE_VALUE (init);
6302 if (TREE_CHAIN (init) == NULL_TREE)
6304 /* If the list has a single element and it's a string literal,
6305 then it's the initializer for the array as a whole. */
6306 if (TREE_CODE (type) == ARRAY_TYPE
6307 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
6308 && TREE_CODE (tree_strip_any_location_wrapper (val))
6309 == STRING_CST)
6310 return val;
6311 /* Handle non-standard extensions like compound literals. This also
6312 prevents triggering aggregate parenthesized-initialization in
6313 compiler-generated code for =default. */
6314 else if (same_type_ignoring_top_level_qualifiers_p (type,
6315 TREE_TYPE (val)))
6316 return val;
6319 init = build_constructor_from_list (init_list_type_node, init);
6320 CONSTRUCTOR_IS_DIRECT_INIT (init) = true;
6321 CONSTRUCTOR_IS_PAREN_INIT (init) = true;
6322 return init;
6325 /* Handle initialization of references. DECL, TYPE, and INIT have the
6326 same meaning as in cp_finish_decl. *CLEANUP must be NULL on entry,
6327 but will be set to a new CLEANUP_STMT if a temporary is created
6328 that must be destroyed subsequently.
6330 Returns an initializer expression to use to initialize DECL, or
6331 NULL if the initialization can be performed statically.
6333 Quotes on semantics can be found in ARM 8.4.3. */
6335 static tree
6336 grok_reference_init (tree decl, tree type, tree init, int flags)
6338 if (init == NULL_TREE)
6340 if ((DECL_LANG_SPECIFIC (decl) == 0
6341 || DECL_IN_AGGR_P (decl) == 0)
6342 && ! DECL_THIS_EXTERN (decl))
6343 error_at (DECL_SOURCE_LOCATION (decl),
6344 "%qD declared as reference but not initialized", decl);
6345 return NULL_TREE;
6348 tree ttype = TREE_TYPE (type);
6349 if (TREE_CODE (init) == TREE_LIST)
6351 /* This handles (C++20 only) code like
6353 const A& r(1, 2, 3);
6355 where we treat the parenthesized list as a CONSTRUCTOR. */
6356 if (TREE_TYPE (init) == NULL_TREE
6357 && CP_AGGREGATE_TYPE_P (ttype)
6358 && !DECL_DECOMPOSITION_P (decl)
6359 && (cxx_dialect >= cxx20))
6361 /* We don't know yet if we should treat const A& r(1) as
6362 const A& r{1}. */
6363 if (list_length (init) == 1)
6365 flags |= LOOKUP_AGGREGATE_PAREN_INIT;
6366 init = build_x_compound_expr_from_list (init, ELK_INIT,
6367 tf_warning_or_error);
6369 /* If the list had more than one element, the code is ill-formed
6370 pre-C++20, so we can build a constructor right away. */
6371 else
6372 init = do_aggregate_paren_init (init, ttype);
6374 else
6375 init = build_x_compound_expr_from_list (init, ELK_INIT,
6376 tf_warning_or_error);
6379 if (TREE_CODE (ttype) != ARRAY_TYPE
6380 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
6381 /* Note: default conversion is only called in very special cases. */
6382 init = decay_conversion (init, tf_warning_or_error);
6384 /* check_initializer handles this for non-reference variables, but for
6385 references we need to do it here or the initializer will get the
6386 incomplete array type and confuse later calls to
6387 cp_complete_array_type. */
6388 if (TREE_CODE (ttype) == ARRAY_TYPE
6389 && TYPE_DOMAIN (ttype) == NULL_TREE
6390 && (BRACE_ENCLOSED_INITIALIZER_P (init)
6391 || TREE_CODE (init) == STRING_CST))
6393 cp_complete_array_type (&ttype, init, false);
6394 if (ttype != TREE_TYPE (type))
6395 type = cp_build_reference_type (ttype, TYPE_REF_IS_RVALUE (type));
6398 /* Convert INIT to the reference type TYPE. This may involve the
6399 creation of a temporary, whose lifetime must be the same as that
6400 of the reference. If so, a DECL_EXPR for the temporary will be
6401 added just after the DECL_EXPR for DECL. That's why we don't set
6402 DECL_INITIAL for local references (instead assigning to them
6403 explicitly); we need to allow the temporary to be initialized
6404 first. */
6405 return initialize_reference (type, init, flags,
6406 tf_warning_or_error);
6409 /* Designated initializers in arrays are not supported in GNU C++.
6410 The parser cannot detect this error since it does not know whether
6411 a given brace-enclosed initializer is for a class type or for an
6412 array. This function checks that CE does not use a designated
6413 initializer. If it does, an error is issued. Returns true if CE
6414 is valid, i.e., does not have a designated initializer. */
6416 bool
6417 check_array_designated_initializer (constructor_elt *ce,
6418 unsigned HOST_WIDE_INT index)
6420 /* Designated initializers for array elements are not supported. */
6421 if (ce->index)
6423 /* The parser only allows identifiers as designated
6424 initializers. */
6425 if (ce->index == error_mark_node)
6427 error ("name used in a GNU-style designated "
6428 "initializer for an array");
6429 return false;
6431 else if (identifier_p (ce->index))
6433 error ("name %qD used in a GNU-style designated "
6434 "initializer for an array", ce->index);
6435 return false;
6438 tree ce_index = build_expr_type_conversion (WANT_INT | WANT_ENUM,
6439 ce->index, true);
6440 if (ce_index
6441 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ce_index))
6442 && (TREE_CODE (ce_index = fold_non_dependent_expr (ce_index))
6443 == INTEGER_CST))
6445 /* A C99 designator is OK if it matches the current index. */
6446 if (wi::to_wide (ce_index) == index)
6448 ce->index = ce_index;
6449 return true;
6451 else
6452 sorry ("non-trivial designated initializers not supported");
6454 else
6455 error_at (cp_expr_loc_or_input_loc (ce->index),
6456 "C99 designator %qE is not an integral constant-expression",
6457 ce->index);
6459 return false;
6462 return true;
6465 /* When parsing `int a[] = {1, 2};' we don't know the size of the
6466 array until we finish parsing the initializer. If that's the
6467 situation we're in, update DECL accordingly. */
6469 static void
6470 maybe_deduce_size_from_array_init (tree decl, tree init)
6472 tree type = TREE_TYPE (decl);
6474 if (TREE_CODE (type) == ARRAY_TYPE
6475 && TYPE_DOMAIN (type) == NULL_TREE
6476 && TREE_CODE (decl) != TYPE_DECL)
6478 /* do_default is really a C-ism to deal with tentative definitions.
6479 But let's leave it here to ease the eventual merge. */
6480 int do_default = !DECL_EXTERNAL (decl);
6481 tree initializer = init ? init : DECL_INITIAL (decl);
6482 int failure = 0;
6484 /* Check that there are no designated initializers in INIT, as
6485 those are not supported in GNU C++, and as the middle-end
6486 will crash if presented with a non-numeric designated
6487 initializer. */
6488 if (initializer && BRACE_ENCLOSED_INITIALIZER_P (initializer))
6490 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initializer);
6491 constructor_elt *ce;
6492 HOST_WIDE_INT i;
6493 FOR_EACH_VEC_SAFE_ELT (v, i, ce)
6495 if (instantiation_dependent_expression_p (ce->index))
6496 return;
6497 if (!check_array_designated_initializer (ce, i))
6498 failure = 1;
6499 /* If an un-designated initializer is type-dependent, we can't
6500 check brace elision yet. */
6501 if (ce->index == NULL_TREE
6502 && type_dependent_expression_p (ce->value))
6503 return;
6507 if (failure)
6508 TREE_TYPE (decl) = error_mark_node;
6509 else
6511 failure = cp_complete_array_type (&TREE_TYPE (decl), initializer,
6512 do_default);
6513 if (failure == 1)
6515 error_at (cp_expr_loc_or_loc (initializer,
6516 DECL_SOURCE_LOCATION (decl)),
6517 "initializer fails to determine size of %qD", decl);
6519 else if (failure == 2)
6521 if (do_default)
6523 error_at (DECL_SOURCE_LOCATION (decl),
6524 "array size missing in %qD", decl);
6526 /* If a `static' var's size isn't known, make it extern as
6527 well as static, so it does not get allocated. If it's not
6528 `static', then don't mark it extern; finish_incomplete_decl
6529 will give it a default size and it will get allocated. */
6530 else if (!pedantic && TREE_STATIC (decl) && !TREE_PUBLIC (decl))
6531 DECL_EXTERNAL (decl) = 1;
6533 else if (failure == 3)
6535 error_at (DECL_SOURCE_LOCATION (decl),
6536 "zero-size array %qD", decl);
6540 cp_apply_type_quals_to_decl (cp_type_quals (TREE_TYPE (decl)), decl);
6542 relayout_decl (decl);
6546 /* Set DECL_SIZE, DECL_ALIGN, etc. for DECL (a VAR_DECL), and issue
6547 any appropriate error messages regarding the layout. */
6549 static void
6550 layout_var_decl (tree decl)
6552 tree type;
6554 type = TREE_TYPE (decl);
6555 if (type == error_mark_node)
6556 return;
6558 /* If we haven't already laid out this declaration, do so now.
6559 Note that we must not call complete type for an external object
6560 because it's type might involve templates that we are not
6561 supposed to instantiate yet. (And it's perfectly valid to say
6562 `extern X x' for some incomplete type `X'.) */
6563 if (!DECL_EXTERNAL (decl))
6564 complete_type (type);
6565 if (!DECL_SIZE (decl)
6566 && TREE_TYPE (decl) != error_mark_node
6567 && complete_or_array_type_p (type))
6568 layout_decl (decl, 0);
6570 if (!DECL_EXTERNAL (decl) && DECL_SIZE (decl) == NULL_TREE)
6572 /* An automatic variable with an incomplete type: that is an error.
6573 Don't talk about array types here, since we took care of that
6574 message in grokdeclarator. */
6575 error_at (DECL_SOURCE_LOCATION (decl),
6576 "storage size of %qD isn%'t known", decl);
6577 TREE_TYPE (decl) = error_mark_node;
6579 #if 0
6580 /* Keep this code around in case we later want to control debug info
6581 based on whether a type is "used". (jason 1999-11-11) */
6583 else if (!DECL_EXTERNAL (decl) && MAYBE_CLASS_TYPE_P (ttype))
6584 /* Let debugger know it should output info for this type. */
6585 note_debug_info_needed (ttype);
6587 if (TREE_STATIC (decl) && DECL_CLASS_SCOPE_P (decl))
6588 note_debug_info_needed (DECL_CONTEXT (decl));
6589 #endif
6591 if ((DECL_EXTERNAL (decl) || TREE_STATIC (decl))
6592 && DECL_SIZE (decl) != NULL_TREE
6593 && ! TREE_CONSTANT (DECL_SIZE (decl)))
6595 if (TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST
6596 && !DECL_LOCAL_DECL_P (decl))
6597 constant_expression_warning (DECL_SIZE (decl));
6598 else
6600 error_at (DECL_SOURCE_LOCATION (decl),
6601 "storage size of %qD isn%'t constant", decl);
6602 TREE_TYPE (decl) = error_mark_node;
6603 type = error_mark_node;
6607 /* If the final element initializes a flexible array field, adjust
6608 the size of the DECL with the initializer based on whether the
6609 DECL is a union or a structure. */
6610 if (type != error_mark_node
6611 && DECL_INITIAL (decl)
6612 && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
6613 && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl)))
6614 && DECL_SIZE (decl) != NULL_TREE
6615 && TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST
6616 && COMPLETE_TYPE_P (type)
6617 && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST
6618 && tree_int_cst_equal (DECL_SIZE (decl), TYPE_SIZE (type)))
6620 constructor_elt &elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ();
6621 if (elt.index)
6623 tree itype = TREE_TYPE (elt.index);
6624 tree vtype = TREE_TYPE (elt.value);
6625 if (TREE_CODE (itype) == ARRAY_TYPE
6626 && TYPE_DOMAIN (itype) == NULL
6627 && TREE_CODE (vtype) == ARRAY_TYPE
6628 && COMPLETE_TYPE_P (vtype))
6630 /* For a structure, add the size of the initializer to the DECL's
6631 size. */
6632 if (TREE_CODE (TREE_TYPE (decl)) == RECORD_TYPE)
6634 DECL_SIZE (decl)
6635 = size_binop (PLUS_EXPR, DECL_SIZE (decl),
6636 TYPE_SIZE (vtype));
6637 DECL_SIZE_UNIT (decl)
6638 = size_binop (PLUS_EXPR, DECL_SIZE_UNIT (decl),
6639 TYPE_SIZE_UNIT (vtype));
6641 /* For a union, the DECL's size is the maximum of the current size
6642 and the size of the initializer. */
6643 else
6645 DECL_SIZE (decl)
6646 = size_binop (MAX_EXPR, DECL_SIZE (decl),
6647 TYPE_SIZE (vtype));
6648 DECL_SIZE_UNIT (decl)
6649 = size_binop (MAX_EXPR, DECL_SIZE_UNIT (decl),
6650 TYPE_SIZE_UNIT (vtype));
6657 /* If a local static variable is declared in an inline function, or if
6658 we have a weak definition, we must endeavor to create only one
6659 instance of the variable at link-time. */
6661 void
6662 maybe_commonize_var (tree decl)
6664 /* Don't mess with __FUNCTION__ and similar. But do handle structured
6665 bindings. */
6666 if (DECL_ARTIFICIAL (decl) && !DECL_DECOMPOSITION_P (decl))
6667 return;
6669 /* Static data in a function with comdat linkage also has comdat
6670 linkage. */
6671 if ((TREE_STATIC (decl)
6672 && DECL_FUNCTION_SCOPE_P (decl)
6673 && vague_linkage_p (DECL_CONTEXT (decl)))
6674 || (TREE_PUBLIC (decl) && DECL_INLINE_VAR_P (decl)))
6676 if (flag_weak)
6678 /* With weak symbols, we simply make the variable COMDAT;
6679 that will cause copies in multiple translations units to
6680 be merged. */
6681 comdat_linkage (decl);
6683 else
6685 if (DECL_INITIAL (decl) == NULL_TREE
6686 || DECL_INITIAL (decl) == error_mark_node)
6688 /* Without weak symbols, we can use COMMON to merge
6689 uninitialized variables. */
6690 TREE_PUBLIC (decl) = 1;
6691 DECL_COMMON (decl) = 1;
6693 else
6695 /* While for initialized variables, we must use internal
6696 linkage -- which means that multiple copies will not
6697 be merged. */
6698 TREE_PUBLIC (decl) = 0;
6699 DECL_COMMON (decl) = 0;
6700 DECL_INTERFACE_KNOWN (decl) = 1;
6701 const char *msg;
6702 if (DECL_INLINE_VAR_P (decl))
6703 msg = G_("sorry: semantics of inline variable "
6704 "%q#D are wrong (you%'ll wind up with "
6705 "multiple copies)");
6706 else
6707 msg = G_("sorry: semantics of inline function "
6708 "static data %q#D are wrong (you%'ll wind "
6709 "up with multiple copies)");
6710 auto_diagnostic_group d;
6711 if (warning_at (DECL_SOURCE_LOCATION (decl), 0,
6712 msg, decl))
6713 inform (DECL_SOURCE_LOCATION (decl),
6714 "you can work around this by removing the initializer");
6720 /* Issue an error message if DECL is an uninitialized const variable.
6721 CONSTEXPR_CONTEXT_P is true when the function is called in a constexpr
6722 context from potential_constant_expression. Returns true if all is well,
6723 false otherwise. */
6725 bool
6726 check_for_uninitialized_const_var (tree decl, bool constexpr_context_p,
6727 tsubst_flags_t complain)
6729 tree type = strip_array_types (TREE_TYPE (decl));
6731 /* ``Unless explicitly declared extern, a const object does not have
6732 external linkage and must be initialized. ($8.4; $12.1)'' ARM
6733 7.1.6 */
6734 if (VAR_P (decl)
6735 && !TYPE_REF_P (type)
6736 && (CP_TYPE_CONST_P (type)
6737 /* C++20 permits trivial default initialization in constexpr
6738 context (P1331R2). */
6739 || (cxx_dialect < cxx20
6740 && (constexpr_context_p
6741 || var_in_constexpr_fn (decl))))
6742 && !DECL_NONTRIVIALLY_INITIALIZED_P (decl))
6744 tree field = default_init_uninitialized_part (type);
6745 if (!field)
6746 return true;
6748 auto_diagnostic_group d;
6749 bool show_notes = true;
6751 if (!constexpr_context_p || cxx_dialect >= cxx20)
6753 if (CP_TYPE_CONST_P (type))
6755 if (complain & tf_error)
6756 show_notes = permerror (DECL_SOURCE_LOCATION (decl),
6757 "uninitialized %<const %D%>", decl);
6759 else
6761 if (!is_instantiation_of_constexpr (current_function_decl)
6762 && (complain & tf_error))
6763 error_at (DECL_SOURCE_LOCATION (decl),
6764 "uninitialized variable %qD in %<constexpr%> "
6765 "function", decl);
6766 else
6767 show_notes = false;
6768 cp_function_chain->invalid_constexpr = true;
6771 else if (complain & tf_error)
6772 error_at (DECL_SOURCE_LOCATION (decl),
6773 "uninitialized variable %qD in %<constexpr%> context",
6774 decl);
6776 if (show_notes && CLASS_TYPE_P (type) && (complain & tf_error))
6778 tree defaulted_ctor;
6780 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)),
6781 "%q#T has no user-provided default constructor", type);
6782 defaulted_ctor = in_class_defaulted_default_constructor (type);
6783 if (defaulted_ctor)
6784 inform (DECL_SOURCE_LOCATION (defaulted_ctor),
6785 "constructor is not user-provided because it is "
6786 "explicitly defaulted in the class body");
6787 inform (DECL_SOURCE_LOCATION (field),
6788 "and the implicitly-defined constructor does not "
6789 "initialize %q#D", field);
6792 return false;
6795 return true;
6798 /* Structure holding the current initializer being processed by reshape_init.
6799 CUR is a pointer to the current element being processed, END is a pointer
6800 after the last element present in the initializer. */
6801 struct reshape_iter
6803 constructor_elt *cur;
6804 constructor_elt *end;
6807 static tree reshape_init_r (tree, reshape_iter *, tree, tsubst_flags_t);
6809 /* FIELD is an element of TYPE_FIELDS or NULL. In the former case, the value
6810 returned is the next FIELD_DECL (possibly FIELD itself) that can be
6811 initialized as if for an aggregate class. If there are no more such fields,
6812 the return value will be NULL. */
6814 tree
6815 next_aggregate_field (tree field)
6817 while (field
6818 && (TREE_CODE (field) != FIELD_DECL
6819 || DECL_UNNAMED_BIT_FIELD (field)
6820 || (DECL_ARTIFICIAL (field)
6821 /* In C++17, aggregates can have bases. */
6822 && !(cxx_dialect >= cxx17 && DECL_FIELD_IS_BASE (field)))))
6823 field = DECL_CHAIN (field);
6825 return field;
6828 /* FIELD is an element of TYPE_FIELDS or NULL. In the former case, the value
6829 returned is the next FIELD_DECL (possibly FIELD itself) that corresponds
6830 to a subobject. If there are no more such fields, the return value will be
6831 NULL. */
6833 tree
6834 next_subobject_field (tree field)
6836 while (field
6837 && (TREE_CODE (field) != FIELD_DECL
6838 || DECL_UNNAMED_BIT_FIELD (field)
6839 || (DECL_ARTIFICIAL (field)
6840 && !DECL_FIELD_IS_BASE (field)
6841 && !DECL_VIRTUAL_P (field))))
6842 field = DECL_CHAIN (field);
6844 return field;
6847 /* Return true for [dcl.init.list] direct-list-initialization from
6848 single element of enumeration with a fixed underlying type. */
6850 bool
6851 is_direct_enum_init (tree type, tree init)
6853 if (cxx_dialect >= cxx17
6854 && TREE_CODE (type) == ENUMERAL_TYPE
6855 && ENUM_FIXED_UNDERLYING_TYPE_P (type)
6856 && TREE_CODE (init) == CONSTRUCTOR
6857 && CONSTRUCTOR_IS_DIRECT_INIT (init)
6858 && CONSTRUCTOR_NELTS (init) == 1
6859 /* DR 2374: The single element needs to be implicitly
6860 convertible to the underlying type of the enum. */
6861 && !type_dependent_expression_p (CONSTRUCTOR_ELT (init, 0)->value)
6862 && can_convert_arg (ENUM_UNDERLYING_TYPE (type),
6863 TREE_TYPE (CONSTRUCTOR_ELT (init, 0)->value),
6864 CONSTRUCTOR_ELT (init, 0)->value,
6865 LOOKUP_IMPLICIT, tf_none))
6866 return true;
6867 return false;
6870 /* Subroutine of reshape_init_array and reshape_init_vector, which does
6871 the actual work. ELT_TYPE is the element type of the array. MAX_INDEX is an
6872 INTEGER_CST representing the size of the array minus one (the maximum index),
6873 or NULL_TREE if the array was declared without specifying the size. D is
6874 the iterator within the constructor. */
6876 static tree
6877 reshape_init_array_1 (tree elt_type, tree max_index, reshape_iter *d,
6878 tree first_initializer_p, tsubst_flags_t complain)
6880 tree new_init;
6881 bool sized_array_p = (max_index && TREE_CONSTANT (max_index));
6882 unsigned HOST_WIDE_INT max_index_cst = 0;
6883 unsigned HOST_WIDE_INT index;
6885 /* The initializer for an array is always a CONSTRUCTOR. If this is the
6886 outermost CONSTRUCTOR and the element type is non-aggregate, we don't need
6887 to build a new one. But don't reuse if not complaining; if this is
6888 tentative, we might also reshape to another type (95319). */
6889 bool reuse = (first_initializer_p
6890 && (complain & tf_error)
6891 && !CP_AGGREGATE_TYPE_P (elt_type)
6892 && !TREE_SIDE_EFFECTS (first_initializer_p));
6893 if (reuse)
6894 new_init = first_initializer_p;
6895 else
6896 new_init = build_constructor (init_list_type_node, NULL);
6898 if (sized_array_p)
6900 /* Minus 1 is used for zero sized arrays. */
6901 if (integer_all_onesp (max_index))
6902 return new_init;
6904 if (tree_fits_uhwi_p (max_index))
6905 max_index_cst = tree_to_uhwi (max_index);
6906 /* sizetype is sign extended, not zero extended. */
6907 else
6908 max_index_cst = tree_to_uhwi (fold_convert (size_type_node, max_index));
6911 /* Loop until there are no more initializers. */
6912 for (index = 0;
6913 d->cur != d->end && (!sized_array_p || index <= max_index_cst);
6914 ++index)
6916 tree elt_init;
6917 constructor_elt *old_cur = d->cur;
6919 if (d->cur->index)
6920 CONSTRUCTOR_IS_DESIGNATED_INIT (new_init) = true;
6921 check_array_designated_initializer (d->cur, index);
6922 elt_init = reshape_init_r (elt_type, d,
6923 /*first_initializer_p=*/NULL_TREE,
6924 complain);
6925 if (elt_init == error_mark_node)
6926 return error_mark_node;
6927 tree idx = size_int (index);
6928 if (reuse)
6930 old_cur->index = idx;
6931 old_cur->value = elt_init;
6933 else
6934 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
6935 idx, elt_init);
6936 if (!TREE_CONSTANT (elt_init))
6937 TREE_CONSTANT (new_init) = false;
6939 /* This can happen with an invalid initializer (c++/54501). */
6940 if (d->cur == old_cur && !sized_array_p)
6941 break;
6944 return new_init;
6947 /* Subroutine of reshape_init_r, processes the initializers for arrays.
6948 Parameters are the same of reshape_init_r. */
6950 static tree
6951 reshape_init_array (tree type, reshape_iter *d, tree first_initializer_p,
6952 tsubst_flags_t complain)
6954 tree max_index = NULL_TREE;
6956 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
6958 if (TYPE_DOMAIN (type))
6959 max_index = array_type_nelts (type);
6961 return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6962 first_initializer_p, complain);
6965 /* Subroutine of reshape_init_r, processes the initializers for vectors.
6966 Parameters are the same of reshape_init_r. */
6968 static tree
6969 reshape_init_vector (tree type, reshape_iter *d, tsubst_flags_t complain)
6971 tree max_index = NULL_TREE;
6973 gcc_assert (VECTOR_TYPE_P (type));
6975 if (COMPOUND_LITERAL_P (d->cur->value))
6977 tree value = d->cur->value;
6978 if (!same_type_p (TREE_TYPE (value), type))
6980 if (complain & tf_error)
6981 error ("invalid type %qT as initializer for a vector of type %qT",
6982 TREE_TYPE (d->cur->value), type);
6983 value = error_mark_node;
6985 ++d->cur;
6986 return value;
6989 /* For a vector, we initialize it as an array of the appropriate size. */
6990 if (VECTOR_TYPE_P (type))
6991 max_index = size_int (TYPE_VECTOR_SUBPARTS (type) - 1);
6993 return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6994 NULL_TREE, complain);
6997 /* Subroutine of reshape_init*: We're initializing an element with TYPE from
6998 INIT, in isolation from any designator or other initializers. */
7000 static tree
7001 reshape_single_init (tree type, tree init, tsubst_flags_t complain)
7003 /* We could also implement this by wrapping init in a new CONSTRUCTOR and
7004 calling reshape_init, but this way can just live on the stack. */
7005 constructor_elt elt = { /*index=*/NULL_TREE, init };
7006 reshape_iter iter = { &elt, &elt + 1 };
7007 return reshape_init_r (type, &iter,
7008 /*first_initializer_p=*/NULL_TREE,
7009 complain);
7012 /* Subroutine of reshape_init_r, processes the initializers for classes
7013 or union. Parameters are the same of reshape_init_r. */
7015 static tree
7016 reshape_init_class (tree type, reshape_iter *d, bool first_initializer_p,
7017 tsubst_flags_t complain)
7019 tree field;
7020 tree new_init;
7022 gcc_assert (CLASS_TYPE_P (type));
7024 /* The initializer for a class is always a CONSTRUCTOR. */
7025 new_init = build_constructor (init_list_type_node, NULL);
7027 int binfo_idx = -1;
7028 tree binfo = TYPE_BINFO (type);
7029 tree base_binfo = NULL_TREE;
7030 if (cxx_dialect >= cxx17 && uses_template_parms (type))
7032 /* We get here from maybe_aggr_guide for C++20 class template argument
7033 deduction. In this case we need to look through the binfo because a
7034 template doesn't have base fields. */
7035 binfo_idx = 0;
7036 BINFO_BASE_ITERATE (binfo, binfo_idx, base_binfo);
7038 if (base_binfo)
7039 field = base_binfo;
7040 else
7041 field = next_aggregate_field (TYPE_FIELDS (type));
7043 if (!field)
7045 /* [dcl.init.aggr]
7047 An initializer for an aggregate member that is an
7048 empty class shall have the form of an empty
7049 initializer-list {}. */
7050 if (!first_initializer_p)
7052 if (complain & tf_error)
7053 error ("initializer for %qT must be brace-enclosed", type);
7054 return error_mark_node;
7056 return new_init;
7059 /* For C++20 CTAD, handle pack expansions in the base list. */
7060 tree last_was_pack_expansion = NULL_TREE;
7062 /* Loop through the initializable fields, gathering initializers. */
7063 while (d->cur != d->end)
7065 tree field_init;
7066 constructor_elt *old_cur = d->cur;
7067 bool direct_desig = false;
7069 /* Handle C++20 designated initializers. */
7070 if (d->cur->index)
7072 if (d->cur->index == error_mark_node)
7073 return error_mark_node;
7075 if (TREE_CODE (d->cur->index) == FIELD_DECL)
7077 /* We already reshaped this; we should have returned early from
7078 reshape_init. */
7079 gcc_checking_assert (false);
7080 if (field != d->cur->index)
7082 if (tree id = DECL_NAME (d->cur->index))
7083 gcc_checking_assert (d->cur->index
7084 == get_class_binding (type, id));
7085 field = d->cur->index;
7088 else if (TREE_CODE (d->cur->index) == IDENTIFIER_NODE)
7090 CONSTRUCTOR_IS_DESIGNATED_INIT (new_init) = true;
7091 field = get_class_binding (type, d->cur->index);
7092 direct_desig = true;
7094 else
7096 if (complain & tf_error)
7097 error ("%<[%E] =%> used in a GNU-style designated initializer"
7098 " for class %qT", d->cur->index, type);
7099 return error_mark_node;
7102 if (!field && ANON_AGGR_TYPE_P (type))
7103 /* Apparently the designator isn't for a member of this anonymous
7104 struct, so head back to the enclosing class. */
7105 break;
7107 if (!field || TREE_CODE (field) != FIELD_DECL)
7109 if (complain & tf_error)
7111 if (field && TREE_CODE (field) == TREE_LIST)
7113 auto_diagnostic_group g;
7114 error ("request for member %qD is ambiguous",
7115 d->cur->index);
7116 print_candidates (field);
7118 else
7119 error ("%qT has no non-static data member named %qD", type,
7120 d->cur->index);
7122 return error_mark_node;
7125 /* If the element is an anonymous union object and the initializer
7126 list is a designated-initializer-list, the anonymous union object
7127 is initialized by the designated-initializer-list { D }, where D
7128 is the designated-initializer-clause naming a member of the
7129 anonymous union object. */
7130 tree ictx = DECL_CONTEXT (field);
7131 if (!same_type_ignoring_top_level_qualifiers_p (ictx, type))
7133 /* Find the anon aggr that is a direct member of TYPE. */
7134 while (ANON_AGGR_TYPE_P (ictx))
7136 tree cctx = TYPE_CONTEXT (ictx);
7137 if (same_type_ignoring_top_level_qualifiers_p (cctx, type))
7138 goto found;
7139 ictx = cctx;
7142 /* Not found, e.g. FIELD is a member of a base class. */
7143 if (complain & tf_error)
7144 error ("%qD is not a direct member of %qT", field, type);
7145 return error_mark_node;
7147 found:
7148 /* Now find the TYPE member with that anon aggr type. */
7149 tree aafield = TYPE_FIELDS (type);
7150 for (; aafield; aafield = TREE_CHAIN (aafield))
7151 if (TREE_TYPE (aafield) == ictx)
7152 break;
7153 gcc_assert (aafield);
7154 field = aafield;
7155 direct_desig = false;
7159 /* If we processed all the member of the class, we are done. */
7160 if (!field)
7161 break;
7163 last_was_pack_expansion = (PACK_EXPANSION_P (TREE_TYPE (field))
7164 ? field : NULL_TREE);
7165 if (last_was_pack_expansion)
7166 /* Each non-trailing aggregate element that is a pack expansion is
7167 assumed to correspond to no elements of the initializer list. */
7168 goto continue_;
7170 if (direct_desig)
7172 /* The designated field F is initialized from this one element.
7174 Note that we don't want to do this if we found the designator
7175 inside an anon aggr above; we use the normal code to implement:
7177 "If the element is an anonymous union member and the initializer
7178 list is a brace-enclosed designated- initializer-list, the element
7179 is initialized by the designated-initializer-list { D }, where D
7180 is the designated- initializer-clause naming a member of the
7181 anonymous union member." */
7182 field_init = reshape_single_init (TREE_TYPE (field),
7183 d->cur->value, complain);
7184 d->cur++;
7186 else
7187 field_init = reshape_init_r (TREE_TYPE (field), d,
7188 /*first_initializer_p=*/NULL_TREE,
7189 complain);
7191 if (field_init == error_mark_node)
7192 return error_mark_node;
7194 if (d->cur == old_cur && d->cur->index)
7196 /* This can happen with an invalid initializer for a flexible
7197 array member (c++/54441). */
7198 if (complain & tf_error)
7199 error ("invalid initializer for %q#D", field);
7200 return error_mark_node;
7203 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init), field, field_init);
7205 /* [dcl.init.aggr]
7207 When a union is initialized with a brace-enclosed
7208 initializer, the braces shall only contain an
7209 initializer for the first member of the union. */
7210 if (TREE_CODE (type) == UNION_TYPE)
7211 break;
7213 continue_:
7214 if (base_binfo)
7216 if (BINFO_BASE_ITERATE (binfo, ++binfo_idx, base_binfo))
7217 field = base_binfo;
7218 else
7219 field = next_aggregate_field (TYPE_FIELDS (type));
7221 else
7222 field = next_aggregate_field (DECL_CHAIN (field));
7225 /* A trailing aggregate element that is a pack expansion is assumed to
7226 correspond to all remaining elements of the initializer list (if any). */
7227 if (last_was_pack_expansion)
7229 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
7230 last_was_pack_expansion, d->cur->value);
7231 while (d->cur != d->end)
7232 d->cur++;
7235 return new_init;
7238 /* Subroutine of reshape_init_r. We're in a context where C99 initializer
7239 designators are not valid; either complain or return true to indicate
7240 that reshape_init_r should return error_mark_node. */
7242 static bool
7243 has_designator_problem (reshape_iter *d, tsubst_flags_t complain)
7245 if (d->cur->index)
7247 if (complain & tf_error)
7248 error_at (cp_expr_loc_or_input_loc (d->cur->index),
7249 "C99 designator %qE outside aggregate initializer",
7250 d->cur->index);
7251 else
7252 return true;
7254 return false;
7257 /* Subroutine of reshape_init, which processes a single initializer (part of
7258 a CONSTRUCTOR). TYPE is the type of the variable being initialized, D is the
7259 iterator within the CONSTRUCTOR which points to the initializer to process.
7260 If this is the first initializer of the outermost CONSTRUCTOR node,
7261 FIRST_INITIALIZER_P is that CONSTRUCTOR; otherwise, it is NULL_TREE. */
7263 static tree
7264 reshape_init_r (tree type, reshape_iter *d, tree first_initializer_p,
7265 tsubst_flags_t complain)
7267 tree init = d->cur->value;
7269 if (error_operand_p (init))
7270 return error_mark_node;
7272 if (first_initializer_p && !CP_AGGREGATE_TYPE_P (type)
7273 && has_designator_problem (d, complain))
7274 return error_mark_node;
7276 tree stripped_init = tree_strip_any_location_wrapper (init);
7278 if (TREE_CODE (type) == COMPLEX_TYPE)
7280 /* A complex type can be initialized from one or two initializers,
7281 but braces are not elided. */
7282 d->cur++;
7283 if (BRACE_ENCLOSED_INITIALIZER_P (stripped_init))
7285 if (CONSTRUCTOR_NELTS (stripped_init) > 2)
7287 if (complain & tf_error)
7288 error ("too many initializers for %qT", type);
7289 else
7290 return error_mark_node;
7293 else if (first_initializer_p && d->cur != d->end)
7295 vec<constructor_elt, va_gc> *v = 0;
7296 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
7297 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, d->cur->value);
7298 if (has_designator_problem (d, complain))
7299 return error_mark_node;
7300 d->cur++;
7301 init = build_constructor (init_list_type_node, v);
7303 return init;
7306 /* A non-aggregate type is always initialized with a single
7307 initializer. */
7308 if (!CP_AGGREGATE_TYPE_P (type)
7309 /* As is an array with dependent bound, which we can see
7310 during C++20 aggregate CTAD. */
7311 || (cxx_dialect >= cxx20
7312 && TREE_CODE (type) == ARRAY_TYPE
7313 && uses_template_parms (TYPE_DOMAIN (type))))
7315 /* It is invalid to initialize a non-aggregate type with a
7316 brace-enclosed initializer before C++0x.
7317 We need to check for BRACE_ENCLOSED_INITIALIZER_P here because
7318 of g++.old-deja/g++.mike/p7626.C: a pointer-to-member constant is
7319 a CONSTRUCTOR (with a record type). */
7320 if (TREE_CODE (stripped_init) == CONSTRUCTOR
7321 /* Don't complain about a capture-init. */
7322 && !CONSTRUCTOR_IS_DIRECT_INIT (stripped_init)
7323 && BRACE_ENCLOSED_INITIALIZER_P (stripped_init)) /* p7626.C */
7325 if (SCALAR_TYPE_P (type))
7327 if (cxx_dialect < cxx11)
7329 if (complain & tf_error)
7330 error ("braces around scalar initializer for type %qT",
7331 type);
7332 init = error_mark_node;
7334 else if (first_initializer_p
7335 || (CONSTRUCTOR_NELTS (stripped_init) > 0
7336 && (BRACE_ENCLOSED_INITIALIZER_P
7337 (CONSTRUCTOR_ELT (stripped_init,0)->value))))
7339 if (complain & tf_error)
7340 error ("too many braces around scalar initializer "
7341 "for type %qT", type);
7342 init = error_mark_node;
7345 else
7346 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
7349 d->cur++;
7350 return init;
7353 /* "If T is a class type and the initializer list has a single element of
7354 type cv U, where U is T or a class derived from T, the object is
7355 initialized from that element." Even if T is an aggregate. */
7356 if (cxx_dialect >= cxx11 && (CLASS_TYPE_P (type) || VECTOR_TYPE_P (type))
7357 && first_initializer_p
7358 /* But not if it's a designated init. */
7359 && !d->cur->index
7360 && d->end - d->cur == 1
7361 && reference_related_p (type, TREE_TYPE (init)))
7363 d->cur++;
7364 return init;
7367 /* [dcl.init.aggr]
7369 All implicit type conversions (clause _conv_) are considered when
7370 initializing the aggregate member with an initializer from an
7371 initializer-list. If the initializer can initialize a member,
7372 the member is initialized. Otherwise, if the member is itself a
7373 non-empty subaggregate, brace elision is assumed and the
7374 initializer is considered for the initialization of the first
7375 member of the subaggregate. */
7376 if ((TREE_CODE (init) != CONSTRUCTOR || COMPOUND_LITERAL_P (init))
7377 /* But don't try this for the first initializer, since that would be
7378 looking through the outermost braces; A a2 = { a1 }; is not a
7379 valid aggregate initialization. */
7380 && !first_initializer_p
7381 && (same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (init))
7382 || can_convert_arg (type, TREE_TYPE (init), init, LOOKUP_NORMAL,
7383 complain)))
7385 d->cur++;
7386 return init;
7389 /* [dcl.init.string]
7391 A char array (whether plain char, signed char, or unsigned char)
7392 can be initialized by a string-literal (optionally enclosed in
7393 braces); a wchar_t array can be initialized by a wide
7394 string-literal (optionally enclosed in braces). */
7395 if (TREE_CODE (type) == ARRAY_TYPE
7396 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type))))
7398 tree str_init = init;
7399 tree stripped_str_init = stripped_init;
7400 reshape_iter stripd = {};
7402 /* Strip one level of braces if and only if they enclose a single
7403 element (as allowed by [dcl.init.string]). */
7404 if (!first_initializer_p
7405 && TREE_CODE (stripped_str_init) == CONSTRUCTOR
7406 && CONSTRUCTOR_NELTS (stripped_str_init) == 1)
7408 stripd.cur = CONSTRUCTOR_ELT (stripped_str_init, 0);
7409 str_init = stripd.cur->value;
7410 stripped_str_init = tree_strip_any_location_wrapper (str_init);
7413 /* If it's a string literal, then it's the initializer for the array
7414 as a whole. Otherwise, continue with normal initialization for
7415 array types (one value per array element). */
7416 if (TREE_CODE (stripped_str_init) == STRING_CST)
7418 if ((first_initializer_p && has_designator_problem (d, complain))
7419 || (stripd.cur && has_designator_problem (&stripd, complain)))
7420 return error_mark_node;
7421 d->cur++;
7422 return str_init;
7426 /* The following cases are about aggregates. If we are not within a full
7427 initializer already, and there is not a CONSTRUCTOR, it means that there
7428 is a missing set of braces (that is, we are processing the case for
7429 which reshape_init exists). */
7430 bool braces_elided_p = false;
7431 if (!first_initializer_p)
7433 if (TREE_CODE (stripped_init) == CONSTRUCTOR)
7435 tree init_type = TREE_TYPE (init);
7436 if (init_type && TYPE_PTRMEMFUNC_P (init_type))
7437 /* There is no need to call reshape_init for pointer-to-member
7438 function initializers, as they are always constructed correctly
7439 by the front end. Here we have e.g. {.__pfn=0B, .__delta=0},
7440 which is missing outermost braces. We should warn below, and
7441 one of the routines below will wrap it in additional { }. */;
7442 /* For a nested compound literal, proceed to specialized routines,
7443 to handle initialization of arrays and similar. */
7444 else if (COMPOUND_LITERAL_P (stripped_init))
7445 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
7446 /* If we have an unresolved designator, we need to find the member it
7447 designates within TYPE, so proceed to the routines below. For
7448 FIELD_DECL or INTEGER_CST designators, we're already initializing
7449 the designated element. */
7450 else if (d->cur->index
7451 && TREE_CODE (d->cur->index) == IDENTIFIER_NODE)
7452 /* Brace elision with designators is only permitted for anonymous
7453 aggregates. */
7454 gcc_checking_assert (ANON_AGGR_TYPE_P (type));
7455 /* A CONSTRUCTOR of the target's type is a previously
7456 digested initializer. */
7457 else if (same_type_ignoring_top_level_qualifiers_p (type, init_type))
7459 ++d->cur;
7460 return init;
7462 else
7464 /* Something that hasn't been reshaped yet. */
7465 ++d->cur;
7466 gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
7467 return reshape_init (type, init, complain);
7471 if (complain & tf_warning)
7472 warning (OPT_Wmissing_braces,
7473 "missing braces around initializer for %qT",
7474 type);
7475 braces_elided_p = true;
7478 /* Dispatch to specialized routines. */
7479 tree new_init;
7480 if (CLASS_TYPE_P (type))
7481 new_init = reshape_init_class (type, d, first_initializer_p, complain);
7482 else if (TREE_CODE (type) == ARRAY_TYPE)
7483 new_init = reshape_init_array (type, d, first_initializer_p, complain);
7484 else if (VECTOR_TYPE_P (type))
7485 new_init = reshape_init_vector (type, d, complain);
7486 else
7487 gcc_unreachable();
7489 if (braces_elided_p
7490 && TREE_CODE (new_init) == CONSTRUCTOR)
7491 CONSTRUCTOR_BRACES_ELIDED_P (new_init) = true;
7493 return new_init;
7496 /* Undo the brace-elision allowed by [dcl.init.aggr] in a
7497 brace-enclosed aggregate initializer.
7499 INIT is the CONSTRUCTOR containing the list of initializers describing
7500 a brace-enclosed initializer for an entity of the indicated aggregate TYPE.
7501 It may not presently match the shape of the TYPE; for example:
7503 struct S { int a; int b; };
7504 struct S a[] = { 1, 2, 3, 4 };
7506 Here INIT will hold a vector of four elements, rather than a
7507 vector of two elements, each itself a vector of two elements. This
7508 routine transforms INIT from the former form into the latter. The
7509 revised CONSTRUCTOR node is returned. */
7511 tree
7512 reshape_init (tree type, tree init, tsubst_flags_t complain)
7514 vec<constructor_elt, va_gc> *v;
7515 reshape_iter d;
7516 tree new_init;
7518 gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (init));
7520 v = CONSTRUCTOR_ELTS (init);
7522 /* An empty constructor does not need reshaping, and it is always a valid
7523 initializer. */
7524 if (vec_safe_is_empty (v))
7525 return init;
7527 if ((*v)[0].index && TREE_CODE ((*v)[0].index) == FIELD_DECL)
7528 /* Already reshaped. */
7529 return init;
7531 /* Brace elision is not performed for a CONSTRUCTOR representing
7532 parenthesized aggregate initialization. */
7533 if (CONSTRUCTOR_IS_PAREN_INIT (init))
7535 tree elt = (*v)[0].value;
7536 /* If we're initializing a char array from a string-literal that is
7537 enclosed in braces, unwrap it here. */
7538 if (TREE_CODE (type) == ARRAY_TYPE
7539 && vec_safe_length (v) == 1
7540 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
7541 && TREE_CODE (tree_strip_any_location_wrapper (elt)) == STRING_CST)
7542 return elt;
7543 return init;
7546 /* Handle [dcl.init.list] direct-list-initialization from
7547 single element of enumeration with a fixed underlying type. */
7548 if (is_direct_enum_init (type, init))
7550 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
7551 type = cv_unqualified (type);
7552 if (check_narrowing (ENUM_UNDERLYING_TYPE (type), elt, complain))
7554 warning_sentinel w (warn_useless_cast);
7555 warning_sentinel w2 (warn_ignored_qualifiers);
7556 return cp_build_c_cast (input_location, type, elt,
7557 tf_warning_or_error);
7559 else
7560 return error_mark_node;
7563 /* Recurse on this CONSTRUCTOR. */
7564 d.cur = &(*v)[0];
7565 d.end = d.cur + v->length ();
7567 new_init = reshape_init_r (type, &d, init, complain);
7568 if (new_init == error_mark_node)
7569 return error_mark_node;
7571 /* Make sure all the element of the constructor were used. Otherwise,
7572 issue an error about exceeding initializers. */
7573 if (d.cur != d.end)
7575 if (complain & tf_error)
7576 error ("too many initializers for %qT", type);
7577 return error_mark_node;
7580 if (CONSTRUCTOR_IS_DIRECT_INIT (init)
7581 && BRACE_ENCLOSED_INITIALIZER_P (new_init))
7582 CONSTRUCTOR_IS_DIRECT_INIT (new_init) = true;
7583 if (CONSTRUCTOR_IS_DESIGNATED_INIT (init)
7584 && BRACE_ENCLOSED_INITIALIZER_P (new_init))
7585 gcc_checking_assert (CONSTRUCTOR_IS_DESIGNATED_INIT (new_init)
7586 || seen_error ());
7588 return new_init;
7591 /* Verify array initializer. Returns true if errors have been reported. */
7593 bool
7594 check_array_initializer (tree decl, tree type, tree init)
7596 tree element_type = TREE_TYPE (type);
7598 /* Structured binding when initialized with an array type needs
7599 to have complete type. */
7600 if (decl
7601 && DECL_DECOMPOSITION_P (decl)
7602 && DECL_DECOMP_IS_BASE (decl)
7603 && !COMPLETE_TYPE_P (type))
7605 error_at (DECL_SOURCE_LOCATION (decl),
7606 "structured binding has incomplete type %qT", type);
7607 TREE_TYPE (decl) = error_mark_node;
7608 return true;
7611 /* The array type itself need not be complete, because the
7612 initializer may tell us how many elements are in the array.
7613 But, the elements of the array must be complete. */
7614 if (!COMPLETE_TYPE_P (complete_type (element_type)))
7616 if (decl)
7617 error_at (DECL_SOURCE_LOCATION (decl),
7618 "elements of array %q#D have incomplete type", decl);
7619 else
7620 error ("elements of array %q#T have incomplete type", type);
7621 return true;
7624 location_t loc = (decl ? location_of (decl) : input_location);
7625 if (!verify_type_context (loc, TCTX_ARRAY_ELEMENT, element_type))
7626 return true;
7628 /* A compound literal can't have variable size. */
7629 if (init && !decl
7630 && ((COMPLETE_TYPE_P (type) && !TREE_CONSTANT (TYPE_SIZE (type)))
7631 || !TREE_CONSTANT (TYPE_SIZE (element_type))))
7633 error ("variable-sized compound literal");
7634 return true;
7636 return false;
7639 /* Subroutine of check_initializer; args are passed down from that function.
7640 Set stmts_are_full_exprs_p to 1 across a call to build_aggr_init. */
7642 static tree
7643 build_aggr_init_full_exprs (tree decl, tree init, int flags)
7645 gcc_assert (stmts_are_full_exprs_p ());
7646 if (init)
7647 maybe_warn_pessimizing_move (init, TREE_TYPE (decl), /*return_p*/false);
7648 return build_aggr_init (decl, init, flags, tf_warning_or_error);
7651 /* Verify INIT (the initializer for DECL), and record the
7652 initialization in DECL_INITIAL, if appropriate. CLEANUP is as for
7653 grok_reference_init.
7655 If the return value is non-NULL, it is an expression that must be
7656 evaluated dynamically to initialize DECL. */
7658 static tree
7659 check_initializer (tree decl, tree init, int flags, vec<tree, va_gc> **cleanups)
7661 tree type;
7662 tree init_code = NULL;
7663 tree core_type;
7665 /* Things that are going to be initialized need to have complete
7666 type. */
7667 TREE_TYPE (decl) = type = complete_type (TREE_TYPE (decl));
7669 if (DECL_HAS_VALUE_EXPR_P (decl))
7671 /* A variable with DECL_HAS_VALUE_EXPR_P set is just a placeholder,
7672 it doesn't have storage to be initialized. */
7673 gcc_assert (init == NULL_TREE);
7674 return NULL_TREE;
7677 if (type == error_mark_node)
7678 /* We will have already complained. */
7679 return NULL_TREE;
7681 if (TREE_CODE (type) == ARRAY_TYPE)
7683 if (check_array_initializer (decl, type, init))
7684 return NULL_TREE;
7686 else if (!COMPLETE_TYPE_P (type))
7688 error_at (DECL_SOURCE_LOCATION (decl),
7689 "%q#D has incomplete type", decl);
7690 TREE_TYPE (decl) = error_mark_node;
7691 return NULL_TREE;
7693 else
7694 /* There is no way to make a variable-sized class type in GNU C++. */
7695 gcc_assert (TREE_CONSTANT (TYPE_SIZE (type)));
7697 if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
7699 int init_len = CONSTRUCTOR_NELTS (init);
7700 if (SCALAR_TYPE_P (type))
7702 if (init_len == 0)
7704 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
7705 init = build_zero_init (type, NULL_TREE, false);
7707 else if (init_len != 1 && TREE_CODE (type) != COMPLEX_TYPE)
7709 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
7710 "scalar object %qD requires one element in "
7711 "initializer", decl);
7712 TREE_TYPE (decl) = error_mark_node;
7713 return NULL_TREE;
7718 if (TREE_CODE (decl) == CONST_DECL)
7720 gcc_assert (!TYPE_REF_P (type));
7722 DECL_INITIAL (decl) = init;
7724 gcc_assert (init != NULL_TREE);
7725 init = NULL_TREE;
7727 else if (!init && DECL_REALLY_EXTERN (decl))
7729 else if (init || type_build_ctor_call (type)
7730 || TYPE_REF_P (type))
7732 if (TYPE_REF_P (type))
7734 init = grok_reference_init (decl, type, init, flags);
7735 flags |= LOOKUP_ALREADY_DIGESTED;
7737 else if (!init)
7738 check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
7739 tf_warning_or_error);
7740 /* Do not reshape constructors of vectors (they don't need to be
7741 reshaped. */
7742 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
7744 if (is_std_init_list (type))
7746 init = perform_implicit_conversion (type, init,
7747 tf_warning_or_error);
7748 flags |= LOOKUP_ALREADY_DIGESTED;
7750 else if (TYPE_NON_AGGREGATE_CLASS (type))
7752 /* Don't reshape if the class has constructors. */
7753 if (cxx_dialect == cxx98)
7754 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
7755 "in C++98 %qD must be initialized by "
7756 "constructor, not by %<{...}%>",
7757 decl);
7759 else if (VECTOR_TYPE_P (type) && TYPE_VECTOR_OPAQUE (type))
7761 error ("opaque vector types cannot be initialized");
7762 init = error_mark_node;
7764 else
7766 init = reshape_init (type, init, tf_warning_or_error);
7767 flags |= LOOKUP_NO_NARROWING;
7770 /* [dcl.init] "Otherwise, if the destination type is an array, the object
7771 is initialized as follows..." So handle things like
7773 int a[](1, 2, 3);
7775 which is permitted in C++20 by P0960. */
7776 else if (TREE_CODE (init) == TREE_LIST
7777 && TREE_TYPE (init) == NULL_TREE
7778 && TREE_CODE (type) == ARRAY_TYPE
7779 && !DECL_DECOMPOSITION_P (decl)
7780 && (cxx_dialect >= cxx20))
7781 init = do_aggregate_paren_init (init, type);
7782 else if (TREE_CODE (init) == TREE_LIST
7783 && TREE_TYPE (init) != unknown_type_node
7784 && !MAYBE_CLASS_TYPE_P (type))
7786 gcc_assert (TREE_CODE (decl) != RESULT_DECL);
7788 /* We get here with code like `int a (2);' */
7789 init = build_x_compound_expr_from_list (init, ELK_INIT,
7790 tf_warning_or_error);
7793 /* If DECL has an array type without a specific bound, deduce the
7794 array size from the initializer. */
7795 maybe_deduce_size_from_array_init (decl, init);
7796 type = TREE_TYPE (decl);
7797 if (type == error_mark_node)
7798 return NULL_TREE;
7800 if (((type_build_ctor_call (type) || CLASS_TYPE_P (type))
7801 && !(flags & LOOKUP_ALREADY_DIGESTED)
7802 && !(init && BRACE_ENCLOSED_INITIALIZER_P (init)
7803 && CP_AGGREGATE_TYPE_P (type)
7804 && (CLASS_TYPE_P (type)
7805 /* The call to build_aggr_init below could end up
7806 calling build_vec_init, which may break when we
7807 are processing a template. */
7808 || processing_template_decl
7809 || !TYPE_NEEDS_CONSTRUCTING (type)
7810 || type_has_extended_temps (type))))
7811 || (DECL_DECOMPOSITION_P (decl) && TREE_CODE (type) == ARRAY_TYPE))
7813 init_code = build_aggr_init_full_exprs (decl, init, flags);
7815 /* A constructor call is a non-trivial initializer even if
7816 it isn't explicitly written. */
7817 if (TREE_SIDE_EFFECTS (init_code))
7818 DECL_NONTRIVIALLY_INITIALIZED_P (decl) = true;
7820 /* If this is a constexpr initializer, expand_default_init will
7821 have returned an INIT_EXPR rather than a CALL_EXPR. In that
7822 case, pull the initializer back out and pass it down into
7823 store_init_value. */
7824 while (true)
7826 if (TREE_CODE (init_code) == EXPR_STMT
7827 || TREE_CODE (init_code) == STMT_EXPR
7828 || TREE_CODE (init_code) == CONVERT_EXPR)
7829 init_code = TREE_OPERAND (init_code, 0);
7830 else if (TREE_CODE (init_code) == BIND_EXPR)
7831 init_code = BIND_EXPR_BODY (init_code);
7832 else
7833 break;
7835 if (TREE_CODE (init_code) == INIT_EXPR)
7837 /* In C++20, the call to build_aggr_init could have created
7838 an INIT_EXPR with a CONSTRUCTOR as the RHS to handle
7839 A(1, 2). */
7840 tree rhs = TREE_OPERAND (init_code, 1);
7841 if (processing_template_decl && TREE_CODE (rhs) == TARGET_EXPR)
7842 /* Avoid leaking TARGET_EXPR into template trees. */
7843 rhs = build_implicit_conv_flags (type, init, flags);
7844 init = rhs;
7846 init_code = NULL_TREE;
7847 /* Don't call digest_init; it's unnecessary and will complain
7848 about aggregate initialization of non-aggregate classes. */
7849 flags |= LOOKUP_ALREADY_DIGESTED;
7851 else if (DECL_DECLARED_CONSTEXPR_P (decl)
7852 || DECL_DECLARED_CONSTINIT_P (decl))
7854 /* Declared constexpr or constinit, but no suitable initializer;
7855 massage init appropriately so we can pass it into
7856 store_init_value for the error. */
7857 tree new_init = NULL_TREE;
7858 if (!processing_template_decl
7859 && TREE_CODE (init_code) == CALL_EXPR)
7860 new_init = build_cplus_new (type, init_code, tf_none);
7861 else if (CLASS_TYPE_P (type)
7862 && (!init || TREE_CODE (init) == TREE_LIST))
7863 new_init = build_functional_cast (input_location, type,
7864 init, tf_none);
7865 if (new_init)
7867 init = new_init;
7868 if (TREE_CODE (init) == TARGET_EXPR
7869 && !(flags & LOOKUP_ONLYCONVERTING))
7870 TARGET_EXPR_DIRECT_INIT_P (init) = true;
7872 init_code = NULL_TREE;
7874 else
7875 init = NULL_TREE;
7878 if (init && TREE_CODE (init) != TREE_VEC)
7880 init_code = store_init_value (decl, init, cleanups, flags);
7882 if (DECL_INITIAL (decl)
7883 && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
7884 && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl))))
7886 tree elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ().value;
7887 if (TREE_CODE (TREE_TYPE (elt)) == ARRAY_TYPE
7888 && TYPE_SIZE (TREE_TYPE (elt)) == NULL_TREE)
7889 cp_complete_array_type (&TREE_TYPE (elt), elt, false);
7892 if (pedantic && TREE_CODE (type) == ARRAY_TYPE
7893 && DECL_INITIAL (decl)
7894 && TREE_CODE (DECL_INITIAL (decl)) == STRING_CST
7895 && PAREN_STRING_LITERAL_P (DECL_INITIAL (decl)))
7896 warning_at (cp_expr_loc_or_loc (DECL_INITIAL (decl),
7897 DECL_SOURCE_LOCATION (decl)),
7898 0, "array %qD initialized by parenthesized "
7899 "string literal %qE",
7900 decl, DECL_INITIAL (decl));
7901 init = NULL_TREE;
7904 else
7906 if (CLASS_TYPE_P (core_type = strip_array_types (type))
7907 && (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type)
7908 || CLASSTYPE_REF_FIELDS_NEED_INIT (core_type)))
7909 diagnose_uninitialized_cst_or_ref_member (core_type, /*using_new=*/false,
7910 /*complain=*/true);
7912 check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
7913 tf_warning_or_error);
7916 if (init && init != error_mark_node)
7917 init_code = cp_build_init_expr (decl, init);
7919 if (init_code && !TREE_SIDE_EFFECTS (init_code)
7920 && init_code != error_mark_node)
7921 init_code = NULL_TREE;
7923 if (init_code)
7925 /* We might have set these in cp_finish_decl. */
7926 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = false;
7927 TREE_CONSTANT (decl) = false;
7930 if (init_code
7931 && DECL_IN_AGGR_P (decl)
7932 && DECL_INITIALIZED_IN_CLASS_P (decl))
7934 static int explained = 0;
7936 auto_diagnostic_group d;
7937 if (cxx_dialect < cxx11)
7938 error ("initializer invalid for static member with constructor");
7939 else if (cxx_dialect < cxx17)
7940 error ("non-constant in-class initialization invalid for static "
7941 "member %qD", decl);
7942 else
7943 error ("non-constant in-class initialization invalid for non-inline "
7944 "static member %qD", decl);
7945 if (!explained)
7947 inform (input_location,
7948 "(an out of class initialization is required)");
7949 explained = 1;
7951 return NULL_TREE;
7954 return init_code;
7957 /* If DECL is not a local variable, give it RTL. */
7959 static void
7960 make_rtl_for_nonlocal_decl (tree decl, tree init, const char* asmspec)
7962 int toplev = toplevel_bindings_p ();
7963 int defer_p;
7965 /* Set the DECL_ASSEMBLER_NAME for the object. */
7966 if (asmspec)
7968 /* The `register' keyword, when used together with an
7969 asm-specification, indicates that the variable should be
7970 placed in a particular register. */
7971 if (VAR_P (decl) && DECL_REGISTER (decl))
7973 set_user_assembler_name (decl, asmspec);
7974 DECL_HARD_REGISTER (decl) = 1;
7976 else
7978 if (TREE_CODE (decl) == FUNCTION_DECL
7979 && fndecl_built_in_p (decl, BUILT_IN_NORMAL))
7980 set_builtin_user_assembler_name (decl, asmspec);
7981 set_user_assembler_name (decl, asmspec);
7982 if (DECL_LOCAL_DECL_P (decl))
7983 if (auto ns_decl = DECL_LOCAL_DECL_ALIAS (decl))
7984 /* We have to propagate the name to the ns-alias.
7985 This is horrible, as we're affecting a
7986 possibly-shared decl. Again, a one-true-decl
7987 model breaks down. */
7988 if (ns_decl != error_mark_node)
7989 set_user_assembler_name (ns_decl, asmspec);
7993 /* Handle non-variables up front. */
7994 if (!VAR_P (decl))
7996 rest_of_decl_compilation (decl, toplev, at_eof);
7997 return;
8000 /* If we see a class member here, it should be a static data
8001 member. */
8002 if (DECL_LANG_SPECIFIC (decl) && DECL_IN_AGGR_P (decl))
8004 gcc_assert (TREE_STATIC (decl));
8005 /* An in-class declaration of a static data member should be
8006 external; it is only a declaration, and not a definition. */
8007 if (init == NULL_TREE)
8008 gcc_assert (DECL_EXTERNAL (decl)
8009 || !TREE_PUBLIC (decl));
8012 /* We don't create any RTL for local variables. */
8013 if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
8014 return;
8016 /* We defer emission of local statics until the corresponding
8017 DECL_EXPR is expanded. But with constexpr its function might never
8018 be expanded, so go ahead and tell cgraph about the variable now. */
8019 defer_p = ((DECL_FUNCTION_SCOPE_P (decl)
8020 && !var_in_maybe_constexpr_fn (decl))
8021 || DECL_VIRTUAL_P (decl));
8023 /* Defer template instantiations. */
8024 if (DECL_LANG_SPECIFIC (decl)
8025 && DECL_IMPLICIT_INSTANTIATION (decl))
8026 defer_p = 1;
8028 /* If we're not deferring, go ahead and assemble the variable. */
8029 if (!defer_p)
8030 rest_of_decl_compilation (decl, toplev, at_eof);
8033 /* walk_tree helper for wrap_temporary_cleanups, below. */
8035 static tree
8036 wrap_cleanups_r (tree *stmt_p, int *walk_subtrees, void *data)
8038 /* Stop at types or full-expression boundaries. */
8039 if (TYPE_P (*stmt_p)
8040 || TREE_CODE (*stmt_p) == CLEANUP_POINT_EXPR)
8042 *walk_subtrees = 0;
8043 return NULL_TREE;
8046 if (TREE_CODE (*stmt_p) == TARGET_EXPR)
8048 tree guard = (tree)data;
8049 tree tcleanup = TARGET_EXPR_CLEANUP (*stmt_p);
8051 if (tcleanup && !CLEANUP_EH_ONLY (*stmt_p)
8052 && !expr_noexcept_p (tcleanup, tf_none))
8054 tcleanup = build2 (TRY_CATCH_EXPR, void_type_node, tcleanup, guard);
8055 /* Tell honor_protect_cleanup_actions to handle this as a separate
8056 cleanup. */
8057 TRY_CATCH_IS_CLEANUP (tcleanup) = 1;
8058 TARGET_EXPR_CLEANUP (*stmt_p) = tcleanup;
8062 return NULL_TREE;
8065 /* We're initializing a local variable which has a cleanup GUARD. If there
8066 are any temporaries used in the initializer INIT of this variable, we
8067 need to wrap their cleanups with TRY_CATCH_EXPR (, GUARD) so that the
8068 variable will be cleaned up properly if one of them throws.
8070 Unfortunately, there's no way to express this properly in terms of
8071 nesting, as the regions for the temporaries overlap the region for the
8072 variable itself; if there are two temporaries, the variable needs to be
8073 the first thing destroyed if either of the temporary destructors throws.
8074 However, we only want to run the variable's cleanup if it actually got
8075 constructed. So we need to guard the temporary cleanups with the
8076 variable's cleanup if they are run on the normal path, but not if they
8077 are run on the exceptional path. We implement this by telling
8078 honor_protect_cleanup_actions to strip the variable cleanup from the
8079 exceptional path.
8081 Another approach could be to make the variable cleanup region enclose
8082 initialization, but depend on a flag to indicate that the variable is
8083 initialized; that's effectively what we do for arrays. But the current
8084 approach works fine for non-arrays, and has no code overhead in the usual
8085 case where the temporary destructors are noexcept. */
8087 static void
8088 wrap_temporary_cleanups (tree init, tree guard)
8090 if (TREE_CODE (guard) == BIND_EXPR)
8092 /* An array cleanup region already encloses any temporary cleanups,
8093 don't wrap it around them again. */
8094 gcc_checking_assert (BIND_EXPR_VEC_DTOR (guard));
8095 return;
8097 cp_walk_tree_without_duplicates (&init, wrap_cleanups_r, (void *)guard);
8100 /* Generate code to initialize DECL (a local variable). */
8102 static void
8103 initialize_local_var (tree decl, tree init, bool decomp)
8105 tree type = TREE_TYPE (decl);
8106 tree cleanup;
8107 int already_used;
8109 gcc_assert (VAR_P (decl) || TREE_CODE (decl) == RESULT_DECL);
8110 gcc_assert (!TREE_STATIC (decl));
8112 if (DECL_SIZE (decl) == NULL_TREE)
8114 /* If we used it already as memory, it must stay in memory. */
8115 DECL_INITIAL (decl) = NULL_TREE;
8116 TREE_ADDRESSABLE (decl) = TREE_USED (decl);
8117 return;
8120 if (type == error_mark_node)
8121 return;
8123 /* Compute and store the initial value. */
8124 already_used = TREE_USED (decl) || TREE_USED (type);
8125 if (TREE_USED (type))
8126 DECL_READ_P (decl) = 1;
8128 /* Generate a cleanup, if necessary. */
8129 cleanup = (decomp ? NULL_TREE
8130 : cxx_maybe_build_cleanup (decl, tf_warning_or_error));
8132 /* Perform the initialization. */
8133 if (init)
8135 tree rinit = (TREE_CODE (init) == INIT_EXPR
8136 ? TREE_OPERAND (init, 1) : NULL_TREE);
8137 if (rinit && !TREE_SIDE_EFFECTS (rinit)
8138 && TREE_OPERAND (init, 0) == decl)
8140 /* Stick simple initializers in DECL_INITIAL so that
8141 -Wno-init-self works (c++/34772). */
8142 DECL_INITIAL (decl) = rinit;
8144 if (warn_init_self && TYPE_REF_P (type))
8146 STRIP_NOPS (rinit);
8147 if (rinit == decl)
8148 warning_at (DECL_SOURCE_LOCATION (decl),
8149 OPT_Winit_self,
8150 "reference %qD is initialized with itself", decl);
8153 else
8155 int saved_stmts_are_full_exprs_p;
8157 /* If we're only initializing a single object, guard the
8158 destructors of any temporaries used in its initializer with
8159 its destructor. */
8160 if (cleanup)
8161 wrap_temporary_cleanups (init, cleanup);
8163 gcc_assert (building_stmt_list_p ());
8164 saved_stmts_are_full_exprs_p = stmts_are_full_exprs_p ();
8165 /* Avoid CLEANUP_POINT_EXPR for the structured binding
8166 bases, those will have CLEANUP_POINT_EXPR at the end of
8167 code emitted by cp_finish_decomp. */
8168 if (decomp)
8169 current_stmt_tree ()->stmts_are_full_exprs_p = 0;
8170 /* P2718R0 - avoid CLEANUP_POINT_EXPR for range-for-initializer,
8171 temporaries from there should have lifetime extended. */
8172 else if (DECL_NAME (decl) == for_range__identifier
8173 && flag_range_for_ext_temps)
8174 current_stmt_tree ()->stmts_are_full_exprs_p = 0;
8175 else
8176 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
8177 finish_expr_stmt (init);
8178 current_stmt_tree ()->stmts_are_full_exprs_p
8179 = saved_stmts_are_full_exprs_p;
8183 /* Set this to 0 so we can tell whether an aggregate which was
8184 initialized was ever used. Don't do this if it has a
8185 destructor, so we don't complain about the 'resource
8186 allocation is initialization' idiom. Now set
8187 attribute((unused)) on types so decls of that type will be
8188 marked used. (see TREE_USED, above.) */
8189 if (TYPE_NEEDS_CONSTRUCTING (type)
8190 && ! already_used
8191 && TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
8192 && DECL_NAME (decl))
8193 TREE_USED (decl) = 0;
8194 else if (already_used)
8195 TREE_USED (decl) = 1;
8197 if (cleanup)
8198 finish_decl_cleanup (decl, cleanup);
8201 /* DECL is a VAR_DECL for a compiler-generated variable with static
8202 storage duration (like a virtual table) whose initializer is a
8203 compile-time constant. Initialize the variable and provide it to the
8204 back end. */
8206 void
8207 initialize_artificial_var (tree decl, vec<constructor_elt, va_gc> *v)
8209 tree init;
8210 gcc_assert (DECL_ARTIFICIAL (decl));
8211 init = build_constructor (TREE_TYPE (decl), v);
8212 gcc_assert (TREE_CODE (init) == CONSTRUCTOR);
8213 DECL_INITIAL (decl) = init;
8214 DECL_INITIALIZED_P (decl) = 1;
8215 /* Mark the decl as constexpr so that we can access its content
8216 at compile time. */
8217 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
8218 DECL_DECLARED_CONSTEXPR_P (decl) = true;
8219 determine_visibility (decl);
8220 layout_var_decl (decl);
8221 maybe_commonize_var (decl);
8222 make_rtl_for_nonlocal_decl (decl, init, /*asmspec=*/NULL);
8225 /* INIT is the initializer for a variable, as represented by the
8226 parser. Returns true iff INIT is value-dependent. */
8228 static bool
8229 value_dependent_init_p (tree init)
8231 if (TREE_CODE (init) == TREE_LIST)
8232 /* A parenthesized initializer, e.g.: int i (3, 2); ? */
8233 return any_value_dependent_elements_p (init);
8234 else if (TREE_CODE (init) == CONSTRUCTOR)
8235 /* A brace-enclosed initializer, e.g.: int i = { 3 }; ? */
8237 if (dependent_type_p (TREE_TYPE (init)))
8238 return true;
8240 vec<constructor_elt, va_gc> *elts;
8241 size_t nelts;
8242 size_t i;
8244 elts = CONSTRUCTOR_ELTS (init);
8245 nelts = vec_safe_length (elts);
8246 for (i = 0; i < nelts; ++i)
8247 if (value_dependent_init_p ((*elts)[i].value))
8248 return true;
8250 else
8251 /* It must be a simple expression, e.g., int i = 3; */
8252 return value_dependent_expression_p (init);
8254 return false;
8257 /* A helper function to be called via walk_tree. If any label exists
8258 under *TP, it is (going to be) forced. Set has_forced_label_in_static. */
8260 static tree
8261 notice_forced_label_r (tree *tp, int *walk_subtrees, void *)
8263 if (TYPE_P (*tp))
8264 *walk_subtrees = 0;
8265 if (TREE_CODE (*tp) == LABEL_DECL)
8266 cfun->has_forced_label_in_static = 1;
8267 return NULL_TREE;
8270 /* Return true if DECL has either a trivial destructor, or for C++20
8271 is constexpr and has a constexpr destructor. */
8273 static bool
8274 decl_maybe_constant_destruction (tree decl, tree type)
8276 return (TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
8277 || (cxx_dialect >= cxx20
8278 && VAR_P (decl)
8279 && DECL_DECLARED_CONSTEXPR_P (decl)
8280 && type_has_constexpr_destructor (strip_array_types (type))));
8283 static tree declare_simd_adjust_this (tree *, int *, void *);
8285 /* Helper function of omp_declare_variant_finalize. Finalize one
8286 "omp declare variant base" attribute. Return true if it should be
8287 removed. */
8289 static bool
8290 omp_declare_variant_finalize_one (tree decl, tree attr)
8292 if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
8294 walk_tree (&TREE_VALUE (TREE_VALUE (attr)), declare_simd_adjust_this,
8295 DECL_ARGUMENTS (decl), NULL);
8296 walk_tree (&TREE_PURPOSE (TREE_VALUE (attr)), declare_simd_adjust_this,
8297 DECL_ARGUMENTS (decl), NULL);
8300 tree ctx = TREE_VALUE (TREE_VALUE (attr));
8301 tree simd = omp_get_context_selector (ctx, OMP_TRAIT_SET_CONSTRUCT,
8302 OMP_TRAIT_CONSTRUCT_SIMD);
8303 if (simd)
8305 TREE_VALUE (simd)
8306 = c_omp_declare_simd_clauses_to_numbers (DECL_ARGUMENTS (decl),
8307 OMP_TS_PROPERTIES (simd));
8308 /* FIXME, adjusting simd args unimplemented. */
8309 return true;
8312 tree chain = TREE_CHAIN (TREE_VALUE (attr));
8313 location_t varid_loc
8314 = cp_expr_loc_or_input_loc (TREE_PURPOSE (TREE_CHAIN (chain)));
8315 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
8316 cp_id_kind idk = (cp_id_kind) tree_to_uhwi (TREE_VALUE (chain));
8317 tree variant = TREE_PURPOSE (TREE_VALUE (attr));
8319 location_t save_loc = input_location;
8320 input_location = varid_loc;
8322 releasing_vec args;
8323 tree parm = DECL_ARGUMENTS (decl);
8324 if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
8325 parm = DECL_CHAIN (parm);
8326 for (; parm; parm = DECL_CHAIN (parm))
8327 if (type_dependent_expression_p (parm))
8328 vec_safe_push (args, build_constructor (TREE_TYPE (parm), NULL));
8329 else if (MAYBE_CLASS_TYPE_P (TREE_TYPE (parm)))
8330 vec_safe_push (args, build_local_temp (TREE_TYPE (parm)));
8331 else
8332 vec_safe_push (args, build_zero_cst (TREE_TYPE (parm)));
8334 bool koenig_p = false;
8335 if (idk == CP_ID_KIND_UNQUALIFIED || idk == CP_ID_KIND_TEMPLATE_ID)
8337 if (identifier_p (variant)
8338 /* In C++20, we may need to perform ADL for a template
8339 name. */
8340 || (TREE_CODE (variant) == TEMPLATE_ID_EXPR
8341 && identifier_p (TREE_OPERAND (variant, 0))))
8343 if (!args->is_empty ())
8345 koenig_p = true;
8346 if (!any_type_dependent_arguments_p (args))
8347 variant = perform_koenig_lookup (variant, args,
8348 tf_warning_or_error);
8350 else
8351 variant = unqualified_fn_lookup_error (variant);
8353 else if (!args->is_empty () && is_overloaded_fn (variant))
8355 tree fn = get_first_fn (variant);
8356 fn = STRIP_TEMPLATE (fn);
8357 if (!((TREE_CODE (fn) == USING_DECL && DECL_DEPENDENT_P (fn))
8358 || DECL_FUNCTION_MEMBER_P (fn)
8359 || DECL_LOCAL_DECL_P (fn)))
8361 koenig_p = true;
8362 if (!any_type_dependent_arguments_p (args))
8363 variant = perform_koenig_lookup (variant, args,
8364 tf_warning_or_error);
8369 if (idk == CP_ID_KIND_QUALIFIED)
8370 variant = finish_call_expr (variant, &args, /*disallow_virtual=*/true,
8371 koenig_p, tf_warning_or_error);
8372 else
8373 variant = finish_call_expr (variant, &args, /*disallow_virtual=*/false,
8374 koenig_p, tf_warning_or_error);
8375 if (variant == error_mark_node && !processing_template_decl)
8376 return true;
8378 variant = cp_get_callee_fndecl_nofold (variant);
8379 input_location = save_loc;
8381 if (variant)
8383 const char *varname = IDENTIFIER_POINTER (DECL_NAME (variant));
8384 if (!comptypes (TREE_TYPE (decl), TREE_TYPE (variant), 0))
8386 error_at (varid_loc, "variant %qD and base %qD have incompatible "
8387 "types", variant, decl);
8388 return true;
8390 if (fndecl_built_in_p (variant)
8391 && (startswith (varname, "__builtin_")
8392 || startswith (varname, "__sync_")
8393 || startswith (varname, "__atomic_")))
8395 error_at (varid_loc, "variant %qD is a built-in", variant);
8396 return true;
8398 else
8400 tree construct
8401 = omp_get_context_selector_list (ctx, OMP_TRAIT_SET_CONSTRUCT);
8402 omp_mark_declare_variant (match_loc, variant, construct);
8403 if (!omp_context_selector_matches (ctx))
8404 return true;
8405 TREE_PURPOSE (TREE_VALUE (attr)) = variant;
8408 else if (!processing_template_decl)
8410 error_at (varid_loc, "could not find variant declaration");
8411 return true;
8414 return false;
8417 /* Helper function, finish up "omp declare variant base" attribute
8418 now that there is a DECL. ATTR is the first "omp declare variant base"
8419 attribute. */
8421 void
8422 omp_declare_variant_finalize (tree decl, tree attr)
8424 size_t attr_len = strlen ("omp declare variant base");
8425 tree *list = &DECL_ATTRIBUTES (decl);
8426 bool remove_all = false;
8427 location_t match_loc = DECL_SOURCE_LOCATION (decl);
8428 if (TREE_CHAIN (TREE_VALUE (attr))
8429 && TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))
8430 && EXPR_HAS_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))))
8431 match_loc = EXPR_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr))));
8432 if (DECL_CONSTRUCTOR_P (decl))
8434 error_at (match_loc, "%<declare variant%> on constructor %qD", decl);
8435 remove_all = true;
8437 else if (DECL_DESTRUCTOR_P (decl))
8439 error_at (match_loc, "%<declare variant%> on destructor %qD", decl);
8440 remove_all = true;
8442 else if (DECL_DEFAULTED_FN (decl))
8444 error_at (match_loc, "%<declare variant%> on defaulted %qD", decl);
8445 remove_all = true;
8447 else if (DECL_DELETED_FN (decl))
8449 error_at (match_loc, "%<declare variant%> on deleted %qD", decl);
8450 remove_all = true;
8452 else if (DECL_VIRTUAL_P (decl))
8454 error_at (match_loc, "%<declare variant%> on virtual %qD", decl);
8455 remove_all = true;
8457 /* This loop is like private_lookup_attribute, except that it works
8458 with tree * rather than tree, as we might want to remove the
8459 attributes that are diagnosed as errorneous. */
8460 while (*list)
8462 tree attr = get_attribute_name (*list);
8463 size_t ident_len = IDENTIFIER_LENGTH (attr);
8464 if (cmp_attribs ("omp declare variant base", attr_len,
8465 IDENTIFIER_POINTER (attr), ident_len))
8467 if (remove_all || omp_declare_variant_finalize_one (decl, *list))
8469 *list = TREE_CHAIN (*list);
8470 continue;
8473 list = &TREE_CHAIN (*list);
8477 static void cp_maybe_mangle_decomp (tree, cp_decomp *);
8479 /* Finish processing of a declaration;
8480 install its line number and initial value.
8481 If the length of an array type is not known before,
8482 it must be determined now, from the initial value, or it is an error.
8484 INIT is the initializer (if any) for DECL. If INIT_CONST_EXPR_P is
8485 true, then INIT is an integral constant expression.
8487 FLAGS is LOOKUP_ONLYCONVERTING if the = init syntax was used, else 0
8488 if the (init) syntax was used.
8490 DECOMP is first identifier's DECL and identifier count in a structured
8491 bindings, nullptr if not a structured binding. */
8493 void
8494 cp_finish_decl (tree decl, tree init, bool init_const_expr_p,
8495 tree asmspec_tree, int flags, cp_decomp *decomp)
8497 vec<tree, va_gc> *cleanups = NULL;
8498 const char *asmspec = NULL;
8499 int was_readonly = 0;
8500 bool var_definition_p = false;
8501 tree auto_node;
8502 auto_vec<tree> extra_cleanups;
8503 struct decomp_cleanup {
8504 tree decl;
8505 cp_decomp *&decomp;
8506 ~decomp_cleanup ()
8508 if (decomp && DECL_DECOMPOSITION_P (decl))
8509 cp_finish_decomp (decl, decomp);
8511 } decomp_cl = { decl, decomp };
8513 if (decl == error_mark_node)
8514 return;
8515 else if (! decl)
8517 if (init)
8518 error ("assignment (not initialization) in declaration");
8519 return;
8522 gcc_assert (TREE_CODE (decl) != RESULT_DECL);
8523 /* Parameters are handled by store_parm_decls, not cp_finish_decl. */
8524 gcc_assert (TREE_CODE (decl) != PARM_DECL);
8526 tree type = TREE_TYPE (decl);
8527 if (type == error_mark_node)
8528 return;
8530 if (VAR_P (decl) && is_copy_initialization (init))
8531 flags |= LOOKUP_ONLYCONVERTING;
8533 /* Warn about register storage specifiers except when in GNU global
8534 or local register variable extension. */
8535 if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec_tree == NULL_TREE)
8537 if (cxx_dialect >= cxx17)
8538 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
8539 "ISO C++17 does not allow %<register%> storage "
8540 "class specifier");
8541 else
8542 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
8543 "%<register%> storage class specifier used");
8546 /* If a name was specified, get the string. */
8547 if (at_namespace_scope_p ())
8548 asmspec_tree = maybe_apply_renaming_pragma (decl, asmspec_tree);
8549 if (asmspec_tree && asmspec_tree != error_mark_node)
8550 asmspec = TREE_STRING_POINTER (asmspec_tree);
8552 bool in_class_decl
8553 = (current_class_type
8554 && CP_DECL_CONTEXT (decl) == current_class_type
8555 && TYPE_BEING_DEFINED (current_class_type)
8556 && !CLASSTYPE_TEMPLATE_INSTANTIATION (current_class_type));
8558 if (in_class_decl
8559 && (DECL_INITIAL (decl) || init))
8560 DECL_INITIALIZED_IN_CLASS_P (decl) = 1;
8562 if (VAR_P (decl)
8563 && (auto_node = type_uses_auto (type)))
8565 tree d_init;
8566 if (init == NULL_TREE)
8568 if (DECL_LANG_SPECIFIC (decl)
8569 && DECL_TEMPLATE_INSTANTIATION (decl)
8570 && !DECL_TEMPLATE_INSTANTIATED (decl))
8572 /* init is null because we're deferring instantiating the
8573 initializer until we need it. Well, we need it now. */
8574 instantiate_decl (decl, /*defer_ok*/true, /*expl*/false);
8575 return;
8578 if (CLASS_PLACEHOLDER_TEMPLATE (auto_node))
8579 /* Class deduction with no initializer is OK. */;
8580 else
8582 /* Ordinary auto deduction without an initializer, a situation
8583 which grokdeclarator already detects and rejects for the most
8584 part. But we can still get here if we're instantiating a
8585 variable template before we've fully parsed (and attached) its
8586 initializer, e.g. template<class> auto x = x<int>; */
8587 error_at (DECL_SOURCE_LOCATION (decl),
8588 "declaration of %q#D has no initializer", decl);
8589 TREE_TYPE (decl) = error_mark_node;
8590 return;
8593 d_init = init;
8594 if (d_init)
8596 if (TREE_CODE (d_init) == TREE_LIST
8597 && !CLASS_PLACEHOLDER_TEMPLATE (auto_node))
8598 d_init = build_x_compound_expr_from_list (d_init, ELK_INIT,
8599 tf_warning_or_error);
8600 d_init = resolve_nondeduced_context (d_init, tf_warning_or_error);
8601 /* Force auto deduction now. Use tf_none to avoid redundant warnings
8602 on deprecated-14.C. */
8603 mark_single_function (d_init, tf_none);
8605 enum auto_deduction_context adc = adc_variable_type;
8606 if (DECL_DECOMPOSITION_P (decl))
8607 adc = adc_decomp_type;
8608 tree outer_targs = NULL_TREE;
8609 if (PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node)
8610 && DECL_LANG_SPECIFIC (decl)
8611 && DECL_TEMPLATE_INFO (decl)
8612 && !DECL_FUNCTION_SCOPE_P (decl))
8613 /* The outer template arguments might be needed for satisfaction.
8614 (For function scope variables, do_auto_deduction will obtain the
8615 outer template arguments from current_function_decl.) */
8616 outer_targs = DECL_TI_ARGS (decl);
8617 type = TREE_TYPE (decl) = do_auto_deduction (type, d_init, auto_node,
8618 tf_warning_or_error, adc,
8619 outer_targs, flags);
8620 if (type == error_mark_node)
8621 return;
8622 if (TREE_CODE (type) == FUNCTION_TYPE)
8624 error ("initializer for %<decltype(auto) %D%> has function type; "
8625 "did you forget the %<()%>?", decl);
8626 TREE_TYPE (decl) = error_mark_node;
8627 return;
8629 /* As in start_decl_1, complete so TREE_READONLY is set properly. */
8630 if (!processing_template_decl
8631 && !type_uses_auto (type)
8632 && !COMPLETE_TYPE_P (complete_type (type)))
8634 auto_diagnostic_group d;
8635 error_at (location_of (decl),
8636 "deduced type %qT for %qD is incomplete", type, decl);
8637 cxx_incomplete_type_inform (type);
8638 TREE_TYPE (decl) = error_mark_node;
8639 return;
8641 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
8643 /* Update the type of the corresponding TEMPLATE_DECL to match. */
8644 if (DECL_LANG_SPECIFIC (decl)
8645 && DECL_TEMPLATE_INFO (decl)
8646 && DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (decl)) == decl)
8647 TREE_TYPE (DECL_TI_TEMPLATE (decl)) = type;
8650 if (ensure_literal_type_for_constexpr_object (decl) == error_mark_node)
8652 DECL_DECLARED_CONSTEXPR_P (decl) = 0;
8653 if (VAR_P (decl) && DECL_CLASS_SCOPE_P (decl))
8655 init = NULL_TREE;
8656 DECL_EXTERNAL (decl) = 1;
8660 if (VAR_P (decl)
8661 && DECL_CLASS_SCOPE_P (decl)
8662 && verify_type_context (DECL_SOURCE_LOCATION (decl),
8663 TCTX_STATIC_STORAGE, type)
8664 && DECL_INITIALIZED_IN_CLASS_P (decl))
8665 check_static_variable_definition (decl, type);
8667 if (!processing_template_decl && VAR_P (decl) && is_global_var (decl))
8669 type_context_kind context = (DECL_THREAD_LOCAL_P (decl)
8670 ? TCTX_THREAD_STORAGE
8671 : TCTX_STATIC_STORAGE);
8672 verify_type_context (input_location, context, TREE_TYPE (decl));
8675 if (init && TREE_CODE (decl) == FUNCTION_DECL)
8677 tree clone;
8678 if (init == ridpointers[(int)RID_DELETE]
8679 || (TREE_CODE (init) == STRING_CST
8680 && TREE_TYPE (init) == ridpointers[(int)RID_DELETE]))
8682 /* FIXME check this is 1st decl. */
8683 if (UNLIKELY (DECL_MAIN_P (decl)))
8685 /* [basic.start.main]/3: A program that defines main as deleted
8686 is ill-formed. */
8687 error ("%<::main%> cannot be deleted");
8688 DECL_INITIAL (decl) = NULL_TREE;
8690 else
8692 DECL_DELETED_FN (decl) = 1;
8693 DECL_DECLARED_INLINE_P (decl) = 1;
8694 DECL_INITIAL (decl)
8695 = TREE_CODE (init) == STRING_CST ? init : error_mark_node;
8696 FOR_EACH_CLONE (clone, decl)
8698 DECL_DELETED_FN (clone) = 1;
8699 DECL_DECLARED_INLINE_P (clone) = 1;
8700 DECL_INITIAL (clone) = DECL_INITIAL (decl);
8703 init = NULL_TREE;
8705 else if (init == ridpointers[(int)RID_DEFAULT])
8707 if (defaultable_fn_check (decl))
8708 DECL_DEFAULTED_FN (decl) = 1;
8709 else
8710 DECL_INITIAL (decl) = NULL_TREE;
8714 if (init && VAR_P (decl))
8716 DECL_NONTRIVIALLY_INITIALIZED_P (decl) = 1;
8717 /* If DECL is a reference, then we want to know whether init is a
8718 reference constant; init_const_expr_p as passed tells us whether
8719 it's an rvalue constant. */
8720 if (TYPE_REF_P (type))
8721 init_const_expr_p = potential_constant_expression (init);
8722 if (init_const_expr_p)
8724 /* Set these flags now for templates. We'll update the flags in
8725 store_init_value for instantiations. */
8726 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
8727 if (decl_maybe_constant_var_p (decl)
8728 /* FIXME setting TREE_CONSTANT on refs breaks the back end. */
8729 && !TYPE_REF_P (type))
8730 TREE_CONSTANT (decl) = true;
8732 /* This is handled mostly by gimplify.cc, but we have to deal with
8733 not warning about int x = x; as it is a GCC extension to turn off
8734 this warning but only if warn_init_self is zero. */
8735 if (!DECL_EXTERNAL (decl)
8736 && !TREE_STATIC (decl)
8737 && decl == tree_strip_any_location_wrapper (init)
8738 && !warning_enabled_at (DECL_SOURCE_LOCATION (decl), OPT_Winit_self))
8739 suppress_warning (decl, OPT_Winit_self);
8741 else if (VAR_P (decl)
8742 && COMPLETE_TYPE_P (type)
8743 && !TYPE_REF_P (type)
8744 && !dependent_type_p (type)
8745 && is_really_empty_class (type, /*ignore_vptr*/false))
8746 /* We have no initializer but there's nothing to initialize anyway.
8747 Treat DECL as constant due to c++/109876. */
8748 TREE_CONSTANT (decl) = true;
8750 if (flag_openmp
8751 && TREE_CODE (decl) == FUNCTION_DECL
8752 /* #pragma omp declare variant on methods handled in finish_struct
8753 instead. */
8754 && (!DECL_OBJECT_MEMBER_FUNCTION_P (decl)
8755 || COMPLETE_TYPE_P (DECL_CONTEXT (decl))))
8756 if (tree attr = lookup_attribute ("omp declare variant base",
8757 DECL_ATTRIBUTES (decl)))
8758 omp_declare_variant_finalize (decl, attr);
8760 if (processing_template_decl)
8762 bool type_dependent_p;
8764 /* Add this declaration to the statement-tree. */
8765 if (at_function_scope_p ())
8766 add_decl_expr (decl);
8768 type_dependent_p = dependent_type_p (type);
8770 if (check_for_bare_parameter_packs (init))
8772 init = NULL_TREE;
8773 DECL_INITIAL (decl) = NULL_TREE;
8776 /* Generally, initializers in templates are expanded when the
8777 template is instantiated. But, if DECL is a variable constant
8778 then it can be used in future constant expressions, so its value
8779 must be available. */
8781 bool dep_init = false;
8783 if (!VAR_P (decl) || type_dependent_p)
8784 /* We can't do anything if the decl has dependent type. */;
8785 else if (init
8786 && (init_const_expr_p || DECL_DECLARED_CONSTEXPR_P (decl))
8787 && !TYPE_REF_P (type)
8788 && decl_maybe_constant_var_p (decl)
8789 && !(dep_init = value_dependent_init_p (init)))
8791 /* This variable seems to be a non-dependent constant, so process
8792 its initializer. If check_initializer returns non-null the
8793 initialization wasn't constant after all. */
8794 tree init_code;
8795 cleanups = make_tree_vector ();
8796 init_code = check_initializer (decl, init, flags, &cleanups);
8797 if (init_code == NULL_TREE)
8798 init = NULL_TREE;
8799 release_tree_vector (cleanups);
8801 else
8803 gcc_assert (!DECL_PRETTY_FUNCTION_P (decl));
8804 /* Try to deduce array size. */
8805 maybe_deduce_size_from_array_init (decl, init);
8806 /* And complain about multiple initializers. */
8807 if (init && TREE_CODE (init) == TREE_LIST && TREE_CHAIN (init)
8808 && !MAYBE_CLASS_TYPE_P (type))
8809 init = build_x_compound_expr_from_list (init, ELK_INIT,
8810 tf_warning_or_error);
8813 if (init)
8814 DECL_INITIAL (decl) = init;
8816 if (dep_init)
8818 retrofit_lang_decl (decl);
8819 SET_DECL_DEPENDENT_INIT_P (decl, true);
8822 if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec)
8824 set_user_assembler_name (decl, asmspec);
8825 DECL_HARD_REGISTER (decl) = 1;
8827 return;
8830 /* Just store non-static data member initializers for later. */
8831 if (init && TREE_CODE (decl) == FIELD_DECL)
8832 DECL_INITIAL (decl) = init;
8834 /* Take care of TYPE_DECLs up front. */
8835 if (TREE_CODE (decl) == TYPE_DECL)
8837 if (type != error_mark_node
8838 && MAYBE_CLASS_TYPE_P (type) && DECL_NAME (decl))
8840 if (TREE_TYPE (DECL_NAME (decl)) && TREE_TYPE (decl) != type)
8841 warning (0, "shadowing previous type declaration of %q#D", decl);
8842 set_identifier_type_value (DECL_NAME (decl), decl);
8845 /* If we have installed this as the canonical typedef for this
8846 type, and that type has not been defined yet, delay emitting
8847 the debug information for it, as we will emit it later. */
8848 if (TYPE_MAIN_DECL (TREE_TYPE (decl)) == decl
8849 && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
8850 TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
8852 rest_of_decl_compilation (decl, DECL_FILE_SCOPE_P (decl),
8853 at_eof);
8854 return;
8857 /* A reference will be modified here, as it is initialized. */
8858 if (! DECL_EXTERNAL (decl)
8859 && TREE_READONLY (decl)
8860 && TYPE_REF_P (type))
8862 was_readonly = 1;
8863 TREE_READONLY (decl) = 0;
8866 /* This needs to happen before extend_ref_init_temps. */
8867 if (VAR_OR_FUNCTION_DECL_P (decl))
8869 if (VAR_P (decl))
8870 maybe_commonize_var (decl);
8871 determine_visibility (decl);
8874 if (VAR_P (decl))
8876 duration_kind dk = decl_storage_duration (decl);
8877 /* [dcl.constinit]/1 "The constinit specifier shall be applied
8878 only to a declaration of a variable with static or thread storage
8879 duration." */
8880 if (DECL_DECLARED_CONSTINIT_P (decl)
8881 && !(dk == dk_thread || dk == dk_static))
8883 error_at (DECL_SOURCE_LOCATION (decl),
8884 "%<constinit%> can only be applied to a variable with "
8885 "static or thread storage duration");
8886 return;
8889 if (decomp)
8890 cp_maybe_mangle_decomp (decl, decomp);
8892 /* If this is a local variable that will need a mangled name,
8893 register it now. We must do this before processing the
8894 initializer for the variable, since the initialization might
8895 require a guard variable, and since the mangled name of the
8896 guard variable will depend on the mangled name of this
8897 variable. */
8898 if (DECL_FUNCTION_SCOPE_P (decl)
8899 && TREE_STATIC (decl)
8900 && !DECL_ARTIFICIAL (decl))
8902 /* The variable holding an anonymous union will have had its
8903 discriminator set in finish_anon_union, after which it's
8904 NAME will have been cleared. */
8905 if (DECL_NAME (decl))
8906 determine_local_discriminator (decl);
8907 /* Normally has_forced_label_in_static is set during GIMPLE
8908 lowering, but [cd]tors are never actually compiled directly.
8909 We need to set this early so we can deal with the label
8910 address extension. */
8911 if ((DECL_CONSTRUCTOR_P (current_function_decl)
8912 || DECL_DESTRUCTOR_P (current_function_decl))
8913 && init)
8915 walk_tree (&init, notice_forced_label_r, NULL, NULL);
8916 add_local_decl (cfun, decl);
8918 /* And make sure it's in the symbol table for
8919 c_parse_final_cleanups to find. */
8920 varpool_node::get_create (decl);
8923 /* Convert the initializer to the type of DECL, if we have not
8924 already initialized DECL. */
8925 if (!DECL_INITIALIZED_P (decl)
8926 /* If !DECL_EXTERNAL then DECL is being defined. In the
8927 case of a static data member initialized inside the
8928 class-specifier, there can be an initializer even if DECL
8929 is *not* defined. */
8930 && (!DECL_EXTERNAL (decl) || init))
8932 cleanups = make_tree_vector ();
8933 init = check_initializer (decl, init, flags, &cleanups);
8935 /* Handle:
8937 [dcl.init]
8939 The memory occupied by any object of static storage
8940 duration is zero-initialized at program startup before
8941 any other initialization takes place.
8943 We cannot create an appropriate initializer until after
8944 the type of DECL is finalized. If DECL_INITIAL is set,
8945 then the DECL is statically initialized, and any
8946 necessary zero-initialization has already been performed. */
8947 if (TREE_STATIC (decl) && !DECL_INITIAL (decl))
8948 DECL_INITIAL (decl) = build_zero_init (TREE_TYPE (decl),
8949 /*nelts=*/NULL_TREE,
8950 /*static_storage_p=*/true);
8951 /* Remember that the initialization for this variable has
8952 taken place. */
8953 DECL_INITIALIZED_P (decl) = 1;
8954 /* This declaration is the definition of this variable,
8955 unless we are initializing a static data member within
8956 the class specifier. */
8957 if (!DECL_EXTERNAL (decl))
8958 var_definition_p = true;
8960 /* If the variable has an array type, lay out the type, even if
8961 there is no initializer. It is valid to index through the
8962 array, and we must get TYPE_ALIGN set correctly on the array
8963 type. */
8964 else if (TREE_CODE (type) == ARRAY_TYPE)
8965 layout_type (type);
8967 if (TREE_STATIC (decl)
8968 && !at_function_scope_p ()
8969 && current_function_decl == NULL)
8970 /* So decl is a global variable or a static member of a
8971 non local class. Record the types it uses
8972 so that we can decide later to emit debug info for them. */
8973 record_types_used_by_current_var_decl (decl);
8976 /* Add this declaration to the statement-tree. This needs to happen
8977 after the call to check_initializer so that the DECL_EXPR for a
8978 reference temp is added before the DECL_EXPR for the reference itself. */
8979 if (DECL_FUNCTION_SCOPE_P (decl))
8981 /* If we're building a variable sized type, and we might be
8982 reachable other than via the top of the current binding
8983 level, then create a new BIND_EXPR so that we deallocate
8984 the object at the right time. */
8985 if (VAR_P (decl)
8986 && DECL_SIZE (decl)
8987 && !TREE_CONSTANT (DECL_SIZE (decl))
8988 && STATEMENT_LIST_HAS_LABEL (cur_stmt_list))
8990 tree bind;
8991 bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL);
8992 TREE_SIDE_EFFECTS (bind) = 1;
8993 add_stmt (bind);
8994 BIND_EXPR_BODY (bind) = push_stmt_list ();
8996 add_decl_expr (decl);
8999 tree decomp_init = NULL_TREE;
9000 /* Let the middle end know about variables and functions -- but not
9001 static data members in uninstantiated class templates. */
9002 if (VAR_OR_FUNCTION_DECL_P (decl))
9004 if (VAR_P (decl))
9006 layout_var_decl (decl);
9007 if (!flag_weak)
9008 /* Check again now that we have an initializer. */
9009 maybe_commonize_var (decl);
9010 /* A class-scope constexpr variable with an out-of-class declaration.
9011 C++17 makes them implicitly inline, but still force it out. */
9012 if (DECL_INLINE_VAR_P (decl)
9013 && !DECL_VAR_DECLARED_INLINE_P (decl)
9014 && !DECL_TEMPLATE_INSTANTIATION (decl)
9015 && !in_class_decl)
9016 mark_needed (decl);
9019 if (var_definition_p
9020 /* With -fmerge-all-constants, gimplify_init_constructor
9021 might add TREE_STATIC to aggregate variables. */
9022 && (TREE_STATIC (decl)
9023 || (flag_merge_constants >= 2
9024 && AGGREGATE_TYPE_P (type))))
9026 /* If a TREE_READONLY variable needs initialization
9027 at runtime, it is no longer readonly and we need to
9028 avoid MEM_READONLY_P being set on RTL created for it. */
9029 if (init)
9031 if (TREE_READONLY (decl))
9032 TREE_READONLY (decl) = 0;
9033 was_readonly = 0;
9035 else if (was_readonly)
9036 TREE_READONLY (decl) = 1;
9038 /* Likewise if it needs destruction. */
9039 if (!decl_maybe_constant_destruction (decl, type))
9040 TREE_READONLY (decl) = 0;
9042 else if (VAR_P (decl)
9043 && CP_DECL_THREAD_LOCAL_P (decl)
9044 && (!DECL_EXTERNAL (decl) || flag_extern_tls_init)
9045 && (was_readonly || TREE_READONLY (decl))
9046 && var_needs_tls_wrapper (decl))
9048 /* TLS variables need dynamic initialization by the TLS wrapper
9049 function, we don't want to hoist accesses to it before the
9050 wrapper. */
9051 was_readonly = 0;
9052 TREE_READONLY (decl) = 0;
9055 make_rtl_for_nonlocal_decl (decl, init, asmspec);
9057 /* Check for abstractness of the type. */
9058 if (var_definition_p)
9059 abstract_virtuals_error (decl, type);
9061 if (decomp && !cp_finish_decomp (decl, decomp, true))
9062 decomp = NULL;
9064 if (TREE_TYPE (decl) == error_mark_node)
9065 /* No initialization required. */
9067 else if (TREE_CODE (decl) == FUNCTION_DECL)
9069 if (init)
9071 if (init == ridpointers[(int)RID_DEFAULT])
9073 /* An out-of-class default definition is defined at
9074 the point where it is explicitly defaulted. */
9075 if (DECL_DELETED_FN (decl))
9076 maybe_explain_implicit_delete (decl);
9077 else if (DECL_INITIAL (decl) == error_mark_node)
9078 synthesize_method (decl);
9080 else
9081 error_at (cp_expr_loc_or_loc (init,
9082 DECL_SOURCE_LOCATION (decl)),
9083 "function %q#D is initialized like a variable",
9084 decl);
9086 /* else no initialization required. */
9088 else if (DECL_EXTERNAL (decl)
9089 && ! (DECL_LANG_SPECIFIC (decl)
9090 && DECL_NOT_REALLY_EXTERN (decl)))
9092 /* check_initializer will have done any constant initialization. */
9094 /* A variable definition. */
9095 else if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
9097 /* Initialize the local variable. */
9098 if (!decomp)
9099 initialize_local_var (decl, init, false);
9100 else
9102 tree cleanup = NULL_TREE;
9103 if (DECL_SIZE (decl))
9104 cleanup = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
9105 /* If cp_finish_decomp needs to emit any code, we need to emit that
9106 code after code emitted by initialize_local_var in a single
9107 CLEANUP_POINT_EXPR, so that temporaries are destructed only
9108 after the cp_finish_decomp emitted code.
9109 If there are any cleanups, either extend_ref_init_temps
9110 created ones or e.g. array destruction, push those first
9111 with the cleanups guarded on a bool temporary, initially
9112 set to false and set to true after initialize_local_var
9113 emitted code. */
9114 tree guard = NULL_TREE;
9115 if (cleanups || cleanup)
9117 guard = force_target_expr (boolean_type_node,
9118 boolean_false_node, tf_none);
9119 add_stmt (guard);
9120 guard = TARGET_EXPR_SLOT (guard);
9122 tree sl = push_stmt_list ();
9123 initialize_local_var (decl, init, true);
9124 if (guard)
9126 add_stmt (build2 (MODIFY_EXPR, boolean_type_node,
9127 guard, boolean_true_node));
9128 for (tree &t : *cleanups)
9129 t = build3 (COND_EXPR, void_type_node,
9130 guard, t, void_node);
9131 if (cleanup)
9132 cleanup = build3 (COND_EXPR, void_type_node,
9133 guard, cleanup, void_node);
9135 unsigned before = stmt_list_stack->length ();
9136 cp_finish_decomp (decl, decomp);
9137 decomp = NULL;
9138 unsigned n_extra_cleanups = stmt_list_stack->length () - before;
9139 sl = pop_stmt_list (sl);
9140 if (n_extra_cleanups)
9142 /* If cp_finish_decomp needs any cleanups, such as for
9143 extend_ref_init_temps created vars, pop_stmt_list
9144 popped that all, so push those extra cleanups around
9145 the whole sequence with a guard variable. */
9146 gcc_assert (TREE_CODE (sl) == STATEMENT_LIST);
9147 guard = force_target_expr (integer_type_node,
9148 integer_zero_node, tf_none);
9149 add_stmt (guard);
9150 guard = TARGET_EXPR_SLOT (guard);
9151 for (unsigned i = 0; i < n_extra_cleanups; ++i)
9153 tree_stmt_iterator tsi = tsi_last (sl);
9154 gcc_assert (!tsi_end_p (tsi));
9155 tree last = tsi_stmt (tsi);
9156 gcc_assert (TREE_CODE (last) == CLEANUP_STMT
9157 && !CLEANUP_EH_ONLY (last));
9158 tree cst = build_int_cst (integer_type_node, i + 1);
9159 tree cl = build3 (COND_EXPR, void_type_node,
9160 build2 (GE_EXPR, boolean_type_node,
9161 guard, cst),
9162 CLEANUP_EXPR (last), void_node);
9163 extra_cleanups.safe_push (cl);
9164 tsi_link_before (&tsi, build2 (MODIFY_EXPR,
9165 integer_type_node,
9166 guard, cst),
9167 TSI_SAME_STMT);
9168 tree sl2 = CLEANUP_BODY (last);
9169 gcc_assert (TREE_CODE (sl2) == STATEMENT_LIST);
9170 tsi_link_before (&tsi, sl2, TSI_SAME_STMT);
9171 tsi_delink (&tsi);
9174 decomp_init = maybe_cleanup_point_expr_void (sl);
9175 if (cleanup)
9176 finish_decl_cleanup (decl, cleanup);
9180 /* If a variable is defined, and then a subsequent
9181 definition with external linkage is encountered, we will
9182 get here twice for the same variable. We want to avoid
9183 calling expand_static_init more than once. For variables
9184 that are not static data members, we can call
9185 expand_static_init only when we actually process the
9186 initializer. It is not legal to redeclare a static data
9187 member, so this issue does not arise in that case. */
9188 else if (var_definition_p && TREE_STATIC (decl))
9189 expand_static_init (decl, init);
9192 /* If a CLEANUP_STMT was created to destroy a temporary bound to a
9193 reference, insert it in the statement-tree now. */
9194 if (cleanups)
9196 for (tree t : *cleanups)
9198 push_cleanup (NULL_TREE, t, false);
9199 /* As in initialize_local_var. */
9200 wrap_temporary_cleanups (init, t);
9202 release_tree_vector (cleanups);
9205 for (tree t : &extra_cleanups)
9206 push_cleanup (NULL_TREE, t, false);
9208 if (decomp_init)
9209 add_stmt (decomp_init);
9211 if (was_readonly)
9212 TREE_READONLY (decl) = 1;
9214 if (flag_openmp
9215 && VAR_P (decl)
9216 && lookup_attribute ("omp declare target implicit",
9217 DECL_ATTRIBUTES (decl)))
9219 DECL_ATTRIBUTES (decl)
9220 = remove_attribute ("omp declare target implicit",
9221 DECL_ATTRIBUTES (decl));
9222 complete_type (TREE_TYPE (decl));
9223 if (!omp_mappable_type (TREE_TYPE (decl)))
9225 auto_diagnostic_group d;
9226 error ("%q+D in declare target directive does not have mappable"
9227 " type", decl);
9228 if (TREE_TYPE (decl) != error_mark_node
9229 && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
9230 cxx_incomplete_type_inform (TREE_TYPE (decl));
9232 else if (!lookup_attribute ("omp declare target",
9233 DECL_ATTRIBUTES (decl))
9234 && !lookup_attribute ("omp declare target link",
9235 DECL_ATTRIBUTES (decl)))
9237 DECL_ATTRIBUTES (decl)
9238 = tree_cons (get_identifier ("omp declare target"),
9239 NULL_TREE, DECL_ATTRIBUTES (decl));
9240 symtab_node *node = symtab_node::get (decl);
9241 if (node != NULL)
9243 node->offloadable = 1;
9244 if (ENABLE_OFFLOADING)
9246 g->have_offload = true;
9247 if (is_a <varpool_node *> (node))
9248 vec_safe_push (offload_vars, decl);
9254 /* This is the last point we can lower alignment so give the target the
9255 chance to do so. */
9256 if (VAR_P (decl)
9257 && !is_global_var (decl)
9258 && !DECL_HARD_REGISTER (decl))
9259 targetm.lower_local_decl_alignment (decl);
9261 invoke_plugin_callbacks (PLUGIN_FINISH_DECL, decl);
9264 /* For class TYPE return itself or some its bases that contain
9265 any direct non-static data members. Return error_mark_node if an
9266 error has been diagnosed. */
9268 static tree
9269 find_decomp_class_base (location_t loc, tree type, tree ret)
9271 bool member_seen = false;
9272 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
9273 if (TREE_CODE (field) != FIELD_DECL
9274 || DECL_ARTIFICIAL (field)
9275 || DECL_UNNAMED_BIT_FIELD (field))
9276 continue;
9277 else if (ret)
9278 return type;
9279 else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
9281 auto_diagnostic_group d;
9282 if (TREE_CODE (TREE_TYPE (field)) == RECORD_TYPE)
9283 error_at (loc, "cannot decompose class type %qT because it has an "
9284 "anonymous struct member", type);
9285 else
9286 error_at (loc, "cannot decompose class type %qT because it has an "
9287 "anonymous union member", type);
9288 inform (DECL_SOURCE_LOCATION (field), "declared here");
9289 return error_mark_node;
9291 else if (!accessible_p (type, field, true))
9293 auto_diagnostic_group d;
9294 error_at (loc, "cannot decompose inaccessible member %qD of %qT",
9295 field, type);
9296 inform (DECL_SOURCE_LOCATION (field),
9297 TREE_PRIVATE (field)
9298 ? G_("declared private here")
9299 : G_("declared protected here"));
9300 return error_mark_node;
9302 else
9303 member_seen = true;
9305 tree base_binfo, binfo;
9306 tree orig_ret = ret;
9307 int i;
9308 if (member_seen)
9309 ret = type;
9310 for (binfo = TYPE_BINFO (type), i = 0;
9311 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
9313 tree t = find_decomp_class_base (loc, TREE_TYPE (base_binfo), ret);
9314 if (t == error_mark_node)
9315 return error_mark_node;
9316 if (t != NULL_TREE && t != ret)
9318 if (ret == type)
9320 error_at (loc, "cannot decompose class type %qT: both it and "
9321 "its base class %qT have non-static data members",
9322 type, t);
9323 return error_mark_node;
9325 else if (orig_ret != NULL_TREE)
9326 return t;
9327 else if (ret != NULL_TREE)
9329 error_at (loc, "cannot decompose class type %qT: its base "
9330 "classes %qT and %qT have non-static data "
9331 "members", type, ret, t);
9332 return error_mark_node;
9334 else
9335 ret = t;
9338 return ret;
9341 /* Return std::tuple_size<TYPE>::value. */
9343 static tree
9344 get_tuple_size (tree type)
9346 tree args = make_tree_vec (1);
9347 TREE_VEC_ELT (args, 0) = type;
9348 tree inst = lookup_template_class (tuple_size_identifier, args,
9349 /*in_decl*/NULL_TREE,
9350 /*context*/std_node,
9351 tf_none);
9352 inst = complete_type (inst);
9353 if (inst == error_mark_node
9354 || !COMPLETE_TYPE_P (inst)
9355 || !CLASS_TYPE_P (type))
9356 return NULL_TREE;
9357 tree val = lookup_qualified_name (inst, value_identifier,
9358 LOOK_want::NORMAL, /*complain*/false);
9359 if (val == error_mark_node)
9360 return NULL_TREE;
9361 if (VAR_P (val) || TREE_CODE (val) == CONST_DECL)
9362 val = maybe_constant_value (val);
9363 if (TREE_CODE (val) == INTEGER_CST)
9364 return val;
9365 else
9366 return error_mark_node;
9369 /* Return std::tuple_element<I,TYPE>::type. */
9371 static tree
9372 get_tuple_element_type (tree type, unsigned i)
9374 tree args = make_tree_vec (2);
9375 TREE_VEC_ELT (args, 0) = build_int_cst (integer_type_node, i);
9376 TREE_VEC_ELT (args, 1) = type;
9377 tree inst = lookup_template_class (tuple_element_identifier, args,
9378 /*in_decl*/NULL_TREE,
9379 /*context*/std_node,
9380 tf_warning_or_error);
9381 return make_typename_type (inst, type_identifier,
9382 none_type, tf_warning_or_error);
9385 /* Return e.get<i>() or get<i>(e). */
9387 static tree
9388 get_tuple_decomp_init (tree decl, unsigned i)
9390 tree targs = make_tree_vec (1);
9391 TREE_VEC_ELT (targs, 0) = build_int_cst (integer_type_node, i);
9393 tree etype = TREE_TYPE (decl);
9394 tree e = convert_from_reference (decl);
9396 /* [The id-expression] e is an lvalue if the type of the entity e is an
9397 lvalue reference and an xvalue otherwise. */
9398 if (!TYPE_REF_P (etype)
9399 || TYPE_REF_IS_RVALUE (etype))
9400 e = move (e);
9402 tree fns = lookup_qualified_name (TREE_TYPE (e), get__identifier,
9403 LOOK_want::NORMAL, /*complain*/false);
9404 bool use_member_get = false;
9406 /* To use a member get, member lookup must find at least one
9407 declaration that is a function template
9408 whose first template parameter is a non-type parameter. */
9409 for (lkp_iterator iter (MAYBE_BASELINK_FUNCTIONS (fns)); iter; ++iter)
9411 tree fn = *iter;
9412 if (TREE_CODE (fn) == TEMPLATE_DECL)
9414 tree tparms = DECL_TEMPLATE_PARMS (fn);
9415 tree parm = TREE_VEC_ELT (INNERMOST_TEMPLATE_PARMS (tparms), 0);
9416 if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
9418 use_member_get = true;
9419 break;
9424 if (use_member_get)
9426 fns = lookup_template_function (fns, targs);
9427 return build_new_method_call (e, fns, /*args*/NULL,
9428 /*path*/NULL_TREE, LOOKUP_NORMAL,
9429 /*fn_p*/NULL, tf_warning_or_error);
9431 else
9433 releasing_vec args (make_tree_vector_single (e));
9434 fns = lookup_template_function (get__identifier, targs);
9435 fns = perform_koenig_lookup (fns, args, tf_warning_or_error);
9436 return finish_call_expr (fns, &args, /*novirt*/false,
9437 /*koenig*/true, tf_warning_or_error);
9441 /* It's impossible to recover the decltype of a tuple decomposition variable
9442 based on the actual type of the variable, so store it in a hash table. */
9444 static GTY((cache)) decl_tree_cache_map *decomp_type_table;
9446 tree
9447 lookup_decomp_type (tree v)
9449 if (tree *slot = decomp_type_table->get (v))
9450 return *slot;
9451 return NULL_TREE;
9454 /* Mangle a decomposition declaration if needed. Arguments like
9455 in cp_finish_decomp. */
9457 static void
9458 cp_maybe_mangle_decomp (tree decl, cp_decomp *decomp)
9460 if (!processing_template_decl
9461 && !error_operand_p (decl)
9462 && TREE_STATIC (decl))
9464 auto_vec<tree, 16> v;
9465 v.safe_grow (decomp->count, true);
9466 tree d = decomp->decl;
9467 for (unsigned int i = 0; i < decomp->count; i++, d = DECL_CHAIN (d))
9468 v[decomp->count - i - 1] = d;
9469 if (DECL_FUNCTION_SCOPE_P (decl))
9471 size_t sz = 3;
9472 for (unsigned int i = 0; i < decomp->count; ++i)
9473 sz += IDENTIFIER_LENGTH (DECL_NAME (v[i])) + 1;
9474 char *name = XALLOCAVEC (char, sz);
9475 name[0] = 'D';
9476 name[1] = 'C';
9477 char *p = name + 2;
9478 for (unsigned int i = 0; i < decomp->count; ++i)
9480 size_t len = IDENTIFIER_LENGTH (DECL_NAME (v[i]));
9481 *p++ = ' ';
9482 memcpy (p, IDENTIFIER_POINTER (DECL_NAME (v[i])), len);
9483 p += len;
9485 *p = '\0';
9486 determine_local_discriminator (decl, get_identifier (name));
9488 SET_DECL_ASSEMBLER_NAME (decl, mangle_decomp (decl, v));
9489 maybe_apply_pragma_weak (decl);
9493 /* Finish a decomposition declaration. DECL is the underlying declaration
9494 "e", FIRST is the head of a chain of decls for the individual identifiers
9495 chained through DECL_CHAIN in reverse order and COUNT is the number of
9496 those decls. If TEST_P is true, return true if any code would need to be
9497 actually emitted but don't emit it. Return false otherwise. */
9499 bool
9500 cp_finish_decomp (tree decl, cp_decomp *decomp, bool test_p)
9502 tree first = decomp->decl;
9503 unsigned count = decomp->count;
9504 if (error_operand_p (decl))
9506 error_out:
9507 while (count--)
9509 TREE_TYPE (first) = error_mark_node;
9510 if (DECL_HAS_VALUE_EXPR_P (first))
9512 SET_DECL_VALUE_EXPR (first, NULL_TREE);
9513 DECL_HAS_VALUE_EXPR_P (first) = 0;
9515 first = DECL_CHAIN (first);
9517 if (DECL_P (decl) && DECL_NAMESPACE_SCOPE_P (decl))
9518 SET_DECL_ASSEMBLER_NAME (decl, get_identifier ("<decomp>"));
9519 return false;
9522 location_t loc = DECL_SOURCE_LOCATION (decl);
9523 if (type_dependent_expression_p (decl)
9524 /* This happens for range for when not in templates.
9525 Still add the DECL_VALUE_EXPRs for later processing. */
9526 || (!processing_template_decl
9527 && type_uses_auto (TREE_TYPE (decl))))
9529 for (unsigned int i = 0; i < count; i++)
9531 if (!DECL_HAS_VALUE_EXPR_P (first))
9533 tree v = build_nt (ARRAY_REF, decl,
9534 size_int (count - i - 1),
9535 NULL_TREE, NULL_TREE);
9536 SET_DECL_VALUE_EXPR (first, v);
9537 DECL_HAS_VALUE_EXPR_P (first) = 1;
9539 if (processing_template_decl)
9540 fit_decomposition_lang_decl (first, decl);
9541 first = DECL_CHAIN (first);
9543 return false;
9546 auto_vec<tree, 16> v;
9547 v.safe_grow (count, true);
9548 tree d = first;
9549 for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
9551 v[count - i - 1] = d;
9552 fit_decomposition_lang_decl (d, decl);
9555 tree type = TREE_TYPE (decl);
9556 tree dexp = decl;
9558 if (TYPE_REF_P (type))
9560 dexp = convert_from_reference (dexp);
9561 type = complete_type (TREE_TYPE (type));
9562 if (type == error_mark_node)
9563 goto error_out;
9564 if (!COMPLETE_TYPE_P (type))
9566 error_at (loc, "structured binding refers to incomplete type %qT",
9567 type);
9568 goto error_out;
9572 tree eltype = NULL_TREE;
9573 unsigned HOST_WIDE_INT eltscnt = 0;
9574 if (TREE_CODE (type) == ARRAY_TYPE)
9576 tree nelts;
9577 nelts = array_type_nelts_top (type);
9578 if (nelts == error_mark_node)
9579 goto error_out;
9580 if (DECL_DECOMP_BASE (decl))
9582 error_at (loc, "array initializer for structured binding "
9583 "declaration in condition");
9584 goto error_out;
9586 if (!tree_fits_uhwi_p (nelts))
9588 error_at (loc, "cannot decompose variable length array %qT", type);
9589 goto error_out;
9591 eltscnt = tree_to_uhwi (nelts);
9592 if (count != eltscnt)
9594 cnt_mismatch:
9595 auto_diagnostic_group d;
9596 if (count > eltscnt)
9597 error_n (loc, count,
9598 "%u name provided for structured binding",
9599 "%u names provided for structured binding", count);
9600 else
9601 error_n (loc, count,
9602 "only %u name provided for structured binding",
9603 "only %u names provided for structured binding", count);
9604 inform_n (loc, eltscnt,
9605 "while %qT decomposes into %wu element",
9606 "while %qT decomposes into %wu elements",
9607 type, eltscnt);
9608 goto error_out;
9610 eltype = TREE_TYPE (type);
9611 for (unsigned int i = 0; i < count; i++)
9613 TREE_TYPE (v[i]) = eltype;
9614 layout_decl (v[i], 0);
9615 if (processing_template_decl)
9616 continue;
9617 tree t = unshare_expr (dexp);
9618 t = build4 (ARRAY_REF, eltype, t, size_int (i), NULL_TREE, NULL_TREE);
9619 SET_DECL_VALUE_EXPR (v[i], t);
9620 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9623 /* 2 GNU extensions. */
9624 else if (TREE_CODE (type) == COMPLEX_TYPE)
9626 eltscnt = 2;
9627 if (count != eltscnt)
9628 goto cnt_mismatch;
9629 eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
9630 for (unsigned int i = 0; i < count; i++)
9632 TREE_TYPE (v[i]) = eltype;
9633 layout_decl (v[i], 0);
9634 if (processing_template_decl)
9635 continue;
9636 tree t = unshare_expr (dexp);
9637 t = build1 (i ? IMAGPART_EXPR : REALPART_EXPR, eltype, t);
9638 SET_DECL_VALUE_EXPR (v[i], t);
9639 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9642 else if (TREE_CODE (type) == VECTOR_TYPE)
9644 if (!TYPE_VECTOR_SUBPARTS (type).is_constant (&eltscnt))
9646 error_at (loc, "cannot decompose variable length vector %qT", type);
9647 goto error_out;
9649 if (count != eltscnt)
9650 goto cnt_mismatch;
9651 eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
9652 for (unsigned int i = 0; i < count; i++)
9654 TREE_TYPE (v[i]) = eltype;
9655 layout_decl (v[i], 0);
9656 if (processing_template_decl)
9657 continue;
9658 tree t = unshare_expr (dexp);
9659 convert_vector_to_array_for_subscript (DECL_SOURCE_LOCATION (v[i]),
9660 &t, size_int (i));
9661 t = build4 (ARRAY_REF, eltype, t, size_int (i), NULL_TREE, NULL_TREE);
9662 SET_DECL_VALUE_EXPR (v[i], t);
9663 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9666 else if (tree tsize = get_tuple_size (type))
9668 if (tsize == error_mark_node)
9670 error_at (loc, "%<std::tuple_size<%T>::value%> is not an integral "
9671 "constant expression", type);
9672 goto error_out;
9674 if (!tree_fits_uhwi_p (tsize))
9676 auto_diagnostic_group d;
9677 error_n (loc, count,
9678 "%u name provided for structured binding",
9679 "%u names provided for structured binding", count);
9680 inform (loc, "while %qT decomposes into %E elements",
9681 type, tsize);
9682 goto error_out;
9684 eltscnt = tree_to_uhwi (tsize);
9685 if (count != eltscnt)
9686 goto cnt_mismatch;
9687 if (test_p)
9688 return true;
9689 if (!processing_template_decl && DECL_DECOMP_BASE (decl))
9691 /* For structured bindings used in conditions we need to evaluate
9692 the conversion of decl (aka e in the standard) to bool or
9693 integral/enumeral type (the latter for switch conditions)
9694 before the get methods. */
9695 tree cond = convert_from_reference (decl);
9696 if (integer_onep (DECL_DECOMP_BASE (decl)))
9697 /* switch condition. */
9698 cond = build_expr_type_conversion (WANT_INT | WANT_ENUM,
9699 cond, true);
9700 else
9701 /* if/while/for condition. */
9702 cond = contextual_conv_bool (cond, tf_warning_or_error);
9703 if (cond && !error_operand_p (cond))
9705 /* Wrap that value into a TARGET_EXPR, emit it right
9706 away and save for later uses in the cp_parse_condition
9707 or its instantiation. */
9708 cond = get_target_expr (cond);
9709 add_stmt (cond);
9710 DECL_DECOMP_BASE (decl) = cond;
9713 int save_read = DECL_READ_P (decl);
9714 for (unsigned i = 0; i < count; ++i)
9716 location_t sloc = input_location;
9717 location_t dloc = DECL_SOURCE_LOCATION (v[i]);
9719 input_location = dloc;
9720 tree init = get_tuple_decomp_init (decl, i);
9721 tree eltype = (init == error_mark_node ? error_mark_node
9722 : get_tuple_element_type (type, i));
9723 input_location = sloc;
9725 if (VOID_TYPE_P (eltype))
9727 error ("%<std::tuple_element<%u, %T>::type%> is %<void%>",
9728 i, type);
9729 eltype = error_mark_node;
9731 if (init == error_mark_node || eltype == error_mark_node)
9733 inform (dloc, "in initialization of structured binding "
9734 "variable %qD", v[i]);
9735 goto error_out;
9737 /* Save the decltype away before reference collapse. */
9738 hash_map_safe_put<hm_ggc> (decomp_type_table, v[i], eltype);
9739 eltype = cp_build_reference_type (eltype, !lvalue_p (init));
9740 TREE_TYPE (v[i]) = eltype;
9741 layout_decl (v[i], 0);
9742 if (DECL_HAS_VALUE_EXPR_P (v[i]))
9744 /* In this case the names are variables, not just proxies. */
9745 SET_DECL_VALUE_EXPR (v[i], NULL_TREE);
9746 DECL_HAS_VALUE_EXPR_P (v[i]) = 0;
9748 if (!processing_template_decl)
9750 copy_linkage (v[i], decl);
9751 cp_finish_decl (v[i], init, /*constexpr*/false,
9752 /*asm*/NULL_TREE, LOOKUP_NORMAL);
9755 /* Ignore reads from the underlying decl performed during initialization
9756 of the individual variables. If those will be read, we'll mark
9757 the underlying decl as read at that point. */
9758 DECL_READ_P (decl) = save_read;
9760 else if (TREE_CODE (type) == UNION_TYPE)
9762 error_at (loc, "cannot decompose union type %qT", type);
9763 goto error_out;
9765 else if (!CLASS_TYPE_P (type))
9767 error_at (loc, "cannot decompose non-array non-class type %qT", type);
9768 goto error_out;
9770 else if (LAMBDA_TYPE_P (type))
9772 error_at (loc, "cannot decompose lambda closure type %qT", type);
9773 goto error_out;
9775 else if (processing_template_decl && complete_type (type) == error_mark_node)
9776 goto error_out;
9777 else if (processing_template_decl && !COMPLETE_TYPE_P (type))
9778 pedwarn (loc, 0, "structured binding refers to incomplete class type %qT",
9779 type);
9780 else
9782 tree btype = find_decomp_class_base (loc, type, NULL_TREE);
9783 if (btype == error_mark_node)
9784 goto error_out;
9785 else if (btype == NULL_TREE)
9787 error_at (loc, "cannot decompose class type %qT without non-static "
9788 "data members", type);
9789 goto error_out;
9791 for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
9792 if (TREE_CODE (field) != FIELD_DECL
9793 || DECL_ARTIFICIAL (field)
9794 || DECL_UNNAMED_BIT_FIELD (field))
9795 continue;
9796 else
9797 eltscnt++;
9798 if (count != eltscnt)
9799 goto cnt_mismatch;
9800 tree t = dexp;
9801 if (type != btype)
9803 t = convert_to_base (t, btype, /*check_access*/true,
9804 /*nonnull*/false, tf_warning_or_error);
9805 type = btype;
9807 unsigned int i = 0;
9808 for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
9809 if (TREE_CODE (field) != FIELD_DECL
9810 || DECL_ARTIFICIAL (field)
9811 || DECL_UNNAMED_BIT_FIELD (field))
9812 continue;
9813 else
9815 tree tt = finish_non_static_data_member (field, unshare_expr (t),
9816 NULL_TREE);
9817 if (REFERENCE_REF_P (tt))
9818 tt = TREE_OPERAND (tt, 0);
9819 TREE_TYPE (v[i]) = TREE_TYPE (tt);
9820 layout_decl (v[i], 0);
9821 if (!processing_template_decl)
9823 SET_DECL_VALUE_EXPR (v[i], tt);
9824 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9826 i++;
9829 if (processing_template_decl)
9831 for (unsigned int i = 0; i < count; i++)
9832 if (!DECL_HAS_VALUE_EXPR_P (v[i]))
9834 tree a = build_nt (ARRAY_REF, decl, size_int (i),
9835 NULL_TREE, NULL_TREE);
9836 SET_DECL_VALUE_EXPR (v[i], a);
9837 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9840 return false;
9843 /* Returns a declaration for a VAR_DECL as if:
9845 extern "C" TYPE NAME;
9847 had been seen. Used to create compiler-generated global
9848 variables. */
9850 static tree
9851 declare_global_var (tree name, tree type)
9853 auto cookie = push_abi_namespace (global_namespace);
9854 tree decl = build_decl (input_location, VAR_DECL, name, type);
9855 TREE_PUBLIC (decl) = 1;
9856 DECL_EXTERNAL (decl) = 1;
9857 DECL_ARTIFICIAL (decl) = 1;
9858 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
9859 /* If the user has explicitly declared this variable (perhaps
9860 because the code we are compiling is part of a low-level runtime
9861 library), then it is possible that our declaration will be merged
9862 with theirs by pushdecl. */
9863 decl = pushdecl (decl);
9864 cp_finish_decl (decl, NULL_TREE, false, NULL_TREE, 0);
9865 pop_abi_namespace (cookie, global_namespace);
9867 return decl;
9870 /* Returns the type for the argument to "atexit" corresponding to the function
9871 to be called when the program exits. */
9873 static tree
9874 get_atexit_fn_ptr_type ()
9876 if (!atexit_fn_ptr_type_node)
9878 tree fn_type = build_function_type_list (void_type_node, NULL_TREE);
9879 atexit_fn_ptr_type_node = build_pointer_type (fn_type);
9882 return atexit_fn_ptr_type_node;
9885 /* Returns the type for the argument to "__cxa_atexit", "__cxa_thread_atexit"
9886 or "__cxa_throw" corresponding to the destructor to be called when the
9887 program exits. */
9889 tree
9890 get_cxa_atexit_fn_ptr_type ()
9892 if (!cleanup_type)
9894 tree fntype = build_function_type_list (void_type_node,
9895 ptr_type_node, NULL_TREE);
9896 fntype = targetm.cxx.adjust_cdtor_callabi_fntype (fntype);
9897 cleanup_type = build_pointer_type (fntype);
9900 return cleanup_type;
9903 /* Returns a pointer to the `atexit' function. Note that if
9904 FLAG_USE_CXA_ATEXIT is nonzero, then this will actually be the new
9905 `__cxa_atexit' function specified in the IA64 C++ ABI. */
9907 static tree
9908 get_atexit_node (void)
9910 tree atexit_fndecl;
9911 tree fn_type;
9912 tree fn_ptr_type;
9913 const char *name;
9914 bool use_aeabi_atexit;
9915 tree ctx = global_namespace;
9917 if (atexit_node)
9918 return atexit_node;
9920 if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
9922 /* The declaration for `__cxa_atexit' is:
9924 int __cxa_atexit (void (*)(void *), void *, void *)
9926 We build up the argument types and then the function type
9927 itself. */
9928 tree argtype0, argtype1, argtype2;
9930 use_aeabi_atexit = targetm.cxx.use_aeabi_atexit ();
9931 /* First, build the pointer-to-function type for the first
9932 argument. */
9933 fn_ptr_type = get_cxa_atexit_fn_ptr_type ();
9934 /* Then, build the rest of the argument types. */
9935 argtype2 = ptr_type_node;
9936 if (use_aeabi_atexit)
9938 argtype1 = fn_ptr_type;
9939 argtype0 = ptr_type_node;
9941 else
9943 argtype1 = ptr_type_node;
9944 argtype0 = fn_ptr_type;
9946 /* And the final __cxa_atexit type. */
9947 fn_type = build_function_type_list (integer_type_node,
9948 argtype0, argtype1, argtype2,
9949 NULL_TREE);
9950 /* ... which needs noexcept. */
9951 fn_type = build_exception_variant (fn_type, noexcept_true_spec);
9952 if (use_aeabi_atexit)
9954 name = "__aeabi_atexit";
9955 push_to_top_level ();
9956 int n = push_namespace (get_identifier ("__aeabiv1"), false);
9957 ctx = current_namespace;
9958 while (n--)
9959 pop_namespace ();
9960 pop_from_top_level ();
9962 else
9964 name = "__cxa_atexit";
9965 ctx = abi_node;
9968 else
9970 /* The declaration for `atexit' is:
9972 int atexit (void (*)());
9974 We build up the argument types and then the function type
9975 itself. */
9976 fn_ptr_type = get_atexit_fn_ptr_type ();
9977 /* Build the final atexit type. */
9978 fn_type = build_function_type_list (integer_type_node,
9979 fn_ptr_type, NULL_TREE);
9980 /* ... which needs noexcept. */
9981 fn_type = build_exception_variant (fn_type, noexcept_true_spec);
9982 name = "atexit";
9985 /* Now, build the function declaration. */
9986 push_lang_context (lang_name_c);
9987 auto cookie = push_abi_namespace (ctx);
9988 atexit_fndecl = build_library_fn_ptr (name, fn_type, ECF_LEAF | ECF_NOTHROW);
9989 DECL_CONTEXT (atexit_fndecl) = FROB_CONTEXT (current_namespace);
9990 /* Install as hidden builtin so we're (a) more relaxed about
9991 exception spec matching and (b) will not give a confusing location
9992 in diagnostic and (c) won't magically appear in user-visible name
9993 lookups. */
9994 DECL_SOURCE_LOCATION (atexit_fndecl) = BUILTINS_LOCATION;
9995 atexit_fndecl = pushdecl (atexit_fndecl, /*hiding=*/true);
9996 pop_abi_namespace (cookie, ctx);
9997 mark_used (atexit_fndecl);
9998 pop_lang_context ();
9999 atexit_node = decay_conversion (atexit_fndecl, tf_warning_or_error);
10001 return atexit_node;
10004 /* Like get_atexit_node, but for thread-local cleanups. */
10006 static tree
10007 get_thread_atexit_node (void)
10009 if (thread_atexit_node)
10010 return thread_atexit_node;
10012 /* The declaration for `__cxa_thread_atexit' is:
10014 int __cxa_thread_atexit (void (*)(void *), void *, void *) */
10015 tree fn_type = build_function_type_list (integer_type_node,
10016 get_cxa_atexit_fn_ptr_type (),
10017 ptr_type_node, ptr_type_node,
10018 NULL_TREE);
10020 /* Now, build the function declaration, as with __cxa_atexit. */
10021 unsigned flags = push_abi_namespace ();
10022 tree atexit_fndecl = build_library_fn_ptr ("__cxa_thread_atexit", fn_type,
10023 ECF_LEAF | ECF_NOTHROW);
10024 DECL_CONTEXT (atexit_fndecl) = FROB_CONTEXT (current_namespace);
10025 DECL_SOURCE_LOCATION (atexit_fndecl) = BUILTINS_LOCATION;
10026 atexit_fndecl = pushdecl (atexit_fndecl, /*hiding=*/true);
10027 pop_abi_namespace (flags);
10028 mark_used (atexit_fndecl);
10029 thread_atexit_node = decay_conversion (atexit_fndecl, tf_warning_or_error);
10031 return thread_atexit_node;
10034 /* Returns the __dso_handle VAR_DECL. */
10036 static tree
10037 get_dso_handle_node (void)
10039 if (dso_handle_node)
10040 return dso_handle_node;
10042 /* Declare the variable. */
10043 dso_handle_node = declare_global_var (get_identifier ("__dso_handle"),
10044 ptr_type_node);
10046 #ifdef HAVE_GAS_HIDDEN
10047 if (dso_handle_node != error_mark_node)
10049 DECL_VISIBILITY (dso_handle_node) = VISIBILITY_HIDDEN;
10050 DECL_VISIBILITY_SPECIFIED (dso_handle_node) = 1;
10052 #endif
10054 return dso_handle_node;
10057 /* Begin a new function with internal linkage whose job will be simply
10058 to destroy some particular variable. OB_PARM is true if object pointer
10059 is passed to the cleanup function, otherwise no argument is passed. */
10061 static GTY(()) int start_cleanup_cnt;
10063 static tree
10064 start_cleanup_fn (bool ob_parm)
10066 char name[32];
10068 push_to_top_level ();
10070 /* No need to mangle this. */
10071 push_lang_context (lang_name_c);
10073 /* Build the name of the function. */
10074 sprintf (name, "__tcf_%d", start_cleanup_cnt++);
10075 tree fntype = TREE_TYPE (ob_parm ? get_cxa_atexit_fn_ptr_type ()
10076 : get_atexit_fn_ptr_type ());
10077 /* Build the function declaration. */
10078 tree fndecl = build_lang_decl (FUNCTION_DECL, get_identifier (name), fntype);
10079 DECL_CONTEXT (fndecl) = FROB_CONTEXT (current_namespace);
10080 /* It's a function with internal linkage, generated by the
10081 compiler. */
10082 TREE_PUBLIC (fndecl) = 0;
10083 DECL_ARTIFICIAL (fndecl) = 1;
10084 /* Make the function `inline' so that it is only emitted if it is
10085 actually needed. It is unlikely that it will be inlined, since
10086 it is only called via a function pointer, but we avoid unnecessary
10087 emissions this way. */
10088 DECL_DECLARED_INLINE_P (fndecl) = 1;
10089 DECL_INTERFACE_KNOWN (fndecl) = 1;
10090 if (ob_parm)
10092 /* Build the parameter. */
10093 tree parmdecl = cp_build_parm_decl (fndecl, NULL_TREE, ptr_type_node);
10094 TREE_USED (parmdecl) = 1;
10095 DECL_READ_P (parmdecl) = 1;
10096 DECL_ARGUMENTS (fndecl) = parmdecl;
10099 fndecl = pushdecl (fndecl, /*hidden=*/true);
10100 start_preparsed_function (fndecl, NULL_TREE, SF_PRE_PARSED);
10102 pop_lang_context ();
10104 return current_function_decl;
10107 /* Finish the cleanup function begun by start_cleanup_fn. */
10109 static void
10110 end_cleanup_fn (void)
10112 expand_or_defer_fn (finish_function (/*inline_p=*/false));
10114 pop_from_top_level ();
10117 /* Generate code to handle the destruction of DECL, an object with
10118 static storage duration. */
10120 tree
10121 register_dtor_fn (tree decl)
10123 tree cleanup;
10124 tree addr;
10125 tree compound_stmt;
10126 tree fcall;
10127 tree type;
10128 bool ob_parm, dso_parm, use_dtor;
10129 tree arg0, arg1, arg2;
10130 tree atex_node;
10132 type = TREE_TYPE (decl);
10133 if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
10134 return void_node;
10136 if (decl_maybe_constant_destruction (decl, type)
10137 && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
10139 cxx_maybe_build_cleanup (decl, tf_warning_or_error);
10140 return void_node;
10143 /* If we're using "__cxa_atexit" (or "__cxa_thread_atexit" or
10144 "__aeabi_atexit"), and DECL is a class object, we can just pass the
10145 destructor to "__cxa_atexit"; we don't have to build a temporary
10146 function to do the cleanup. */
10147 dso_parm = (flag_use_cxa_atexit
10148 && !targetm.cxx.use_atexit_for_cxa_atexit ());
10149 ob_parm = (CP_DECL_THREAD_LOCAL_P (decl) || dso_parm);
10150 use_dtor = ob_parm && CLASS_TYPE_P (type);
10151 if (use_dtor)
10153 cleanup = get_class_binding (type, complete_dtor_identifier);
10155 /* Make sure it is accessible. */
10156 perform_or_defer_access_check (TYPE_BINFO (type), cleanup, cleanup,
10157 tf_warning_or_error);
10159 else
10161 /* Call build_cleanup before we enter the anonymous function so
10162 that any access checks will be done relative to the current
10163 scope, rather than the scope of the anonymous function. */
10164 build_cleanup (decl);
10166 /* Now start the function. */
10167 cleanup = start_cleanup_fn (ob_parm);
10169 /* Now, recompute the cleanup. It may contain SAVE_EXPRs that refer
10170 to the original function, rather than the anonymous one. That
10171 will make the back end think that nested functions are in use,
10172 which causes confusion. */
10173 push_deferring_access_checks (dk_no_check);
10174 fcall = build_cleanup (decl);
10175 pop_deferring_access_checks ();
10177 /* Create the body of the anonymous function. */
10178 compound_stmt = begin_compound_stmt (BCS_FN_BODY);
10179 finish_expr_stmt (fcall);
10180 finish_compound_stmt (compound_stmt);
10181 end_cleanup_fn ();
10184 /* Call atexit with the cleanup function. */
10185 mark_used (cleanup);
10186 cleanup = build_address (cleanup);
10188 if (CP_DECL_THREAD_LOCAL_P (decl))
10189 atex_node = get_thread_atexit_node ();
10190 else
10191 atex_node = get_atexit_node ();
10193 if (use_dtor)
10195 /* We must convert CLEANUP to the type that "__cxa_atexit"
10196 expects. */
10197 cleanup = build_nop (get_cxa_atexit_fn_ptr_type (), cleanup);
10198 /* "__cxa_atexit" will pass the address of DECL to the
10199 cleanup function. */
10200 mark_used (decl);
10201 addr = build_address (decl);
10202 /* The declared type of the parameter to "__cxa_atexit" is
10203 "void *". For plain "T*", we could just let the
10204 machinery in cp_build_function_call convert it -- but if the
10205 type is "cv-qualified T *", then we need to convert it
10206 before passing it in, to avoid spurious errors. */
10207 addr = build_nop (ptr_type_node, addr);
10209 else
10210 /* Since the cleanup functions we build ignore the address
10211 they're given, there's no reason to pass the actual address
10212 in, and, in general, it's cheaper to pass NULL than any
10213 other value. */
10214 addr = null_pointer_node;
10216 if (dso_parm)
10217 arg2 = cp_build_addr_expr (get_dso_handle_node (),
10218 tf_warning_or_error);
10219 else if (ob_parm)
10220 /* Just pass NULL to the dso handle parm if we don't actually
10221 have a DSO handle on this target. */
10222 arg2 = null_pointer_node;
10223 else
10224 arg2 = NULL_TREE;
10226 if (ob_parm)
10228 if (!CP_DECL_THREAD_LOCAL_P (decl)
10229 && targetm.cxx.use_aeabi_atexit ())
10231 arg1 = cleanup;
10232 arg0 = addr;
10234 else
10236 arg1 = addr;
10237 arg0 = cleanup;
10240 else
10242 arg0 = cleanup;
10243 arg1 = NULL_TREE;
10245 return cp_build_function_call_nary (atex_node, tf_warning_or_error,
10246 arg0, arg1, arg2, NULL_TREE);
10249 /* DECL is a VAR_DECL with static storage duration. INIT, if present,
10250 is its initializer. Generate code to handle the construction
10251 and destruction of DECL. */
10253 static void
10254 expand_static_init (tree decl, tree init)
10256 gcc_assert (VAR_P (decl));
10257 gcc_assert (TREE_STATIC (decl));
10259 /* Some variables require no dynamic initialization. */
10260 if (decl_maybe_constant_destruction (decl, TREE_TYPE (decl)))
10262 /* Make sure the destructor is callable. */
10263 cxx_maybe_build_cleanup (decl, tf_warning_or_error);
10264 if (!init)
10265 return;
10268 if (CP_DECL_THREAD_LOCAL_P (decl) && DECL_GNU_TLS_P (decl)
10269 && !DECL_FUNCTION_SCOPE_P (decl))
10271 auto_diagnostic_group d;
10272 location_t dloc = DECL_SOURCE_LOCATION (decl);
10273 if (init)
10274 error_at (dloc, "non-local variable %qD declared %<__thread%> "
10275 "needs dynamic initialization", decl);
10276 else
10277 error_at (dloc, "non-local variable %qD declared %<__thread%> "
10278 "has a non-trivial destructor", decl);
10279 static bool informed;
10280 if (!informed)
10282 inform (dloc, "C++11 %<thread_local%> allows dynamic "
10283 "initialization and destruction");
10284 informed = true;
10286 return;
10289 if (DECL_FUNCTION_SCOPE_P (decl))
10291 /* Emit code to perform this initialization but once. */
10292 tree if_stmt = NULL_TREE, inner_if_stmt = NULL_TREE;
10293 tree then_clause = NULL_TREE, inner_then_clause = NULL_TREE;
10294 tree guard, guard_addr;
10295 tree flag, begin;
10296 /* We don't need thread-safety code for thread-local vars. */
10297 bool thread_guard = (flag_threadsafe_statics
10298 && !CP_DECL_THREAD_LOCAL_P (decl));
10300 /* Emit code to perform this initialization but once. This code
10301 looks like:
10303 static <type> guard;
10304 if (!__atomic_load (guard.first_byte)) {
10305 if (__cxa_guard_acquire (&guard)) {
10306 bool flag = false;
10307 try {
10308 // Do initialization.
10309 flag = true; __cxa_guard_release (&guard);
10310 // Register variable for destruction at end of program.
10311 } catch {
10312 if (!flag) __cxa_guard_abort (&guard);
10317 Note that the `flag' variable is only set to 1 *after* the
10318 initialization is complete. This ensures that an exception,
10319 thrown during the construction, will cause the variable to
10320 reinitialized when we pass through this code again, as per:
10322 [stmt.dcl]
10324 If the initialization exits by throwing an exception, the
10325 initialization is not complete, so it will be tried again
10326 the next time control enters the declaration.
10328 This process should be thread-safe, too; multiple threads
10329 should not be able to initialize the variable more than
10330 once. */
10332 /* Create the guard variable. */
10333 guard = get_guard (decl);
10335 /* Begin the conditional initialization. */
10336 if_stmt = begin_if_stmt ();
10338 finish_if_stmt_cond (get_guard_cond (guard, thread_guard), if_stmt);
10339 then_clause = begin_compound_stmt (BCS_NO_SCOPE);
10341 if (thread_guard)
10343 tree vfntype = NULL_TREE;
10344 tree acquire_name, release_name, abort_name;
10345 tree acquire_fn, release_fn, abort_fn;
10346 guard_addr = build_address (guard);
10348 acquire_name = get_identifier ("__cxa_guard_acquire");
10349 release_name = get_identifier ("__cxa_guard_release");
10350 abort_name = get_identifier ("__cxa_guard_abort");
10351 acquire_fn = get_global_binding (acquire_name);
10352 release_fn = get_global_binding (release_name);
10353 abort_fn = get_global_binding (abort_name);
10354 if (!acquire_fn)
10355 acquire_fn = push_library_fn
10356 (acquire_name, build_function_type_list (integer_type_node,
10357 TREE_TYPE (guard_addr),
10358 NULL_TREE),
10359 NULL_TREE, ECF_NOTHROW);
10360 if (!release_fn || !abort_fn)
10361 vfntype = build_function_type_list (void_type_node,
10362 TREE_TYPE (guard_addr),
10363 NULL_TREE);
10364 if (!release_fn)
10365 release_fn = push_library_fn (release_name, vfntype, NULL_TREE,
10366 ECF_NOTHROW);
10367 if (!abort_fn)
10368 abort_fn = push_library_fn (abort_name, vfntype, NULL_TREE,
10369 ECF_NOTHROW | ECF_LEAF);
10371 inner_if_stmt = begin_if_stmt ();
10372 finish_if_stmt_cond (build_call_n (acquire_fn, 1, guard_addr),
10373 inner_if_stmt);
10375 inner_then_clause = begin_compound_stmt (BCS_NO_SCOPE);
10376 begin = get_target_expr (boolean_false_node);
10377 flag = TARGET_EXPR_SLOT (begin);
10379 TARGET_EXPR_CLEANUP (begin)
10380 = build3 (COND_EXPR, void_type_node, flag,
10381 void_node,
10382 build_call_n (abort_fn, 1, guard_addr));
10383 CLEANUP_EH_ONLY (begin) = 1;
10385 /* Do the initialization itself. */
10386 init = add_stmt_to_compound (begin, init);
10387 init = add_stmt_to_compound (init,
10388 build2 (MODIFY_EXPR, void_type_node,
10389 flag, boolean_true_node));
10391 /* Use atexit to register a function for destroying this static
10392 variable. Do this before calling __cxa_guard_release. */
10393 init = add_stmt_to_compound (init, register_dtor_fn (decl));
10395 init = add_stmt_to_compound (init, build_call_n (release_fn, 1,
10396 guard_addr));
10398 else
10400 init = add_stmt_to_compound (init, set_guard (guard));
10402 /* Use atexit to register a function for destroying this static
10403 variable. */
10404 init = add_stmt_to_compound (init, register_dtor_fn (decl));
10407 finish_expr_stmt (init);
10409 if (thread_guard)
10411 finish_compound_stmt (inner_then_clause);
10412 finish_then_clause (inner_if_stmt);
10413 finish_if_stmt (inner_if_stmt);
10416 finish_compound_stmt (then_clause);
10417 finish_then_clause (if_stmt);
10418 finish_if_stmt (if_stmt);
10420 else if (CP_DECL_THREAD_LOCAL_P (decl))
10421 tls_aggregates = tree_cons (init, decl, tls_aggregates);
10422 else
10423 static_aggregates = tree_cons (init, decl, static_aggregates);
10427 /* Make TYPE a complete type based on INITIAL_VALUE.
10428 Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
10429 2 if there was no information (in which case assume 0 if DO_DEFAULT),
10430 3 if the initializer list is empty (in pedantic mode). */
10433 cp_complete_array_type (tree *ptype, tree initial_value, bool do_default)
10435 int failure;
10436 tree type, elt_type;
10438 /* Don't get confused by a CONSTRUCTOR for some other type. */
10439 if (initial_value && TREE_CODE (initial_value) == CONSTRUCTOR
10440 && !BRACE_ENCLOSED_INITIALIZER_P (initial_value)
10441 && TREE_CODE (TREE_TYPE (initial_value)) != ARRAY_TYPE)
10442 return 1;
10444 if (initial_value)
10446 /* An array of character type can be initialized from a
10447 brace-enclosed string constant so call reshape_init to
10448 remove the optional braces from a braced string literal. */
10449 if (char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (*ptype)))
10450 && BRACE_ENCLOSED_INITIALIZER_P (initial_value))
10451 initial_value = reshape_init (*ptype, initial_value,
10452 tf_warning_or_error);
10454 /* If any of the elements are parameter packs, we can't actually
10455 complete this type now because the array size is dependent. */
10456 if (TREE_CODE (initial_value) == CONSTRUCTOR)
10457 for (auto &e: CONSTRUCTOR_ELTS (initial_value))
10458 if (PACK_EXPANSION_P (e.value))
10459 return 0;
10462 failure = complete_array_type (ptype, initial_value, do_default);
10464 /* We can create the array before the element type is complete, which
10465 means that we didn't have these two bits set in the original type
10466 either. In completing the type, we are expected to propagate these
10467 bits. See also complete_type which does the same thing for arrays
10468 of fixed size. */
10469 type = *ptype;
10470 if (type != error_mark_node && TYPE_DOMAIN (type))
10472 elt_type = TREE_TYPE (type);
10473 TYPE_NEEDS_CONSTRUCTING (type) = TYPE_NEEDS_CONSTRUCTING (elt_type);
10474 TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
10475 = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (elt_type);
10478 return failure;
10481 /* As above, but either give an error or reject zero-size arrays, depending
10482 on COMPLAIN. */
10485 cp_complete_array_type_or_error (tree *ptype, tree initial_value,
10486 bool do_default, tsubst_flags_t complain)
10488 int failure;
10489 bool sfinae = !(complain & tf_error);
10490 /* In SFINAE context we can't be lenient about zero-size arrays. */
10491 if (sfinae)
10492 ++pedantic;
10493 failure = cp_complete_array_type (ptype, initial_value, do_default);
10494 if (sfinae)
10495 --pedantic;
10496 if (failure)
10498 if (sfinae)
10499 /* Not an error. */;
10500 else if (failure == 1)
10501 error ("initializer fails to determine size of %qT", *ptype);
10502 else if (failure == 2)
10504 if (do_default)
10505 error ("array size missing in %qT", *ptype);
10507 else if (failure == 3)
10508 error ("zero-size array %qT", *ptype);
10509 *ptype = error_mark_node;
10511 return failure;
10514 /* Return zero if something is declared to be a member of type
10515 CTYPE when in the context of CUR_TYPE. STRING is the error
10516 message to print in that case. Otherwise, quietly return 1. */
10518 static int
10519 member_function_or_else (tree ctype, tree cur_type, enum overload_flags flags)
10521 if (ctype && ctype != cur_type)
10523 if (flags == DTOR_FLAG)
10524 error ("destructor for alien class %qT cannot be a member", ctype);
10525 else
10526 error ("constructor for alien class %qT cannot be a member", ctype);
10527 return 0;
10529 return 1;
10532 /* Subroutine of `grokdeclarator'. */
10534 /* Generate errors possibly applicable for a given set of specifiers.
10535 This is for ARM $7.1.2. */
10537 static void
10538 bad_specifiers (tree object,
10539 enum bad_spec_place type,
10540 int virtualp,
10541 int quals,
10542 int inlinep,
10543 int friendp,
10544 int raises,
10545 const location_t* locations)
10547 switch (type)
10549 case BSP_VAR:
10550 if (virtualp)
10551 error_at (locations[ds_virtual],
10552 "%qD declared as a %<virtual%> variable", object);
10553 if (quals)
10554 error ("%<const%> and %<volatile%> function specifiers on "
10555 "%qD invalid in variable declaration", object);
10556 break;
10557 case BSP_PARM:
10558 if (virtualp)
10559 error_at (locations[ds_virtual],
10560 "%qD declared as a %<virtual%> parameter", object);
10561 if (inlinep)
10562 error_at (locations[ds_inline],
10563 "%qD declared as an %<inline%> parameter", object);
10564 if (quals)
10565 error ("%<const%> and %<volatile%> function specifiers on "
10566 "%qD invalid in parameter declaration", object);
10567 break;
10568 case BSP_TYPE:
10569 if (virtualp)
10570 error_at (locations[ds_virtual],
10571 "%qD declared as a %<virtual%> type", object);
10572 if (inlinep)
10573 error_at (locations[ds_inline],
10574 "%qD declared as an %<inline%> type", object);
10575 if (quals)
10576 error ("%<const%> and %<volatile%> function specifiers on "
10577 "%qD invalid in type declaration", object);
10578 break;
10579 case BSP_FIELD:
10580 if (virtualp)
10581 error_at (locations[ds_virtual],
10582 "%qD declared as a %<virtual%> field", object);
10583 if (inlinep)
10584 error_at (locations[ds_inline],
10585 "%qD declared as an %<inline%> field", object);
10586 if (quals)
10587 error ("%<const%> and %<volatile%> function specifiers on "
10588 "%qD invalid in field declaration", object);
10589 break;
10590 default:
10591 gcc_unreachable();
10593 if (friendp)
10594 error ("%q+D declared as a friend", object);
10595 if (raises
10596 && !flag_noexcept_type
10597 && (TREE_CODE (object) == TYPE_DECL
10598 || (!TYPE_PTRFN_P (TREE_TYPE (object))
10599 && !TYPE_REFFN_P (TREE_TYPE (object))
10600 && !TYPE_PTRMEMFUNC_P (TREE_TYPE (object)))))
10601 error ("%q+D declared with an exception specification", object);
10604 /* DECL is a member function or static data member and is presently
10605 being defined. Check that the definition is taking place in a
10606 valid namespace. */
10608 static void
10609 check_class_member_definition_namespace (tree decl)
10611 /* These checks only apply to member functions and static data
10612 members. */
10613 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
10614 /* We check for problems with specializations in pt.cc in
10615 check_specialization_namespace, where we can issue better
10616 diagnostics. */
10617 if (processing_specialization)
10618 return;
10619 /* We check this in check_explicit_instantiation_namespace. */
10620 if (processing_explicit_instantiation)
10621 return;
10622 /* [class.mfct]
10624 A member function definition that appears outside of the
10625 class definition shall appear in a namespace scope enclosing
10626 the class definition.
10628 [class.static.data]
10630 The definition for a static data member shall appear in a
10631 namespace scope enclosing the member's class definition. */
10632 if (!is_ancestor (current_namespace, DECL_CONTEXT (decl)))
10633 permerror (input_location, "definition of %qD is not in namespace enclosing %qT",
10634 decl, DECL_CONTEXT (decl));
10637 /* Build a PARM_DECL for the "this" parameter of FN. TYPE is the
10638 METHOD_TYPE for a non-static member function; QUALS are the
10639 cv-qualifiers that apply to the function. */
10641 tree
10642 build_this_parm (tree fn, tree type, cp_cv_quals quals)
10644 tree this_type;
10645 tree qual_type;
10646 tree parm;
10647 cp_cv_quals this_quals;
10649 if (CLASS_TYPE_P (type))
10651 this_type
10652 = cp_build_qualified_type (type, quals & ~TYPE_QUAL_RESTRICT);
10653 this_type = build_pointer_type (this_type);
10655 else
10656 this_type = type_of_this_parm (type);
10657 /* The `this' parameter is implicitly `const'; it cannot be
10658 assigned to. */
10659 this_quals = (quals & TYPE_QUAL_RESTRICT) | TYPE_QUAL_CONST;
10660 qual_type = cp_build_qualified_type (this_type, this_quals);
10661 parm = build_artificial_parm (fn, this_identifier, qual_type);
10662 cp_apply_type_quals_to_decl (this_quals, parm);
10663 return parm;
10666 /* DECL is a static member function. Complain if it was declared
10667 with function-cv-quals. */
10669 static void
10670 check_static_quals (tree decl, cp_cv_quals quals)
10672 if (quals != TYPE_UNQUALIFIED)
10673 error ("static member function %q#D declared with type qualifiers",
10674 decl);
10677 /* Helper function. Replace the temporary this parameter injected
10678 during cp_finish_omp_declare_simd with the real this parameter. */
10680 static tree
10681 declare_simd_adjust_this (tree *tp, int *walk_subtrees, void *data)
10683 tree this_parm = (tree) data;
10684 if (TREE_CODE (*tp) == PARM_DECL
10685 && DECL_NAME (*tp) == this_identifier
10686 && *tp != this_parm)
10687 *tp = this_parm;
10688 else if (TYPE_P (*tp))
10689 *walk_subtrees = 0;
10690 return NULL_TREE;
10693 /* CTYPE is class type, or null if non-class.
10694 TYPE is type this FUNCTION_DECL should have, either FUNCTION_TYPE
10695 or METHOD_TYPE.
10696 DECLARATOR is the function's name.
10697 PARMS is a chain of PARM_DECLs for the function.
10698 VIRTUALP is truthvalue of whether the function is virtual or not.
10699 FLAGS are to be passed through to `grokclassfn'.
10700 QUALS are qualifiers indicating whether the function is `const'
10701 or `volatile'.
10702 RAISES is a list of exceptions that this function can raise.
10703 CHECK is 1 if we must find this method in CTYPE, 0 if we should
10704 not look, and -1 if we should not call `grokclassfn' at all.
10706 SFK is the kind of special function (if any) for the new function.
10708 Returns `NULL_TREE' if something goes wrong, after issuing
10709 applicable error messages. */
10711 static tree
10712 grokfndecl (tree ctype,
10713 tree type,
10714 tree declarator,
10715 tree parms,
10716 tree orig_declarator,
10717 const cp_decl_specifier_seq *declspecs,
10718 tree decl_reqs,
10719 int virtualp,
10720 enum overload_flags flags,
10721 cp_cv_quals quals,
10722 cp_ref_qualifier rqual,
10723 tree raises,
10724 int check,
10725 int friendp,
10726 int publicp,
10727 int inlinep,
10728 bool deletedp,
10729 bool xobj_func_p,
10730 special_function_kind sfk,
10731 bool funcdef_flag,
10732 bool late_return_type_p,
10733 int template_count,
10734 tree in_namespace,
10735 tree* attrlist,
10736 location_t location)
10738 tree decl;
10739 tree t;
10741 if (location == UNKNOWN_LOCATION)
10742 location = input_location;
10744 /* Was the concept specifier present? */
10745 bool concept_p = inlinep & 4;
10747 if (concept_p)
10749 error_at (location, "function concepts are no longer supported");
10750 return NULL_TREE;
10753 type = build_cp_fntype_variant (type, rqual, raises, late_return_type_p);
10755 decl = build_lang_decl_loc (location, FUNCTION_DECL, declarator, type);
10757 /* Set the constraints on the declaration. */
10758 if (flag_concepts)
10760 tree tmpl_reqs = NULL_TREE;
10761 tree ctx = friendp ? current_class_type : ctype;
10762 bool block_local = TREE_CODE (current_scope ()) == FUNCTION_DECL;
10763 bool memtmpl = (!block_local
10764 && (current_template_depth
10765 > template_class_depth (ctx)));
10766 if (memtmpl)
10768 if (!current_template_parms)
10769 /* If there are no template parameters, something must have
10770 gone wrong. */
10771 gcc_assert (seen_error ());
10772 else
10773 tmpl_reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
10775 tree ci = build_constraints (tmpl_reqs, decl_reqs);
10776 /* C++20 CA378: Remove non-templated constrained functions. */
10777 /* [temp.friend]/9 A non-template friend declaration with a
10778 requires-clause shall be a definition. A friend function template with
10779 a constraint that depends on a template parameter from an enclosing
10780 template shall be a definition. */
10781 if (ci
10782 && (block_local
10783 || !processing_template_decl
10784 || (friendp && !memtmpl && !funcdef_flag)))
10786 if (!friendp || !processing_template_decl)
10787 error_at (location, "constraints on a non-templated function");
10788 else
10789 error_at (location, "constrained non-template friend declaration"
10790 " must be a definition");
10791 ci = NULL_TREE;
10793 set_constraints (decl, ci);
10794 if (ci && friendp && memtmpl && !funcdef_flag
10795 && uses_outer_template_parms_in_constraints (decl, ctx))
10796 error_at (location, "friend function template with constraints that "
10797 "depend on outer template parameters must be a definition");
10800 if (TREE_CODE (type) == METHOD_TYPE)
10802 tree parm = build_this_parm (decl, type, quals);
10803 DECL_CHAIN (parm) = parms;
10804 parms = parm;
10806 /* Allocate space to hold the vptr bit if needed. */
10807 SET_DECL_ALIGN (decl, MINIMUM_METHOD_BOUNDARY);
10810 DECL_ARGUMENTS (decl) = parms;
10811 for (t = parms; t; t = DECL_CHAIN (t))
10812 DECL_CONTEXT (t) = decl;
10814 /* Propagate volatile out from type to decl. */
10815 if (TYPE_VOLATILE (type))
10816 TREE_THIS_VOLATILE (decl) = 1;
10818 /* Setup decl according to sfk. */
10819 switch (sfk)
10821 case sfk_constructor:
10822 case sfk_copy_constructor:
10823 case sfk_move_constructor:
10824 DECL_CXX_CONSTRUCTOR_P (decl) = 1;
10825 DECL_NAME (decl) = ctor_identifier;
10826 break;
10827 case sfk_destructor:
10828 DECL_CXX_DESTRUCTOR_P (decl) = 1;
10829 DECL_NAME (decl) = dtor_identifier;
10830 break;
10831 case sfk_deduction_guide:
10832 /* Give deduction guides a definition even though they don't really
10833 have one: the restriction that you can't repeat a deduction guide
10834 makes them more like a definition anyway. */
10835 DECL_INITIAL (decl) = void_node;
10836 break;
10837 default:
10838 break;
10841 if (friendp && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)
10843 if (funcdef_flag)
10844 error_at (location,
10845 "defining explicit specialization %qD in friend declaration",
10846 orig_declarator);
10847 else
10849 tree fns = TREE_OPERAND (orig_declarator, 0);
10850 tree args = TREE_OPERAND (orig_declarator, 1);
10852 if (PROCESSING_REAL_TEMPLATE_DECL_P ())
10854 /* Something like `template <class T> friend void f<T>()'. */
10855 error_at (location,
10856 "invalid use of template-id %qD in declaration "
10857 "of primary template",
10858 orig_declarator);
10859 return NULL_TREE;
10862 /* A friend declaration of the form friend void f<>(). Record
10863 the information in the TEMPLATE_ID_EXPR. */
10864 SET_DECL_IMPLICIT_INSTANTIATION (decl);
10866 gcc_assert (identifier_p (fns) || OVL_P (fns));
10867 DECL_TEMPLATE_INFO (decl) = build_template_info (fns, args);
10869 for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
10870 if (TREE_PURPOSE (t)
10871 && TREE_CODE (TREE_PURPOSE (t)) == DEFERRED_PARSE)
10873 error_at (defparse_location (TREE_PURPOSE (t)),
10874 "default arguments are not allowed in declaration "
10875 "of friend template specialization %qD",
10876 decl);
10877 return NULL_TREE;
10880 if (inlinep & 1)
10882 error_at (declspecs->locations[ds_inline],
10883 "%<inline%> is not allowed in declaration of friend "
10884 "template specialization %qD",
10885 decl);
10886 return NULL_TREE;
10891 /* C++17 11.3.6/4: "If a friend declaration specifies a default argument
10892 expression, that declaration shall be a definition..." */
10893 if (friendp && !funcdef_flag)
10895 for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
10896 t && t != void_list_node; t = TREE_CHAIN (t))
10897 if (TREE_PURPOSE (t))
10899 permerror (DECL_SOURCE_LOCATION (decl),
10900 "friend declaration of %qD specifies default "
10901 "arguments and isn%'t a definition", decl);
10902 break;
10906 /* If this decl has namespace scope, set that up. */
10907 if (in_namespace)
10908 set_decl_namespace (decl, in_namespace, friendp);
10909 else if (ctype)
10910 DECL_CONTEXT (decl) = ctype;
10911 else
10912 DECL_CONTEXT (decl) = FROB_CONTEXT (current_decl_namespace ());
10914 /* `main' and builtins have implicit 'C' linkage. */
10915 if (ctype == NULL_TREE
10916 && DECL_FILE_SCOPE_P (decl)
10917 && current_lang_name == lang_name_cplusplus
10918 && (MAIN_NAME_P (declarator)
10919 || (IDENTIFIER_LENGTH (declarator) > 10
10920 && IDENTIFIER_POINTER (declarator)[0] == '_'
10921 && IDENTIFIER_POINTER (declarator)[1] == '_'
10922 && startswith (IDENTIFIER_POINTER (declarator) + 2,
10923 "builtin_"))
10924 || (targetcm.cxx_implicit_extern_c
10925 && (targetcm.cxx_implicit_extern_c
10926 (IDENTIFIER_POINTER (declarator))))))
10927 SET_DECL_LANGUAGE (decl, lang_c);
10929 DECL_STATIC_FUNCTION_P (decl)
10930 = !xobj_func_p && ctype && TREE_CODE (type) == FUNCTION_TYPE;
10931 DECL_FUNCTION_XOBJ_FLAG (decl) = xobj_func_p;
10933 if (deletedp)
10934 DECL_DELETED_FN (decl) = 1;
10936 if (ctype && funcdef_flag)
10937 check_class_member_definition_namespace (decl);
10939 if (ctype == NULL_TREE && DECL_MAIN_P (decl))
10941 if (PROCESSING_REAL_TEMPLATE_DECL_P())
10942 error_at (location, "cannot declare %<::main%> to be a template");
10943 if (inlinep & 1)
10944 error_at (declspecs->locations[ds_inline],
10945 "cannot declare %<::main%> to be inline");
10946 if (inlinep & 2)
10947 error_at (declspecs->locations[ds_constexpr],
10948 "cannot declare %<::main%> to be %qs", "constexpr");
10949 if (inlinep & 8)
10950 error_at (declspecs->locations[ds_consteval],
10951 "cannot declare %<::main%> to be %qs", "consteval");
10952 if (!publicp)
10953 error_at (location, "cannot declare %<::main%> to be static");
10954 if (current_lang_depth () != 0)
10955 pedwarn (location, OPT_Wpedantic, "cannot declare %<::main%> with a"
10956 " linkage specification");
10957 if (module_attach_p ())
10958 error_at (location, "cannot attach %<::main%> to a named module");
10959 inlinep = 0;
10960 publicp = 1;
10963 /* Members of anonymous types and local classes have no linkage; make
10964 them internal. If a typedef is made later, this will be changed. */
10965 if (ctype && !TREE_PUBLIC (TYPE_MAIN_DECL (ctype)))
10966 publicp = 0;
10967 else if (ctype && decl_function_context (TYPE_MAIN_DECL (ctype)))
10968 /* But members of local classes in a module CMI should have their
10969 definitions exported, in case they are (directly or indirectly)
10970 used by an importer. We don't just use module_has_cmi_p here
10971 because for entities in the GMF we don't yet know whether this
10972 module will have a CMI, so we'll conservatively assume it might. */
10973 publicp = module_maybe_has_cmi_p ();
10975 if (publicp && cxx_dialect == cxx98)
10977 /* [basic.link]: A name with no linkage (notably, the name of a class
10978 or enumeration declared in a local scope) shall not be used to
10979 declare an entity with linkage.
10981 DR 757 relaxes this restriction for C++0x. */
10982 no_linkage_error (decl);
10985 TREE_PUBLIC (decl) = publicp;
10986 if (! publicp)
10988 DECL_INTERFACE_KNOWN (decl) = 1;
10989 DECL_NOT_REALLY_EXTERN (decl) = 1;
10992 /* If the declaration was declared inline, mark it as such. */
10993 if (inlinep)
10995 DECL_DECLARED_INLINE_P (decl) = 1;
10996 if (publicp)
10997 DECL_COMDAT (decl) = 1;
10999 if (inlinep & 2)
11000 DECL_DECLARED_CONSTEXPR_P (decl) = true;
11001 else if (inlinep & 8)
11003 DECL_DECLARED_CONSTEXPR_P (decl) = true;
11004 SET_DECL_IMMEDIATE_FUNCTION_P (decl);
11007 DECL_EXTERNAL (decl) = 1;
11008 if (TREE_CODE (type) == FUNCTION_TYPE)
11010 if (quals || rqual)
11011 TREE_TYPE (decl) = apply_memfn_quals (TREE_TYPE (decl),
11012 TYPE_UNQUALIFIED,
11013 REF_QUAL_NONE);
11014 auto_diagnostic_group d;
11015 if (quals)
11016 error (!ctype
11017 ? G_("non-member function %qD cannot have cv-qualifier")
11018 : !xobj_func_p
11019 ? G_("static member function %qD cannot have cv-qualifier")
11020 : G_("explicit object member function "
11021 "%qD cannot have cv-qualifier"),
11022 decl);
11023 if (rqual)
11024 error (!ctype
11025 ? G_("non-member function %qD cannot have ref-qualifier")
11026 : !xobj_func_p
11027 ? G_("static member function %qD cannot have ref-qualifier")
11028 : G_("explicit object member function "
11029 "%qD cannot have ref-qualifier"),
11030 decl);
11032 if (xobj_func_p && (quals || rqual))
11033 inform (DECL_SOURCE_LOCATION (DECL_ARGUMENTS (decl)),
11034 "explicit object parameter declared here");
11035 quals = TYPE_UNQUALIFIED;
11036 rqual = REF_QUAL_NONE;
11040 if (deduction_guide_p (decl))
11042 tree type = TREE_TYPE (DECL_NAME (decl));
11043 if (in_namespace == NULL_TREE
11044 && CP_DECL_CONTEXT (decl) != CP_TYPE_CONTEXT (type))
11046 auto_diagnostic_group d;
11047 error_at (location, "deduction guide %qD must be declared in the "
11048 "same scope as %qT", decl, type);
11049 inform (location_of (type), " declared here");
11050 return NULL_TREE;
11052 if (DECL_CLASS_SCOPE_P (decl)
11053 && current_access_specifier != declared_access (TYPE_NAME (type)))
11055 auto_diagnostic_group d;
11056 error_at (location, "deduction guide %qD must have the same access "
11057 "as %qT", decl, type);
11058 inform (location_of (type), " declared here");
11060 if (funcdef_flag)
11061 error_at (location,
11062 "deduction guide %qD must not have a function body", decl);
11064 else if (IDENTIFIER_ANY_OP_P (DECL_NAME (decl))
11065 && !grok_op_properties (decl, /*complain=*/true))
11066 return NULL_TREE;
11067 else if (UDLIT_OPER_P (DECL_NAME (decl)))
11069 bool long_long_unsigned_p;
11070 bool long_double_p;
11071 const char *suffix = NULL;
11072 /* [over.literal]/6: Literal operators shall not have C linkage. */
11073 if (DECL_LANGUAGE (decl) == lang_c)
11075 auto_diagnostic_group d;
11076 error_at (location, "literal operator with C linkage");
11077 maybe_show_extern_c_location ();
11078 return NULL_TREE;
11081 if (DECL_NAMESPACE_SCOPE_P (decl))
11083 if (!check_literal_operator_args (decl, &long_long_unsigned_p,
11084 &long_double_p))
11086 error_at (location, "%qD has invalid argument list", decl);
11087 return NULL_TREE;
11090 suffix = UDLIT_OP_SUFFIX (DECL_NAME (decl));
11091 if (long_long_unsigned_p)
11093 if (cpp_interpret_int_suffix (parse_in, suffix, strlen (suffix)))
11094 warning_at (location, 0, "integer suffix %qs"
11095 " shadowed by implementation", suffix);
11097 else if (long_double_p)
11099 if (cpp_interpret_float_suffix (parse_in, suffix, strlen (suffix)))
11100 warning_at (location, 0, "floating-point suffix %qs"
11101 " shadowed by implementation", suffix);
11103 /* 17.6.3.3.5 */
11104 if (suffix[0] != '_'
11105 && !current_function_decl && !(friendp && !funcdef_flag))
11106 warning_at (location, OPT_Wliteral_suffix,
11107 "literal operator suffixes not preceded by %<_%>"
11108 " are reserved for future standardization");
11110 else
11112 error_at (location, "%qD must be a non-member function", decl);
11113 return NULL_TREE;
11117 if (funcdef_flag)
11118 /* Make the init_value nonzero so pushdecl knows this is not
11119 tentative. error_mark_node is replaced later with the BLOCK. */
11120 DECL_INITIAL (decl) = error_mark_node;
11122 if (TYPE_NOTHROW_P (type) || nothrow_libfn_p (decl))
11123 TREE_NOTHROW (decl) = 1;
11125 if (flag_openmp || flag_openmp_simd)
11127 /* Adjust "omp declare simd" attributes. */
11128 tree ods = lookup_attribute ("omp declare simd", *attrlist);
11129 if (ods)
11131 tree attr;
11132 for (attr = ods; attr;
11133 attr = lookup_attribute ("omp declare simd", TREE_CHAIN (attr)))
11135 if (TREE_CODE (type) == METHOD_TYPE)
11136 walk_tree (&TREE_VALUE (attr), declare_simd_adjust_this,
11137 DECL_ARGUMENTS (decl), NULL);
11138 if (TREE_VALUE (attr) != NULL_TREE)
11140 tree cl = TREE_VALUE (TREE_VALUE (attr));
11141 cl = c_omp_declare_simd_clauses_to_numbers
11142 (DECL_ARGUMENTS (decl), cl);
11143 if (cl)
11144 TREE_VALUE (TREE_VALUE (attr)) = cl;
11145 else
11146 TREE_VALUE (attr) = NULL_TREE;
11152 /* Caller will do the rest of this. */
11153 if (check < 0)
11154 return decl;
11156 if (ctype != NULL_TREE)
11157 grokclassfn (ctype, decl, flags);
11159 /* 12.4/3 */
11160 if (cxx_dialect >= cxx11
11161 && DECL_DESTRUCTOR_P (decl)
11162 && !TYPE_BEING_DEFINED (DECL_CONTEXT (decl))
11163 && !processing_template_decl)
11164 deduce_noexcept_on_destructor (decl);
11166 set_originating_module (decl);
11168 decl = check_explicit_specialization (orig_declarator, decl,
11169 template_count,
11170 2 * funcdef_flag +
11171 4 * (friendp != 0),
11172 *attrlist);
11173 if (decl == error_mark_node)
11174 return NULL_TREE;
11176 if (DECL_STATIC_FUNCTION_P (decl))
11177 check_static_quals (decl, quals);
11179 if (attrlist)
11181 cplus_decl_attributes (&decl, *attrlist, 0);
11182 *attrlist = NULL_TREE;
11185 if (DECL_HAS_CONTRACTS_P (decl))
11186 rebuild_postconditions (decl);
11188 /* Check main's type after attributes have been applied. */
11189 if (ctype == NULL_TREE && DECL_MAIN_P (decl))
11191 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
11192 integer_type_node))
11194 tree oldtypeargs = TYPE_ARG_TYPES (TREE_TYPE (decl));
11195 tree newtype;
11196 error_at (declspecs->locations[ds_type_spec],
11197 "%<::main%> must return %<int%>");
11198 newtype = build_function_type (integer_type_node, oldtypeargs);
11199 TREE_TYPE (decl) = newtype;
11201 if (warn_main)
11202 check_main_parameter_types (decl);
11205 if (ctype != NULL_TREE && check)
11207 tree old_decl = check_classfn (ctype, decl,
11208 (current_template_depth
11209 > template_class_depth (ctype))
11210 ? current_template_parms
11211 : NULL_TREE);
11213 if (old_decl == error_mark_node)
11214 return NULL_TREE;
11216 if (old_decl)
11218 tree ok;
11219 tree pushed_scope;
11221 if (TREE_CODE (old_decl) == TEMPLATE_DECL)
11222 /* Because grokfndecl is always supposed to return a
11223 FUNCTION_DECL, we pull out the DECL_TEMPLATE_RESULT
11224 here. We depend on our callers to figure out that its
11225 really a template that's being returned. */
11226 old_decl = DECL_TEMPLATE_RESULT (old_decl);
11228 if (DECL_STATIC_FUNCTION_P (old_decl)
11229 && TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
11231 /* Remove the `this' parm added by grokclassfn. */
11232 revert_static_member_fn (decl);
11233 check_static_quals (decl, quals);
11235 if (DECL_ARTIFICIAL (old_decl))
11237 error ("definition of implicitly-declared %qD", old_decl);
11238 return NULL_TREE;
11240 else if (DECL_DEFAULTED_FN (old_decl))
11242 auto_diagnostic_group d;
11243 error ("definition of explicitly-defaulted %q+D", decl);
11244 inform (DECL_SOURCE_LOCATION (old_decl),
11245 "%q#D explicitly defaulted here", old_decl);
11246 return NULL_TREE;
11249 /* Since we've smashed OLD_DECL to its
11250 DECL_TEMPLATE_RESULT, we must do the same to DECL. */
11251 if (TREE_CODE (decl) == TEMPLATE_DECL)
11252 decl = DECL_TEMPLATE_RESULT (decl);
11254 /* Attempt to merge the declarations. This can fail, in
11255 the case of some invalid specialization declarations. */
11256 pushed_scope = push_scope (ctype);
11257 ok = duplicate_decls (decl, old_decl);
11258 if (pushed_scope)
11259 pop_scope (pushed_scope);
11260 if (!ok)
11262 error ("no %q#D member function declared in class %qT",
11263 decl, ctype);
11264 return NULL_TREE;
11266 if (ok == error_mark_node)
11267 return NULL_TREE;
11268 return old_decl;
11272 if (DECL_CONSTRUCTOR_P (decl) && !grok_ctor_properties (ctype, decl))
11273 return NULL_TREE;
11275 if (ctype == NULL_TREE || check)
11276 return decl;
11278 if (virtualp)
11279 DECL_VIRTUAL_P (decl) = 1;
11281 return decl;
11284 /* decl is a FUNCTION_DECL.
11285 specifiers are the parsed virt-specifiers.
11287 Set flags to reflect the virt-specifiers.
11289 Returns decl. */
11291 static tree
11292 set_virt_specifiers (tree decl, cp_virt_specifiers specifiers)
11294 if (decl == NULL_TREE)
11295 return decl;
11296 if (specifiers & VIRT_SPEC_OVERRIDE)
11297 DECL_OVERRIDE_P (decl) = 1;
11298 if (specifiers & VIRT_SPEC_FINAL)
11299 DECL_FINAL_P (decl) = 1;
11300 return decl;
11303 /* DECL is a VAR_DECL for a static data member. Set flags to reflect
11304 the linkage that DECL will receive in the object file. */
11306 static void
11307 set_linkage_for_static_data_member (tree decl)
11309 /* A static data member always has static storage duration and
11310 external linkage. Note that static data members are forbidden in
11311 local classes -- the only situation in which a class has
11312 non-external linkage. */
11313 TREE_PUBLIC (decl) = 1;
11314 TREE_STATIC (decl) = 1;
11315 /* For non-template classes, static data members are always put
11316 out in exactly those files where they are defined, just as
11317 with ordinary namespace-scope variables. */
11318 if (!processing_template_decl)
11319 DECL_INTERFACE_KNOWN (decl) = 1;
11322 /* Create a VAR_DECL named NAME with the indicated TYPE.
11324 If SCOPE is non-NULL, it is the class type or namespace containing
11325 the variable. If SCOPE is NULL, the variable should is created in
11326 the innermost enclosing scope. */
11328 static tree
11329 grokvardecl (tree type,
11330 tree name,
11331 tree orig_declarator,
11332 const cp_decl_specifier_seq *declspecs,
11333 int initialized,
11334 int type_quals,
11335 int inlinep,
11336 bool conceptp,
11337 int template_count,
11338 tree scope,
11339 location_t location)
11341 tree decl;
11342 tree explicit_scope;
11344 gcc_assert (!name || identifier_p (name));
11346 bool constp = (type_quals & TYPE_QUAL_CONST) != 0;
11347 bool volatilep = (type_quals & TYPE_QUAL_VOLATILE) != 0;
11349 /* Compute the scope in which to place the variable, but remember
11350 whether or not that scope was explicitly specified by the user. */
11351 explicit_scope = scope;
11352 if (!scope)
11354 /* An explicit "extern" specifier indicates a namespace-scope
11355 variable. */
11356 if (declspecs->storage_class == sc_extern)
11357 scope = current_decl_namespace ();
11358 else if (!at_function_scope_p ())
11359 scope = current_scope ();
11362 if (scope
11363 && (/* If the variable is a namespace-scope variable declared in a
11364 template, we need DECL_LANG_SPECIFIC. */
11365 (TREE_CODE (scope) == NAMESPACE_DECL && processing_template_decl)
11366 /* Similarly for namespace-scope variables with language linkage
11367 other than C++. */
11368 || (TREE_CODE (scope) == NAMESPACE_DECL
11369 && current_lang_name != lang_name_cplusplus)
11370 /* Similarly for static data members. */
11371 || TYPE_P (scope)
11372 /* Similarly for explicit specializations. */
11373 || (orig_declarator
11374 && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)))
11375 decl = build_lang_decl_loc (location, VAR_DECL, name, type);
11376 else
11377 decl = build_decl (location, VAR_DECL, name, type);
11379 if (explicit_scope && TREE_CODE (explicit_scope) == NAMESPACE_DECL)
11380 set_decl_namespace (decl, explicit_scope, 0);
11381 else
11382 DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
11384 if (declspecs->storage_class == sc_extern)
11386 DECL_THIS_EXTERN (decl) = 1;
11387 DECL_EXTERNAL (decl) = !initialized;
11390 if (DECL_CLASS_SCOPE_P (decl))
11392 set_linkage_for_static_data_member (decl);
11393 /* This function is only called with out-of-class definitions. */
11394 DECL_EXTERNAL (decl) = 0;
11395 check_class_member_definition_namespace (decl);
11397 /* At top level, either `static' or no s.c. makes a definition
11398 (perhaps tentative), and absence of `static' makes it public. */
11399 else if (toplevel_bindings_p ())
11401 TREE_PUBLIC (decl) = (declspecs->storage_class != sc_static
11402 && (DECL_THIS_EXTERN (decl)
11403 || ! constp
11404 || volatilep
11405 || inlinep
11406 || in_template_context
11407 || processing_specialization
11408 || module_attach_p ()));
11409 TREE_STATIC (decl) = ! DECL_EXTERNAL (decl);
11411 /* Not at top level, only `static' makes a static definition. */
11412 else
11414 TREE_STATIC (decl) = declspecs->storage_class == sc_static;
11415 TREE_PUBLIC (decl) = DECL_EXTERNAL (decl);
11418 set_originating_module (decl);
11420 if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
11422 if (DECL_EXTERNAL (decl) || TREE_STATIC (decl))
11424 CP_DECL_THREAD_LOCAL_P (decl) = true;
11425 if (!processing_template_decl)
11426 set_decl_tls_model (decl, decl_default_tls_model (decl));
11428 if (declspecs->gnu_thread_keyword_p)
11429 SET_DECL_GNU_TLS_P (decl);
11432 /* If the type of the decl has no linkage, make sure that we'll
11433 notice that in mark_used. */
11434 if (cxx_dialect > cxx98
11435 && decl_linkage (decl) != lk_none
11436 && DECL_LANG_SPECIFIC (decl) == NULL
11437 && !DECL_EXTERN_C_P (decl)
11438 && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
11439 retrofit_lang_decl (decl);
11441 if (TREE_PUBLIC (decl))
11443 /* [basic.link]: A name with no linkage (notably, the name of a class
11444 or enumeration declared in a local scope) shall not be used to
11445 declare an entity with linkage.
11447 DR 757 relaxes this restriction for C++0x. */
11448 if (cxx_dialect < cxx11)
11449 no_linkage_error (decl);
11451 else
11452 DECL_INTERFACE_KNOWN (decl) = 1;
11454 if (DECL_NAME (decl)
11455 && MAIN_NAME_P (DECL_NAME (decl)))
11457 if (scope == global_namespace)
11458 error_at (DECL_SOURCE_LOCATION (decl),
11459 "cannot declare %<::main%> to be a global variable");
11460 else if (DECL_EXTERN_C_P (decl))
11461 error_at (DECL_SOURCE_LOCATION (decl),
11462 "an entity named %<main%> cannot be declared with "
11463 "C language linkage");
11466 /* Check if a variable is being declared as a concept. */
11467 if (conceptp)
11469 if (!processing_template_decl)
11470 error_at (declspecs->locations[ds_concept],
11471 "a non-template variable cannot be %<concept%>");
11472 else if (!at_namespace_scope_p ())
11473 error_at (declspecs->locations[ds_concept],
11474 "concept must be defined at namespace scope");
11475 else
11476 error_at (declspecs->locations[ds_concept],
11477 "variable concepts are no longer supported");
11478 return NULL_TREE;
11480 else if (flag_concepts
11481 && current_template_depth > template_class_depth (scope))
11483 tree ci = current_template_constraints ();
11484 set_constraints (decl, ci);
11487 // Handle explicit specializations and instantiations of variable templates.
11488 if (orig_declarator)
11489 decl = check_explicit_specialization (orig_declarator, decl,
11490 template_count, 0);
11492 return decl != error_mark_node ? decl : NULL_TREE;
11495 /* Create and return a canonical pointer to member function type, for
11496 TYPE, which is a POINTER_TYPE to a METHOD_TYPE. */
11498 tree
11499 build_ptrmemfunc_type (tree type)
11501 tree field, fields;
11502 tree t;
11504 if (type == error_mark_node)
11505 return type;
11507 /* Make sure that we always have the unqualified pointer-to-member
11508 type first. */
11509 if (cp_cv_quals quals = cp_type_quals (type))
11511 tree unqual = build_ptrmemfunc_type (TYPE_MAIN_VARIANT (type));
11512 return cp_build_qualified_type (unqual, quals);
11515 /* If a canonical type already exists for this type, use it. We use
11516 this method instead of type_hash_canon, because it only does a
11517 simple equality check on the list of field members. */
11519 t = TYPE_PTRMEMFUNC_TYPE (type);
11520 if (t)
11521 return t;
11523 t = make_node (RECORD_TYPE);
11525 /* Let the front end know this is a pointer to member function. */
11526 TYPE_PTRMEMFUNC_FLAG (t) = 1;
11528 field = build_decl (input_location, FIELD_DECL, pfn_identifier, type);
11529 DECL_NONADDRESSABLE_P (field) = 1;
11530 fields = field;
11532 field = build_decl (input_location, FIELD_DECL, delta_identifier,
11533 delta_type_node);
11534 DECL_NONADDRESSABLE_P (field) = 1;
11535 DECL_CHAIN (field) = fields;
11536 fields = field;
11538 finish_builtin_struct (t, "__ptrmemfunc_type", fields, ptr_type_node);
11540 /* Zap out the name so that the back end will give us the debugging
11541 information for this anonymous RECORD_TYPE. */
11542 TYPE_NAME (t) = NULL_TREE;
11544 /* Cache this pointer-to-member type so that we can find it again
11545 later. */
11546 TYPE_PTRMEMFUNC_TYPE (type) = t;
11548 if (TYPE_STRUCTURAL_EQUALITY_P (type))
11549 SET_TYPE_STRUCTURAL_EQUALITY (t);
11550 else if (TYPE_CANONICAL (type) != type)
11551 TYPE_CANONICAL (t) = build_ptrmemfunc_type (TYPE_CANONICAL (type));
11553 return t;
11556 /* Create and return a pointer to data member type. */
11558 tree
11559 build_ptrmem_type (tree class_type, tree member_type)
11561 if (TREE_CODE (member_type) == METHOD_TYPE)
11563 cp_cv_quals quals = type_memfn_quals (member_type);
11564 cp_ref_qualifier rqual = type_memfn_rqual (member_type);
11565 member_type = build_memfn_type (member_type, class_type, quals, rqual);
11566 return build_ptrmemfunc_type (build_pointer_type (member_type));
11568 else
11570 gcc_assert (TREE_CODE (member_type) != FUNCTION_TYPE);
11571 return build_offset_type (class_type, member_type);
11575 /* DECL is a VAR_DECL defined in-class, whose TYPE is also given.
11576 Check to see that the definition is valid. Issue appropriate error
11577 messages. */
11579 static void
11580 check_static_variable_definition (tree decl, tree type)
11582 /* Avoid redundant diagnostics on out-of-class definitions. */
11583 if (!current_class_type || !TYPE_BEING_DEFINED (current_class_type))
11585 /* Can't check yet if we don't know the type. */
11586 else if (dependent_type_p (type))
11588 /* If DECL is declared constexpr, we'll do the appropriate checks
11589 in check_initializer. Similarly for inline static data members. */
11590 else if (DECL_P (decl)
11591 && (DECL_DECLARED_CONSTEXPR_P (decl)
11592 || DECL_VAR_DECLARED_INLINE_P (decl)))
11594 else if (cxx_dialect >= cxx11 && !INTEGRAL_OR_ENUMERATION_TYPE_P (type))
11596 if (!COMPLETE_TYPE_P (type))
11597 error_at (DECL_SOURCE_LOCATION (decl),
11598 "in-class initialization of static data member %q#D of "
11599 "incomplete type", decl);
11600 else if (literal_type_p (type))
11601 permerror (DECL_SOURCE_LOCATION (decl),
11602 "%<constexpr%> needed for in-class initialization of "
11603 "static data member %q#D of non-integral type", decl);
11604 else
11605 error_at (DECL_SOURCE_LOCATION (decl),
11606 "in-class initialization of static data member %q#D of "
11607 "non-literal type", decl);
11609 /* Motion 10 at San Diego: If a static const integral data member is
11610 initialized with an integral constant expression, the initializer
11611 may appear either in the declaration (within the class), or in
11612 the definition, but not both. If it appears in the class, the
11613 member is a member constant. The file-scope definition is always
11614 required. */
11615 else if (!ARITHMETIC_TYPE_P (type) && TREE_CODE (type) != ENUMERAL_TYPE)
11616 error_at (DECL_SOURCE_LOCATION (decl),
11617 "invalid in-class initialization of static data member "
11618 "of non-integral type %qT",
11619 type);
11620 else if (!CP_TYPE_CONST_P (type))
11621 error_at (DECL_SOURCE_LOCATION (decl),
11622 "ISO C++ forbids in-class initialization of non-const "
11623 "static member %qD",
11624 decl);
11625 else if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type))
11626 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
11627 "ISO C++ forbids initialization of member constant "
11628 "%qD of non-integral type %qT", decl, type);
11631 /* *expr_p is part of the TYPE_SIZE of a variably-sized array. If any
11632 SAVE_EXPRs in *expr_p wrap expressions with side-effects, break those
11633 expressions out into temporary variables so that walk_tree doesn't
11634 step into them (c++/15764). */
11636 static tree
11637 stabilize_save_expr_r (tree *expr_p, int *walk_subtrees, void *data)
11639 hash_set<tree> *pset = (hash_set<tree> *)data;
11640 tree expr = *expr_p;
11641 if (TREE_CODE (expr) == SAVE_EXPR)
11643 tree op = TREE_OPERAND (expr, 0);
11644 cp_walk_tree (&op, stabilize_save_expr_r, data, pset);
11645 if (TREE_SIDE_EFFECTS (op))
11646 TREE_OPERAND (expr, 0) = get_temp_regvar (TREE_TYPE (op), op);
11647 *walk_subtrees = 0;
11649 else if (!EXPR_P (expr) || !TREE_SIDE_EFFECTS (expr))
11650 *walk_subtrees = 0;
11651 return NULL;
11654 /* Entry point for the above. */
11656 static void
11657 stabilize_vla_size (tree size)
11659 hash_set<tree> pset;
11660 /* Break out any function calls into temporary variables. */
11661 cp_walk_tree (&size, stabilize_save_expr_r, &pset, &pset);
11664 /* Reduce a SIZEOF_EXPR to its value. */
11666 tree
11667 fold_sizeof_expr (tree t)
11669 tree r;
11670 if (SIZEOF_EXPR_TYPE_P (t))
11671 r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
11672 TREE_TYPE (TREE_OPERAND (t, 0)),
11673 SIZEOF_EXPR, false, false);
11674 else if (TYPE_P (TREE_OPERAND (t, 0)))
11675 r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
11676 TREE_OPERAND (t, 0), SIZEOF_EXPR,
11677 false, false);
11678 else
11679 r = cxx_sizeof_or_alignof_expr (EXPR_LOCATION (t),
11680 TREE_OPERAND (t, 0), SIZEOF_EXPR,
11681 false, false);
11682 if (r == error_mark_node)
11683 r = size_one_node;
11684 return r;
11687 /* Given the SIZE (i.e., number of elements) in an array, compute
11688 an appropriate index type for the array. If non-NULL, NAME is
11689 the name of the entity being declared. */
11691 static tree
11692 compute_array_index_type_loc (location_t name_loc, tree name, tree size,
11693 tsubst_flags_t complain)
11695 if (error_operand_p (size))
11696 return error_mark_node;
11698 /* The type of the index being computed. */
11699 tree itype;
11701 /* The original numeric size as seen in the source code before
11702 conversion to size_t. */
11703 tree origsize = size;
11705 location_t loc = cp_expr_loc_or_loc (size, name ? name_loc : input_location);
11707 if (!type_dependent_expression_p (size))
11709 origsize = size = mark_rvalue_use (size);
11711 if (cxx_dialect < cxx11 && TREE_CODE (size) == NOP_EXPR
11712 && TREE_SIDE_EFFECTS (size))
11713 /* In C++98, we mark a non-constant array bound with a magic
11714 NOP_EXPR with TREE_SIDE_EFFECTS; don't fold in that case. */;
11715 else
11717 size = build_converted_constant_expr (size_type_node, size, complain);
11718 /* Pedantically a constant expression is required here and so
11719 __builtin_is_constant_evaluated () should fold to true if it
11720 is successfully folded into a constant. */
11721 size = fold_non_dependent_expr (size, complain,
11722 /*manifestly_const_eval=*/true);
11724 if (!TREE_CONSTANT (size))
11725 size = origsize;
11728 if (error_operand_p (size))
11729 return error_mark_node;
11731 /* The array bound must be an integer type. */
11732 tree type = TREE_TYPE (size);
11733 if (!INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
11735 if (!(complain & tf_error))
11736 return error_mark_node;
11737 if (name)
11738 error_at (loc, "size of array %qD has non-integral type %qT",
11739 name, type);
11740 else
11741 error_at (loc, "size of array has non-integral type %qT", type);
11742 size = integer_one_node;
11746 /* A type is dependent if it is...an array type constructed from any
11747 dependent type or whose size is specified by a constant expression
11748 that is value-dependent. */
11749 /* We can only call value_dependent_expression_p on integral constant
11750 expressions. */
11751 if (processing_template_decl
11752 && potential_constant_expression (size)
11753 && value_dependent_expression_p (size))
11755 /* Just build the index type and mark that it requires
11756 structural equality checks. */
11757 in_template:
11758 itype = build_index_type (build_min (MINUS_EXPR, sizetype,
11759 size, size_one_node));
11760 TYPE_DEPENDENT_P (itype) = 1;
11761 TYPE_DEPENDENT_P_VALID (itype) = 1;
11762 SET_TYPE_STRUCTURAL_EQUALITY (itype);
11763 return itype;
11766 if (TREE_CODE (size) != INTEGER_CST)
11768 tree folded = cp_fully_fold (size);
11769 if (TREE_CODE (folded) == INTEGER_CST)
11771 if (name)
11772 pedwarn (loc, OPT_Wpedantic, "size of array %qD is not an "
11773 "integral constant-expression", name);
11774 else
11775 pedwarn (loc, OPT_Wpedantic,
11776 "size of array is not an integral constant-expression");
11778 if (TREE_CONSTANT (size) && !TREE_CONSTANT (folded))
11779 /* We might have lost the TREE_CONSTANT flag e.g. when we are
11780 folding a conversion from a pointer to integral type. In that
11781 case issue an error below and don't treat this as a VLA. */;
11782 else
11783 /* Use the folded result for VLAs, too; it will have resolved
11784 SIZEOF_EXPR. */
11785 size = folded;
11788 /* Normally, the array-bound will be a constant. */
11789 if (TREE_CODE (size) == INTEGER_CST)
11791 /* The size to use in diagnostics that reflects the constant
11792 size used in the source, rather than SIZE massaged above. */
11793 tree diagsize = size;
11795 /* If the original size before conversion to size_t was signed
11796 and negative, convert it to ssizetype to restore the sign. */
11797 if (!TYPE_UNSIGNED (TREE_TYPE (origsize))
11798 && TREE_CODE (size) == INTEGER_CST
11799 && tree_int_cst_sign_bit (size))
11801 diagsize = fold_convert (ssizetype, size);
11803 /* Clear the overflow bit that may have been set as a result
11804 of the conversion from the sizetype of the new size to
11805 ssizetype. */
11806 TREE_OVERFLOW (diagsize) = false;
11809 /* Verify that the array has a positive number of elements
11810 and issue the appropriate diagnostic if it doesn't. */
11811 if (!valid_array_size_p (loc, diagsize, name, (complain & tf_error)))
11813 if (!(complain & tf_error))
11814 return error_mark_node;
11815 size = integer_one_node;
11817 /* As an extension we allow zero-sized arrays. */
11818 else if (integer_zerop (size))
11820 if (!(complain & tf_error))
11821 /* We must fail if performing argument deduction (as
11822 indicated by the state of complain), so that
11823 another substitution can be found. */
11824 return error_mark_node;
11825 else if (name)
11826 pedwarn (loc, OPT_Wpedantic,
11827 "ISO C++ forbids zero-size array %qD", name);
11828 else
11829 pedwarn (loc, OPT_Wpedantic,
11830 "ISO C++ forbids zero-size array");
11833 else if (TREE_CONSTANT (size)
11834 /* We don't allow VLAs at non-function scopes, or during
11835 tentative template substitution. */
11836 || !at_function_scope_p ()
11837 || !(complain & tf_error))
11839 if (!(complain & tf_error))
11840 return error_mark_node;
11841 /* `(int) &fn' is not a valid array bound. */
11842 if (name)
11843 error_at (loc,
11844 "size of array %qD is not an integral constant-expression",
11845 name);
11846 else
11847 error_at (loc, "size of array is not an integral constant-expression");
11848 size = integer_one_node;
11850 else if (pedantic && warn_vla != 0)
11852 if (name)
11853 pedwarn (name_loc, OPT_Wvla,
11854 "ISO C++ forbids variable length array %qD", name);
11855 else
11856 pedwarn (input_location, OPT_Wvla,
11857 "ISO C++ forbids variable length array");
11859 else if (warn_vla > 0)
11861 if (name)
11862 warning_at (name_loc, OPT_Wvla,
11863 "variable length array %qD is used", name);
11864 else
11865 warning (OPT_Wvla,
11866 "variable length array is used");
11869 if (processing_template_decl && !TREE_CONSTANT (size))
11870 goto in_template;
11871 else
11873 if (!TREE_CONSTANT (size))
11875 /* A variable sized array. Arrange for the SAVE_EXPR on the inside
11876 of the MINUS_EXPR, which allows the -1 to get folded with the +1
11877 that happens when building TYPE_SIZE. */
11878 size = variable_size (size);
11879 stabilize_vla_size (size);
11882 /* Compute the index of the largest element in the array. It is
11883 one less than the number of elements in the array. We save
11884 and restore PROCESSING_TEMPLATE_DECL so that computations in
11885 cp_build_binary_op will be appropriately folded. */
11887 processing_template_decl_sentinel s;
11888 itype = cp_build_binary_op (input_location,
11889 MINUS_EXPR,
11890 cp_convert (ssizetype, size, complain),
11891 cp_convert (ssizetype, integer_one_node,
11892 complain),
11893 complain);
11894 itype = maybe_constant_value (itype, NULL_TREE, mce_true);
11897 if (!TREE_CONSTANT (itype))
11899 if (sanitize_flags_p (SANITIZE_VLA)
11900 && current_function_decl != NULL_TREE)
11902 /* We have to add 1 -- in the ubsan routine we generate
11903 LE_EXPR rather than LT_EXPR. */
11904 tree t = fold_build2 (PLUS_EXPR, TREE_TYPE (itype), itype,
11905 build_one_cst (TREE_TYPE (itype)));
11906 t = ubsan_instrument_vla (input_location, t);
11907 finish_expr_stmt (t);
11910 /* Make sure that there was no overflow when creating to a signed
11911 index type. (For example, on a 32-bit machine, an array with
11912 size 2^32 - 1 is too big.) */
11913 else if (TREE_CODE (itype) == INTEGER_CST
11914 && TREE_OVERFLOW (itype))
11916 if (!(complain & tf_error))
11917 return error_mark_node;
11918 error ("overflow in array dimension");
11919 TREE_OVERFLOW (itype) = 0;
11923 /* Create and return the appropriate index type. */
11924 itype = build_index_type (itype);
11926 /* If the index type were dependent, we would have returned early, so
11927 remember that it isn't. */
11928 TYPE_DEPENDENT_P (itype) = 0;
11929 TYPE_DEPENDENT_P_VALID (itype) = 1;
11930 return itype;
11933 tree
11934 compute_array_index_type (tree name, tree size, tsubst_flags_t complain)
11936 return compute_array_index_type_loc (input_location, name, size, complain);
11939 /* Returns the scope (if any) in which the entity declared by
11940 DECLARATOR will be located. If the entity was declared with an
11941 unqualified name, NULL_TREE is returned. */
11943 tree
11944 get_scope_of_declarator (const cp_declarator *declarator)
11946 while (declarator && declarator->kind != cdk_id)
11947 declarator = declarator->declarator;
11949 /* If the declarator-id is a SCOPE_REF, the scope in which the
11950 declaration occurs is the first operand. */
11951 if (declarator
11952 && declarator->u.id.qualifying_scope)
11953 return declarator->u.id.qualifying_scope;
11955 /* Otherwise, the declarator is not a qualified name; the entity will
11956 be declared in the current scope. */
11957 return NULL_TREE;
11960 /* Returns an ARRAY_TYPE for an array with SIZE elements of the
11961 indicated TYPE. If non-NULL, NAME is the NAME of the declaration
11962 with this type. */
11964 static tree
11965 create_array_type_for_decl (tree name, tree type, tree size, location_t loc)
11967 tree itype = NULL_TREE;
11969 /* If things have already gone awry, bail now. */
11970 if (type == error_mark_node || size == error_mark_node)
11971 return error_mark_node;
11973 /* [dcl.type.class.deduct] prohibits forming an array of placeholder
11974 for a deduced class type. */
11975 if (template_placeholder_p (type))
11977 if (name)
11978 error_at (loc, "%qD declared as array of template placeholder "
11979 "type %qT", name, type);
11980 else
11981 error ("creating array of template placeholder type %qT", type);
11982 return error_mark_node;
11985 /* If there are some types which cannot be array elements,
11986 issue an error-message and return. */
11987 switch (TREE_CODE (type))
11989 case VOID_TYPE:
11990 if (name)
11991 error_at (loc, "declaration of %qD as array of void", name);
11992 else
11993 error ("creating array of void");
11994 return error_mark_node;
11996 case FUNCTION_TYPE:
11997 if (name)
11998 error_at (loc, "declaration of %qD as array of functions", name);
11999 else
12000 error ("creating array of functions");
12001 return error_mark_node;
12003 case REFERENCE_TYPE:
12004 if (name)
12005 error_at (loc, "declaration of %qD as array of references", name);
12006 else
12007 error ("creating array of references");
12008 return error_mark_node;
12010 case METHOD_TYPE:
12011 if (name)
12012 error_at (loc, "declaration of %qD as array of function members",
12013 name);
12014 else
12015 error ("creating array of function members");
12016 return error_mark_node;
12018 default:
12019 break;
12022 if (!verify_type_context (name ? loc : input_location,
12023 TCTX_ARRAY_ELEMENT, type))
12024 return error_mark_node;
12026 /* [dcl.array]
12028 The constant expressions that specify the bounds of the arrays
12029 can be omitted only for the first member of the sequence. */
12030 if (TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type))
12032 if (name)
12033 error_at (loc, "declaration of %qD as multidimensional array must "
12034 "have bounds for all dimensions except the first",
12035 name);
12036 else
12037 error ("multidimensional array must have bounds for all "
12038 "dimensions except the first");
12040 return error_mark_node;
12043 /* Figure out the index type for the array. */
12044 if (size)
12046 itype = compute_array_index_type_loc (loc, name, size,
12047 tf_warning_or_error);
12048 if (type_uses_auto (type)
12049 && variably_modified_type_p (itype, /*fn=*/NULL_TREE))
12051 sorry_at (loc, "variable-length array of %<auto%>");
12052 return error_mark_node;
12056 return build_cplus_array_type (type, itype);
12059 /* Returns the smallest location that is not UNKNOWN_LOCATION. */
12061 static location_t
12062 min_location (location_t loca, location_t locb)
12064 if (loca == UNKNOWN_LOCATION
12065 || (locb != UNKNOWN_LOCATION
12066 && linemap_location_before_p (line_table, locb, loca)))
12067 return locb;
12068 return loca;
12071 /* Returns the smallest location != UNKNOWN_LOCATION among the
12072 three stored in LOCATIONS[ds_const], LOCATIONS[ds_volatile],
12073 and LOCATIONS[ds_restrict]. */
12075 static location_t
12076 smallest_type_quals_location (int type_quals, const location_t* locations)
12078 location_t loc = UNKNOWN_LOCATION;
12080 if (type_quals & TYPE_QUAL_CONST)
12081 loc = locations[ds_const];
12083 if (type_quals & TYPE_QUAL_VOLATILE)
12084 loc = min_location (loc, locations[ds_volatile]);
12086 if (type_quals & TYPE_QUAL_RESTRICT)
12087 loc = min_location (loc, locations[ds_restrict]);
12089 return loc;
12092 /* Returns the smallest among the latter and locations[ds_type_spec]. */
12094 static location_t
12095 smallest_type_location (int type_quals, const location_t* locations)
12097 location_t loc = smallest_type_quals_location (type_quals, locations);
12098 return min_location (loc, locations[ds_type_spec]);
12101 static location_t
12102 smallest_type_location (const cp_decl_specifier_seq *declspecs)
12104 int type_quals = get_type_quals (declspecs);
12105 return smallest_type_location (type_quals, declspecs->locations);
12108 /* Check that it's OK to declare a function with the indicated TYPE
12109 and TYPE_QUALS. SFK indicates the kind of special function (if any)
12110 that this function is. OPTYPE is the type given in a conversion
12111 operator declaration, or the class type for a constructor/destructor.
12112 Returns the actual return type of the function; that may be different
12113 than TYPE if an error occurs, or for certain special functions. */
12115 static tree
12116 check_special_function_return_type (special_function_kind sfk,
12117 tree type,
12118 tree optype,
12119 int type_quals,
12120 const location_t* locations)
12122 switch (sfk)
12124 case sfk_constructor:
12125 if (type)
12126 error_at (smallest_type_location (type_quals, locations),
12127 "return type specification for constructor invalid");
12128 else if (type_quals != TYPE_UNQUALIFIED)
12129 error_at (smallest_type_quals_location (type_quals, locations),
12130 "qualifiers are not allowed on constructor declaration");
12132 if (targetm.cxx.cdtor_returns_this ())
12133 type = build_pointer_type (optype);
12134 else
12135 type = void_type_node;
12136 break;
12138 case sfk_destructor:
12139 if (type)
12140 error_at (smallest_type_location (type_quals, locations),
12141 "return type specification for destructor invalid");
12142 else if (type_quals != TYPE_UNQUALIFIED)
12143 error_at (smallest_type_quals_location (type_quals, locations),
12144 "qualifiers are not allowed on destructor declaration");
12146 /* We can't use the proper return type here because we run into
12147 problems with ambiguous bases and covariant returns. */
12148 if (targetm.cxx.cdtor_returns_this ())
12149 type = build_pointer_type (void_type_node);
12150 else
12151 type = void_type_node;
12152 break;
12154 case sfk_conversion:
12155 if (type)
12156 error_at (smallest_type_location (type_quals, locations),
12157 "return type specified for %<operator %T%>", optype);
12158 else if (type_quals != TYPE_UNQUALIFIED)
12159 error_at (smallest_type_quals_location (type_quals, locations),
12160 "qualifiers are not allowed on declaration of "
12161 "%<operator %T%>", optype);
12163 type = optype;
12164 break;
12166 case sfk_deduction_guide:
12167 if (type)
12168 error_at (smallest_type_location (type_quals, locations),
12169 "return type specified for deduction guide");
12170 else if (type_quals != TYPE_UNQUALIFIED)
12171 error_at (smallest_type_quals_location (type_quals, locations),
12172 "qualifiers are not allowed on declaration of "
12173 "deduction guide");
12174 if (TREE_CODE (optype) == TEMPLATE_TEMPLATE_PARM)
12176 error ("template template parameter %qT in declaration of "
12177 "deduction guide", optype);
12178 type = error_mark_node;
12180 else
12181 type = make_template_placeholder (CLASSTYPE_TI_TEMPLATE (optype));
12182 for (int i = 0; i < ds_last; ++i)
12183 if (i != ds_explicit && locations[i])
12184 error_at (locations[i],
12185 "%<decl-specifier%> in declaration of deduction guide");
12186 break;
12188 default:
12189 gcc_unreachable ();
12192 return type;
12195 /* A variable or data member (whose unqualified name is IDENTIFIER)
12196 has been declared with the indicated TYPE. If the TYPE is not
12197 acceptable, issue an error message and return a type to use for
12198 error-recovery purposes. */
12200 tree
12201 check_var_type (tree identifier, tree type, location_t loc)
12203 if (VOID_TYPE_P (type))
12205 if (!identifier)
12206 error_at (loc, "unnamed variable or field declared void");
12207 else if (identifier_p (identifier))
12209 gcc_assert (!IDENTIFIER_ANY_OP_P (identifier));
12210 error_at (loc, "variable or field %qE declared void",
12211 identifier);
12213 else
12214 error_at (loc, "variable or field declared void");
12215 type = error_mark_node;
12218 return type;
12221 /* Handle declaring DECL as an inline variable. */
12223 static void
12224 mark_inline_variable (tree decl, location_t loc)
12226 bool inlinep = true;
12227 if (! toplevel_bindings_p ())
12229 error_at (loc, "%<inline%> specifier invalid for variable "
12230 "%qD declared at block scope", decl);
12231 inlinep = false;
12233 else if (cxx_dialect < cxx17)
12234 pedwarn (loc, OPT_Wc__17_extensions, "inline variables are only available "
12235 "with %<-std=c++17%> or %<-std=gnu++17%>");
12236 if (inlinep)
12238 retrofit_lang_decl (decl);
12239 SET_DECL_VAR_DECLARED_INLINE_P (decl);
12244 /* Assign a typedef-given name to a class or enumeration type declared
12245 as anonymous at first. This was split out of grokdeclarator
12246 because it is also used in libcc1. */
12248 void
12249 name_unnamed_type (tree type, tree decl)
12251 gcc_assert (TYPE_UNNAMED_P (type));
12253 /* Replace the anonymous decl with the real decl. Be careful not to
12254 rename other typedefs (such as the self-reference) of type. */
12255 tree orig = TYPE_NAME (type);
12256 for (tree t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
12257 if (TYPE_NAME (t) == orig)
12258 TYPE_NAME (t) = decl;
12260 /* If this is a typedef within a template class, the nested
12261 type is a (non-primary) template. The name for the
12262 template needs updating as well. */
12263 if (TYPE_LANG_SPECIFIC (type) && CLASSTYPE_TEMPLATE_INFO (type))
12264 DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)) = DECL_NAME (decl);
12266 /* Adjust linkage now that we aren't unnamed anymore. */
12267 reset_type_linkage (type);
12269 /* FIXME remangle member functions; member functions of a
12270 type with external linkage have external linkage. */
12272 /* Check that our job is done, and that it would fail if we
12273 attempted to do it again. */
12274 gcc_assert (!TYPE_UNNAMED_P (type));
12277 /* Check that decltype(auto) was well-formed: only plain decltype(auto)
12278 is allowed. TYPE might contain a decltype(auto). Returns true if
12279 there was a problem, false otherwise. */
12281 static bool
12282 check_decltype_auto (location_t loc, tree type)
12284 if (tree a = type_uses_auto (type))
12286 if (AUTO_IS_DECLTYPE (a))
12288 if (a != type)
12290 error_at (loc, "%qT as type rather than plain "
12291 "%<decltype(auto)%>", type);
12292 return true;
12294 else if (TYPE_QUALS (type) != TYPE_UNQUALIFIED)
12296 error_at (loc, "%<decltype(auto)%> cannot be cv-qualified");
12297 return true;
12301 return false;
12304 /* Given declspecs and a declarator (abstract or otherwise), determine
12305 the name and type of the object declared and construct a DECL node
12306 for it.
12308 DECLSPECS points to the representation of declaration-specifier
12309 sequence that precedes declarator.
12311 DECL_CONTEXT says which syntactic context this declaration is in:
12312 NORMAL for most contexts. Make a VAR_DECL or FUNCTION_DECL or TYPE_DECL.
12313 FUNCDEF for a function definition. Like NORMAL but a few different
12314 error messages in each case. Return value may be zero meaning
12315 this definition is too screwy to try to parse.
12316 MEMFUNCDEF for a function definition. Like FUNCDEF but prepares to
12317 handle member functions (which have FIELD context).
12318 Return value may be zero meaning this definition is too screwy to
12319 try to parse.
12320 PARM for a parameter declaration (either within a function prototype
12321 or before a function body). Make a PARM_DECL, or return void_type_node.
12322 TPARM for a template parameter declaration.
12323 CATCHPARM for a parameter declaration before a catch clause.
12324 TYPENAME if for a typename (in a cast or sizeof).
12325 Don't make a DECL node; just return the ..._TYPE node.
12326 FIELD for a struct or union field; make a FIELD_DECL.
12327 BITFIELD for a field with specified width.
12329 INITIALIZED is as for start_decl.
12331 ATTRLIST is a pointer to the list of attributes, which may be NULL
12332 if there are none; *ATTRLIST may be modified if attributes from inside
12333 the declarator should be applied to the declaration.
12335 When this function is called, scoping variables (such as
12336 CURRENT_CLASS_TYPE) should reflect the scope in which the
12337 declaration occurs, not the scope in which the new declaration will
12338 be placed. For example, on:
12340 void S::f() { ... }
12342 when grokdeclarator is called for `S::f', the CURRENT_CLASS_TYPE
12343 should not be `S'.
12345 Returns a DECL (if a declarator is present), a TYPE (if there is no
12346 declarator, in cases like "struct S;"), or the ERROR_MARK_NODE if an
12347 error occurs. */
12349 tree
12350 grokdeclarator (const cp_declarator *declarator,
12351 cp_decl_specifier_seq *declspecs,
12352 enum decl_context decl_context,
12353 int initialized,
12354 tree* attrlist)
12356 tree type = NULL_TREE;
12357 int longlong = 0;
12358 int explicit_intN = 0;
12359 int int_n_alt = 0;
12360 int virtualp, explicitp, friendp, inlinep, staticp;
12361 int explicit_int = 0;
12362 int explicit_char = 0;
12363 int defaulted_int = 0;
12365 tree typedef_decl = NULL_TREE;
12366 const char *name = NULL;
12367 tree typedef_type = NULL_TREE;
12368 /* True if this declarator is a function definition. */
12369 bool funcdef_flag = false;
12370 cp_declarator_kind innermost_code = cdk_error;
12371 int bitfield = 0;
12372 #if 0
12373 /* See the code below that used this. */
12374 tree decl_attr = NULL_TREE;
12375 #endif
12377 /* Keep track of what sort of function is being processed
12378 so that we can warn about default return values, or explicit
12379 return values which do not match prescribed defaults. */
12380 special_function_kind sfk = sfk_none;
12382 tree dname = NULL_TREE;
12383 tree ctor_return_type = NULL_TREE;
12384 enum overload_flags flags = NO_SPECIAL;
12385 /* cv-qualifiers that apply to the declarator, for a declaration of
12386 a member function. */
12387 cp_cv_quals memfn_quals = TYPE_UNQUALIFIED;
12388 /* virt-specifiers that apply to the declarator, for a declaration of
12389 a member function. */
12390 cp_virt_specifiers virt_specifiers = VIRT_SPEC_UNSPECIFIED;
12391 /* ref-qualifier that applies to the declarator, for a declaration of
12392 a member function. */
12393 cp_ref_qualifier rqual = REF_QUAL_NONE;
12394 /* cv-qualifiers that apply to the type specified by the DECLSPECS. */
12395 int type_quals = get_type_quals (declspecs);
12396 tree raises = NULL_TREE;
12397 int template_count = 0;
12398 tree returned_attrs = NULL_TREE;
12399 tree parms = NULL_TREE;
12400 const cp_declarator *id_declarator;
12401 /* The unqualified name of the declarator; either an
12402 IDENTIFIER_NODE, BIT_NOT_EXPR, or TEMPLATE_ID_EXPR. */
12403 tree unqualified_id;
12404 /* The class type, if any, in which this entity is located,
12405 or NULL_TREE if none. Note that this value may be different from
12406 the current class type; for example if an attempt is made to declare
12407 "A::f" inside "B", this value will be "A". */
12408 tree ctype = current_class_type;
12409 /* The NAMESPACE_DECL for the namespace in which this entity is
12410 located. If an unqualified name is used to declare the entity,
12411 this value will be NULL_TREE, even if the entity is located at
12412 namespace scope. */
12413 tree in_namespace = NULL_TREE;
12414 cp_storage_class storage_class;
12415 bool unsigned_p, signed_p, short_p, long_p, thread_p;
12416 bool type_was_error_mark_node = false;
12417 bool parameter_pack_p = declarator ? declarator->parameter_pack_p : false;
12418 bool template_type_arg = false;
12419 bool template_parm_flag = false;
12420 bool typedef_p = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
12421 bool constexpr_p = decl_spec_seq_has_spec_p (declspecs, ds_constexpr);
12422 bool constinit_p = decl_spec_seq_has_spec_p (declspecs, ds_constinit);
12423 bool consteval_p = decl_spec_seq_has_spec_p (declspecs, ds_consteval);
12424 bool late_return_type_p = false;
12425 bool array_parameter_p = false;
12426 tree reqs = NULL_TREE;
12428 signed_p = decl_spec_seq_has_spec_p (declspecs, ds_signed);
12429 unsigned_p = decl_spec_seq_has_spec_p (declspecs, ds_unsigned);
12430 short_p = decl_spec_seq_has_spec_p (declspecs, ds_short);
12431 long_p = decl_spec_seq_has_spec_p (declspecs, ds_long);
12432 longlong = decl_spec_seq_has_spec_p (declspecs, ds_long_long);
12433 explicit_intN = declspecs->explicit_intN_p;
12434 int_n_alt = declspecs->int_n_alt;
12435 thread_p = decl_spec_seq_has_spec_p (declspecs, ds_thread);
12437 // Was concept_p specified? Note that ds_concept
12438 // implies ds_constexpr!
12439 bool concept_p = decl_spec_seq_has_spec_p (declspecs, ds_concept);
12440 if (concept_p)
12441 constexpr_p = true;
12443 if (decl_context == FUNCDEF)
12444 funcdef_flag = true, decl_context = NORMAL;
12445 else if (decl_context == MEMFUNCDEF)
12446 funcdef_flag = true, decl_context = FIELD;
12447 else if (decl_context == BITFIELD)
12448 bitfield = 1, decl_context = FIELD;
12449 else if (decl_context == TEMPLATE_TYPE_ARG)
12450 template_type_arg = true, decl_context = TYPENAME;
12451 else if (decl_context == TPARM)
12452 template_parm_flag = true, decl_context = PARM;
12454 if (initialized == SD_DEFAULTED || initialized == SD_DELETED)
12455 funcdef_flag = true;
12457 location_t typespec_loc = loc_or_input_loc (smallest_type_location
12458 (type_quals,
12459 declspecs->locations));
12460 location_t id_loc;
12461 location_t init_loc;
12462 if (declarator)
12464 id_loc = loc_or_input_loc (declarator->id_loc);
12465 init_loc = loc_or_input_loc (declarator->init_loc);
12467 else
12468 init_loc = id_loc = input_location;
12470 /* Look inside a declarator for the name being declared
12471 and get it as a string, for an error message. */
12472 for (id_declarator = declarator;
12473 id_declarator;
12474 id_declarator = id_declarator->declarator)
12476 if (id_declarator->kind != cdk_id)
12477 innermost_code = id_declarator->kind;
12479 switch (id_declarator->kind)
12481 case cdk_function:
12482 if (id_declarator->declarator
12483 && id_declarator->declarator->kind == cdk_id)
12485 sfk = id_declarator->declarator->u.id.sfk;
12486 if (sfk == sfk_destructor)
12487 flags = DTOR_FLAG;
12489 break;
12491 case cdk_id:
12493 tree qualifying_scope = id_declarator->u.id.qualifying_scope;
12494 tree decl = id_declarator->u.id.unqualified_name;
12495 if (!decl)
12496 break;
12497 if (qualifying_scope)
12499 if (check_for_bare_parameter_packs (qualifying_scope,
12500 id_declarator->id_loc))
12501 return error_mark_node;
12502 if (at_function_scope_p ())
12504 /* [dcl.meaning]
12506 A declarator-id shall not be qualified except
12507 for ...
12509 None of the cases are permitted in block
12510 scope. */
12511 if (qualifying_scope == global_namespace)
12512 error ("invalid use of qualified-name %<::%D%>",
12513 decl);
12514 else if (TYPE_P (qualifying_scope))
12515 error ("invalid use of qualified-name %<%T::%D%>",
12516 qualifying_scope, decl);
12517 else
12518 error ("invalid use of qualified-name %<%D::%D%>",
12519 qualifying_scope, decl);
12520 return error_mark_node;
12522 else if (TYPE_P (qualifying_scope))
12524 ctype = qualifying_scope;
12525 if (!MAYBE_CLASS_TYPE_P (ctype))
12527 error_at (id_declarator->id_loc,
12528 "%q#T is not a class or namespace", ctype);
12529 ctype = NULL_TREE;
12531 else if (innermost_code != cdk_function
12532 && current_class_type
12533 && !uniquely_derived_from_p (ctype,
12534 current_class_type))
12536 error_at (id_declarator->id_loc,
12537 "invalid use of qualified-name %<%T::%D%>",
12538 qualifying_scope, decl);
12539 return error_mark_node;
12542 else if (TREE_CODE (qualifying_scope) == NAMESPACE_DECL)
12543 in_namespace = qualifying_scope;
12545 switch (TREE_CODE (decl))
12547 case BIT_NOT_EXPR:
12549 if (innermost_code != cdk_function)
12551 error_at (EXPR_LOCATION (decl),
12552 "declaration of %qE as non-function", decl);
12553 return error_mark_node;
12555 else if (!qualifying_scope
12556 && !(current_class_type && at_class_scope_p ()))
12558 error_at (EXPR_LOCATION (decl),
12559 "declaration of %qE as non-member", decl);
12560 return error_mark_node;
12563 tree type = TREE_OPERAND (decl, 0);
12564 if (TYPE_P (type))
12565 type = constructor_name (type);
12566 name = identifier_to_locale (IDENTIFIER_POINTER (type));
12567 dname = decl;
12569 break;
12571 case TEMPLATE_ID_EXPR:
12573 tree fns = TREE_OPERAND (decl, 0);
12575 dname = fns;
12576 if (!identifier_p (dname))
12577 dname = OVL_NAME (dname);
12579 /* Fall through. */
12581 case IDENTIFIER_NODE:
12582 if (identifier_p (decl))
12583 dname = decl;
12585 if (IDENTIFIER_KEYWORD_P (dname))
12587 error ("declarator-id missing; using reserved word %qD",
12588 dname);
12589 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
12591 else if (!IDENTIFIER_CONV_OP_P (dname))
12592 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
12593 else
12595 gcc_assert (flags == NO_SPECIAL);
12596 flags = TYPENAME_FLAG;
12597 sfk = sfk_conversion;
12598 tree glob = get_global_binding (dname);
12599 if (glob && TREE_CODE (glob) == TYPE_DECL)
12600 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
12601 else
12602 name = "<invalid operator>";
12604 break;
12606 default:
12607 gcc_unreachable ();
12609 break;
12612 case cdk_array:
12613 case cdk_pointer:
12614 case cdk_reference:
12615 case cdk_ptrmem:
12616 break;
12618 case cdk_decomp:
12619 name = "structured binding";
12620 break;
12622 case cdk_error:
12623 return error_mark_node;
12625 default:
12626 gcc_unreachable ();
12628 if (id_declarator->kind == cdk_id)
12629 break;
12632 /* [dcl.fct.edf]
12634 The declarator in a function-definition shall have the form
12635 D1 ( parameter-declaration-clause) ... */
12636 if (funcdef_flag && innermost_code != cdk_function)
12638 error_at (id_loc, "function definition does not declare parameters");
12639 return error_mark_node;
12642 if (flags == TYPENAME_FLAG
12643 && innermost_code != cdk_function
12644 && ! (ctype && !declspecs->any_specifiers_p))
12646 error_at (id_loc, "declaration of %qD as non-function", dname);
12647 return error_mark_node;
12650 if (dname && identifier_p (dname))
12652 if (UDLIT_OPER_P (dname)
12653 && innermost_code != cdk_function)
12655 error_at (id_loc, "declaration of %qD as non-function", dname);
12656 return error_mark_node;
12659 if (IDENTIFIER_ANY_OP_P (dname))
12661 if (typedef_p)
12663 error_at (id_loc, "declaration of %qD as %<typedef%>", dname);
12664 return error_mark_node;
12666 else if (decl_context == PARM || decl_context == CATCHPARM)
12668 error_at (id_loc, "declaration of %qD as parameter", dname);
12669 return error_mark_node;
12674 /* Anything declared one level down from the top level
12675 must be one of the parameters of a function
12676 (because the body is at least two levels down). */
12678 /* This heuristic cannot be applied to C++ nodes! Fixed, however,
12679 by not allowing C++ class definitions to specify their parameters
12680 with xdecls (must be spec.d in the parmlist).
12682 Since we now wait to push a class scope until we are sure that
12683 we are in a legitimate method context, we must set oldcname
12684 explicitly (since current_class_name is not yet alive).
12686 We also want to avoid calling this a PARM if it is in a namespace. */
12688 if (decl_context == NORMAL && !toplevel_bindings_p ())
12690 cp_binding_level *b = current_binding_level;
12691 current_binding_level = b->level_chain;
12692 if (current_binding_level != 0 && toplevel_bindings_p ())
12693 decl_context = PARM;
12694 current_binding_level = b;
12697 if (name == NULL)
12698 name = decl_context == PARM ? "parameter" : "type name";
12700 if (consteval_p && constexpr_p)
12702 error_at (declspecs->locations[ds_consteval],
12703 "both %qs and %qs specified", "constexpr", "consteval");
12704 return error_mark_node;
12707 if (concept_p && typedef_p)
12709 error_at (declspecs->locations[ds_concept],
12710 "%qs cannot appear in a typedef declaration", "concept");
12711 return error_mark_node;
12714 if (constexpr_p && typedef_p)
12716 error_at (declspecs->locations[ds_constexpr],
12717 "%qs cannot appear in a typedef declaration", "constexpr");
12718 return error_mark_node;
12721 if (consteval_p && typedef_p)
12723 error_at (declspecs->locations[ds_consteval],
12724 "%qs cannot appear in a typedef declaration", "consteval");
12725 return error_mark_node;
12728 if (constinit_p && typedef_p)
12730 error_at (declspecs->locations[ds_constinit],
12731 "%qs cannot appear in a typedef declaration", "constinit");
12732 return error_mark_node;
12735 /* [dcl.spec]/2 "At most one of the constexpr, consteval, and constinit
12736 keywords shall appear in a decl-specifier-seq." */
12737 if (constinit_p && constexpr_p)
12739 gcc_rich_location richloc (declspecs->locations[ds_constinit]);
12740 richloc.add_range (declspecs->locations[ds_constexpr]);
12741 error_at (&richloc,
12742 "can use at most one of the %<constinit%> and %<constexpr%> "
12743 "specifiers");
12744 return error_mark_node;
12747 /* If there were multiple types specified in the decl-specifier-seq,
12748 issue an error message. */
12749 if (declspecs->multiple_types_p)
12751 error_at (typespec_loc,
12752 "two or more data types in declaration of %qs", name);
12753 return error_mark_node;
12756 if (declspecs->conflicting_specifiers_p)
12757 return error_mark_node;
12759 /* Extract the basic type from the decl-specifier-seq. */
12760 type = declspecs->type;
12761 if (type == error_mark_node)
12763 type = NULL_TREE;
12764 type_was_error_mark_node = true;
12767 /* Ignore erroneous attributes. */
12768 if (attrlist && *attrlist == error_mark_node)
12769 *attrlist = NULL_TREE;
12771 /* An object declared as __attribute__((unavailable)) suppresses
12772 any reports of being declared with unavailable or deprecated
12773 items. An object declared as __attribute__((deprecated))
12774 suppresses warnings of uses of other deprecated items. */
12775 auto ds = make_temp_override (deprecated_state);
12776 if (attrlist && lookup_attribute ("unavailable", *attrlist))
12777 deprecated_state = UNAVAILABLE_DEPRECATED_SUPPRESS;
12778 else if (attrlist && lookup_attribute ("deprecated", *attrlist))
12779 deprecated_state = DEPRECATED_SUPPRESS;
12781 cp_handle_deprecated_or_unavailable (type);
12782 if (type && TREE_CODE (type) == TYPE_DECL)
12784 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (type));
12785 typedef_decl = type;
12786 type = TREE_TYPE (typedef_decl);
12787 if (DECL_ARTIFICIAL (typedef_decl))
12788 cp_handle_deprecated_or_unavailable (type);
12790 /* No type at all: default to `int', and set DEFAULTED_INT
12791 because it was not a user-defined typedef. */
12792 if (type == NULL_TREE)
12794 if (signed_p || unsigned_p || long_p || short_p)
12796 /* These imply 'int'. */
12797 type = integer_type_node;
12798 defaulted_int = 1;
12800 /* If we just have "complex", it is equivalent to "complex double". */
12801 else if (!longlong && !explicit_intN
12802 && decl_spec_seq_has_spec_p (declspecs, ds_complex))
12804 type = double_type_node;
12805 pedwarn (declspecs->locations[ds_complex], OPT_Wpedantic,
12806 "ISO C++ does not support plain %<complex%> meaning "
12807 "%<double complex%>");
12810 /* Gather flags. */
12811 explicit_int = declspecs->explicit_int_p;
12812 explicit_char = declspecs->explicit_char_p;
12814 #if 0
12815 /* See the code below that used this. */
12816 if (typedef_decl)
12817 decl_attr = DECL_ATTRIBUTES (typedef_decl);
12818 #endif
12819 typedef_type = type;
12821 if (sfk == sfk_conversion || sfk == sfk_deduction_guide)
12822 ctor_return_type = TREE_TYPE (dname);
12823 else
12824 ctor_return_type = ctype;
12826 if (sfk != sfk_none)
12828 type = check_special_function_return_type (sfk, type,
12829 ctor_return_type,
12830 type_quals,
12831 declspecs->locations);
12832 type_quals = TYPE_UNQUALIFIED;
12834 else if (type == NULL_TREE)
12836 int is_main;
12838 explicit_int = -1;
12840 /* We handle `main' specially here, because 'main () { }' is so
12841 common. With no options, it is allowed. With -Wreturn-type,
12842 it is a warning. It is only an error with -pedantic-errors. */
12843 is_main = (funcdef_flag
12844 && dname && identifier_p (dname)
12845 && MAIN_NAME_P (dname)
12846 && ctype == NULL_TREE
12847 && in_namespace == NULL_TREE
12848 && current_namespace == global_namespace);
12850 if (type_was_error_mark_node)
12851 /* We've already issued an error, don't complain more. */;
12852 else if (in_system_header_at (id_loc) || flag_ms_extensions)
12853 /* Allow it, sigh. */;
12854 else if (! is_main)
12855 permerror (id_loc, "ISO C++ forbids declaration of %qs with no type",
12856 name);
12857 else if (pedantic)
12858 pedwarn (id_loc, OPT_Wpedantic,
12859 "ISO C++ forbids declaration of %qs with no type", name);
12860 else
12861 warning_at (id_loc, OPT_Wreturn_type,
12862 "ISO C++ forbids declaration of %qs with no type", name);
12864 if (type_was_error_mark_node && template_parm_flag)
12865 /* FIXME we should be able to propagate the error_mark_node as is
12866 for other contexts too. */
12867 type = error_mark_node;
12868 else
12869 type = integer_type_node;
12872 ctype = NULL_TREE;
12874 if (explicit_intN)
12876 if (! int_n_enabled_p[declspecs->int_n_idx])
12878 error_at (declspecs->locations[ds_type_spec],
12879 "%<__int%d%> is not supported by this target",
12880 int_n_data[declspecs->int_n_idx].bitsize);
12881 explicit_intN = false;
12883 /* Don't pedwarn if the alternate "__intN__" form has been used instead
12884 of "__intN". */
12885 else if (!int_n_alt && pedantic)
12886 pedwarn (declspecs->locations[ds_type_spec], OPT_Wpedantic,
12887 "ISO C++ does not support %<__int%d%> for %qs",
12888 int_n_data[declspecs->int_n_idx].bitsize, name);
12891 /* Now process the modifiers that were specified
12892 and check for invalid combinations. */
12894 /* Long double is a special combination. */
12895 if (long_p && !longlong && TYPE_MAIN_VARIANT (type) == double_type_node)
12897 long_p = false;
12898 type = cp_build_qualified_type (long_double_type_node,
12899 cp_type_quals (type));
12902 /* Check all other uses of type modifiers. */
12904 if (unsigned_p || signed_p || long_p || short_p)
12906 location_t loc;
12907 const char *key;
12908 if (unsigned_p)
12910 key = "unsigned";
12911 loc = declspecs->locations[ds_unsigned];
12913 else if (signed_p)
12915 key = "signed";
12916 loc = declspecs->locations[ds_signed];
12918 else if (longlong)
12920 key = "long long";
12921 loc = declspecs->locations[ds_long_long];
12923 else if (long_p)
12925 key = "long";
12926 loc = declspecs->locations[ds_long];
12928 else /* if (short_p) */
12930 key = "short";
12931 loc = declspecs->locations[ds_short];
12934 int ok = 0;
12936 if (signed_p && unsigned_p)
12938 gcc_rich_location richloc (declspecs->locations[ds_signed]);
12939 richloc.add_range (declspecs->locations[ds_unsigned]);
12940 error_at (&richloc,
12941 "%<signed%> and %<unsigned%> specified together");
12943 else if (long_p && short_p)
12945 gcc_rich_location richloc (declspecs->locations[ds_long]);
12946 richloc.add_range (declspecs->locations[ds_short]);
12947 error_at (&richloc, "%<long%> and %<short%> specified together");
12949 else if (TREE_CODE (type) != INTEGER_TYPE
12950 || type == char8_type_node
12951 || type == char16_type_node
12952 || type == char32_type_node
12953 || ((long_p || short_p)
12954 && (explicit_char || explicit_intN)))
12955 error_at (loc, "%qs specified with %qT", key, type);
12956 else if (!explicit_int && !defaulted_int
12957 && !explicit_char && !explicit_intN)
12959 if (typedef_decl)
12961 pedwarn (loc, OPT_Wpedantic,
12962 "%qs specified with typedef-name %qD",
12963 key, typedef_decl);
12964 ok = !flag_pedantic_errors;
12965 /* PR108099: __int128_t comes from c_common_nodes_and_builtins,
12966 and is not built as a typedef. */
12967 if (is_typedef_decl (typedef_decl))
12968 type = DECL_ORIGINAL_TYPE (typedef_decl);
12970 else if (declspecs->decltype_p)
12971 error_at (loc, "%qs specified with %<decltype%>", key);
12972 else
12973 error_at (loc, "%qs specified with %<typeof%>", key);
12975 else
12976 ok = 1;
12978 /* Discard the type modifiers if they are invalid. */
12979 if (! ok)
12981 unsigned_p = false;
12982 signed_p = false;
12983 long_p = false;
12984 short_p = false;
12985 longlong = 0;
12989 /* Decide whether an integer type is signed or not.
12990 Optionally treat bitfields as signed by default. */
12991 if (unsigned_p
12992 /* [class.bit]
12994 It is implementation-defined whether a plain (neither
12995 explicitly signed or unsigned) char, short, int, or long
12996 bit-field is signed or unsigned.
12998 Naturally, we extend this to long long as well. Note that
12999 this does not include wchar_t. */
13000 || (bitfield && !flag_signed_bitfields
13001 && !signed_p
13002 /* A typedef for plain `int' without `signed' can be
13003 controlled just like plain `int', but a typedef for
13004 `signed int' cannot be so controlled. */
13005 && !(typedef_decl
13006 && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl))
13007 && TREE_CODE (type) == INTEGER_TYPE
13008 && !same_type_p (TYPE_MAIN_VARIANT (type), wchar_type_node)))
13010 if (explicit_intN)
13011 type = int_n_trees[declspecs->int_n_idx].unsigned_type;
13012 else if (longlong)
13013 type = long_long_unsigned_type_node;
13014 else if (long_p)
13015 type = long_unsigned_type_node;
13016 else if (short_p)
13017 type = short_unsigned_type_node;
13018 else if (type == char_type_node)
13019 type = unsigned_char_type_node;
13020 else if (typedef_decl)
13021 type = c_common_unsigned_type (type);
13022 else
13023 type = unsigned_type_node;
13025 else if (signed_p && type == char_type_node)
13026 type = signed_char_type_node;
13027 else if (explicit_intN)
13028 type = int_n_trees[declspecs->int_n_idx].signed_type;
13029 else if (longlong)
13030 type = long_long_integer_type_node;
13031 else if (long_p)
13032 type = long_integer_type_node;
13033 else if (short_p)
13034 type = short_integer_type_node;
13035 else if (signed_p && typedef_decl)
13036 type = c_common_signed_type (type);
13038 if (decl_spec_seq_has_spec_p (declspecs, ds_complex))
13040 if (TREE_CODE (type) != INTEGER_TYPE && TREE_CODE (type) != REAL_TYPE)
13041 error_at (declspecs->locations[ds_complex],
13042 "complex invalid for %qs", name);
13043 /* If a modifier is specified, the resulting complex is the complex
13044 form of TYPE. E.g, "complex short" is "complex short int". */
13045 else if (type == integer_type_node)
13046 type = complex_integer_type_node;
13047 else if (type == float_type_node)
13048 type = complex_float_type_node;
13049 else if (type == double_type_node)
13050 type = complex_double_type_node;
13051 else if (type == long_double_type_node)
13052 type = complex_long_double_type_node;
13053 else
13054 type = build_complex_type (type);
13057 /* If we're using the injected-class-name to form a compound type or a
13058 declaration, replace it with the underlying class so we don't get
13059 redundant typedefs in the debug output. But if we are returning the
13060 type unchanged, leave it alone so that it's available to
13061 maybe_get_template_decl_from_type_decl. */
13062 if (CLASS_TYPE_P (type)
13063 && DECL_SELF_REFERENCE_P (TYPE_NAME (type))
13064 && type == TREE_TYPE (TYPE_NAME (type))
13065 && (declarator || type_quals))
13066 type = DECL_ORIGINAL_TYPE (TYPE_NAME (type));
13068 type_quals |= cp_type_quals (type);
13069 type = cp_build_qualified_type
13070 (type, type_quals, ((((typedef_decl && !DECL_ARTIFICIAL (typedef_decl))
13071 || declspecs->decltype_p)
13072 ? tf_ignore_bad_quals : 0) | tf_warning_or_error));
13073 /* We might have ignored or rejected some of the qualifiers. */
13074 type_quals = cp_type_quals (type);
13076 if (cxx_dialect >= cxx17 && type && is_auto (type)
13077 && innermost_code != cdk_function
13078 /* Placeholder in parm gets a better error below. */
13079 && !(decl_context == PARM || decl_context == CATCHPARM)
13080 && id_declarator && declarator != id_declarator)
13081 if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (type))
13083 auto_diagnostic_group g;
13084 gcc_rich_location richloc (typespec_loc);
13085 richloc.add_fixit_insert_after ("<>");
13086 error_at (&richloc, "missing template argument list after %qE; "
13087 "for deduction, template placeholder must be followed "
13088 "by a simple declarator-id", tmpl);
13089 inform (DECL_SOURCE_LOCATION (tmpl), "%qD declared here", tmpl);
13090 type = error_mark_node;
13093 staticp = 0;
13094 inlinep = decl_spec_seq_has_spec_p (declspecs, ds_inline);
13095 virtualp = decl_spec_seq_has_spec_p (declspecs, ds_virtual);
13096 explicitp = decl_spec_seq_has_spec_p (declspecs, ds_explicit);
13098 storage_class = declspecs->storage_class;
13099 if (storage_class == sc_static)
13100 staticp = 1 + (decl_context == FIELD);
13101 else if (decl_context == FIELD && sfk == sfk_deduction_guide)
13102 /* Treat class-scope deduction guides as static member functions
13103 so that they get a FUNCTION_TYPE instead of a METHOD_TYPE. */
13104 staticp = 2;
13106 if (virtualp)
13108 if (staticp == 2)
13110 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
13111 richloc.add_range (declspecs->locations[ds_storage_class]);
13112 error_at (&richloc, "member %qD cannot be declared both %<virtual%> "
13113 "and %<static%>", dname);
13114 storage_class = sc_none;
13115 staticp = 0;
13117 if (constexpr_p && pedantic && cxx_dialect < cxx20)
13119 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
13120 richloc.add_range (declspecs->locations[ds_constexpr]);
13121 pedwarn (&richloc, OPT_Wc__20_extensions, "member %qD can be "
13122 "declared both %<virtual%> and %<constexpr%> only in "
13123 "%<-std=c++20%> or %<-std=gnu++20%>", dname);
13126 friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
13128 /* Issue errors about use of storage classes for parameters. */
13129 if (decl_context == PARM)
13131 if (typedef_p)
13133 error_at (declspecs->locations[ds_typedef],
13134 "typedef declaration invalid in parameter declaration");
13135 return error_mark_node;
13137 else if (template_parm_flag && storage_class != sc_none)
13139 error_at (min_location (declspecs->locations[ds_thread],
13140 declspecs->locations[ds_storage_class]),
13141 "storage class specified for template parameter %qs",
13142 name);
13143 return error_mark_node;
13145 else if (storage_class == sc_static
13146 || storage_class == sc_extern
13147 || thread_p)
13149 error_at (min_location (declspecs->locations[ds_thread],
13150 declspecs->locations[ds_storage_class]),
13151 "storage class specified for parameter %qs", name);
13152 return error_mark_node;
13155 /* Function parameters cannot be concept. */
13156 if (concept_p)
13158 error_at (declspecs->locations[ds_concept],
13159 "a parameter cannot be declared %qs", "concept");
13160 concept_p = 0;
13161 constexpr_p = 0;
13163 /* Function parameters cannot be constexpr. If we saw one, moan
13164 and pretend it wasn't there. */
13165 else if (constexpr_p)
13167 error_at (declspecs->locations[ds_constexpr],
13168 "a parameter cannot be declared %qs", "constexpr");
13169 constexpr_p = 0;
13171 if (constinit_p)
13173 error_at (declspecs->locations[ds_constinit],
13174 "a parameter cannot be declared %qs", "constinit");
13175 constinit_p = 0;
13177 if (consteval_p)
13179 error_at (declspecs->locations[ds_consteval],
13180 "a parameter cannot be declared %qs", "consteval");
13181 consteval_p = 0;
13185 /* Give error if `virtual' is used outside of class declaration. */
13186 if (virtualp
13187 && (current_class_name == NULL_TREE || decl_context != FIELD))
13189 error_at (declspecs->locations[ds_virtual],
13190 "%<virtual%> outside class declaration");
13191 virtualp = 0;
13194 if (innermost_code == cdk_decomp)
13196 location_t loc = (declarator->kind == cdk_reference
13197 ? declarator->declarator->id_loc : declarator->id_loc);
13198 if (inlinep)
13199 error_at (declspecs->locations[ds_inline],
13200 "structured binding declaration cannot be %qs", "inline");
13201 if (typedef_p)
13202 error_at (declspecs->locations[ds_typedef],
13203 "structured binding declaration cannot be %qs", "typedef");
13204 if (constexpr_p && !concept_p)
13205 error_at (declspecs->locations[ds_constexpr], "structured "
13206 "binding declaration cannot be %qs", "constexpr");
13207 if (consteval_p)
13208 error_at (declspecs->locations[ds_consteval], "structured "
13209 "binding declaration cannot be %qs", "consteval");
13210 if (thread_p && cxx_dialect < cxx20)
13211 pedwarn (declspecs->locations[ds_thread], OPT_Wc__20_extensions,
13212 "structured binding declaration can be %qs only in "
13213 "%<-std=c++20%> or %<-std=gnu++20%>",
13214 declspecs->gnu_thread_keyword_p
13215 ? "__thread" : "thread_local");
13216 if (concept_p)
13217 error_at (declspecs->locations[ds_concept],
13218 "structured binding declaration cannot be %qs", "concept");
13219 /* [dcl.struct.bind] "A cv that includes volatile is deprecated." */
13220 if (type_quals & TYPE_QUAL_VOLATILE)
13221 warning_at (declspecs->locations[ds_volatile], OPT_Wvolatile,
13222 "%<volatile%>-qualified structured binding is deprecated");
13223 switch (storage_class)
13225 case sc_none:
13226 break;
13227 case sc_register:
13228 error_at (loc, "structured binding declaration cannot be %qs",
13229 "register");
13230 break;
13231 case sc_static:
13232 if (cxx_dialect < cxx20)
13233 pedwarn (loc, OPT_Wc__20_extensions,
13234 "structured binding declaration can be %qs only in "
13235 "%<-std=c++20%> or %<-std=gnu++20%>", "static");
13236 break;
13237 case sc_extern:
13238 error_at (loc, "structured binding declaration cannot be %qs",
13239 "extern");
13240 break;
13241 case sc_mutable:
13242 error_at (loc, "structured binding declaration cannot be %qs",
13243 "mutable");
13244 break;
13245 case sc_auto:
13246 error_at (loc, "structured binding declaration cannot be "
13247 "C++98 %<auto%>");
13248 break;
13249 default:
13250 gcc_unreachable ();
13252 if (TREE_CODE (type) != TEMPLATE_TYPE_PARM
13253 || TYPE_IDENTIFIER (type) != auto_identifier)
13255 if (type != error_mark_node)
13257 auto_diagnostic_group d;
13258 error_at (loc, "structured binding declaration cannot have "
13259 "type %qT", type);
13260 inform (loc,
13261 "type must be cv-qualified %<auto%> or reference to "
13262 "cv-qualified %<auto%>");
13264 type = build_qualified_type (make_auto (), type_quals);
13265 declspecs->type = type;
13267 else if (PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type))
13268 pedwarn (loc, OPT_Wpedantic,
13269 "structured binding declaration cannot have constrained "
13270 "%<auto%> type %qT", type);
13271 inlinep = 0;
13272 typedef_p = 0;
13273 constexpr_p = 0;
13274 consteval_p = 0;
13275 concept_p = 0;
13276 if (storage_class != sc_static)
13278 storage_class = sc_none;
13279 declspecs->storage_class = sc_none;
13283 /* Static anonymous unions are dealt with here. */
13284 if (staticp && decl_context == TYPENAME
13285 && declspecs->type
13286 && ANON_AGGR_TYPE_P (declspecs->type))
13287 decl_context = FIELD;
13289 /* Warn about storage classes that are invalid for certain
13290 kinds of declarations (parameters, typenames, etc.). */
13291 if (thread_p
13292 && ((storage_class
13293 && storage_class != sc_extern
13294 && storage_class != sc_static)
13295 || typedef_p))
13297 location_t loc
13298 = min_location (declspecs->locations[ds_thread],
13299 declspecs->locations[ds_storage_class]);
13300 error_at (loc, "multiple storage classes in declaration of %qs", name);
13301 thread_p = false;
13303 if (decl_context != NORMAL
13304 && ((storage_class != sc_none
13305 && storage_class != sc_mutable)
13306 || thread_p))
13308 if ((decl_context == PARM || decl_context == CATCHPARM)
13309 && (storage_class == sc_register
13310 || storage_class == sc_auto))
13312 else if (typedef_p)
13314 else if (decl_context == FIELD
13315 /* C++ allows static class elements. */
13316 && storage_class == sc_static)
13317 /* C++ also allows inlines and signed and unsigned elements,
13318 but in those cases we don't come in here. */
13320 else
13322 location_t loc
13323 = min_location (declspecs->locations[ds_thread],
13324 declspecs->locations[ds_storage_class]);
13325 if (decl_context == FIELD)
13326 error_at (loc, "storage class specified for %qs", name);
13327 else if (decl_context == PARM || decl_context == CATCHPARM)
13328 error_at (loc, "storage class specified for parameter %qs", name);
13329 else
13330 error_at (loc, "storage class specified for typename");
13331 if (storage_class == sc_register
13332 || storage_class == sc_auto
13333 || storage_class == sc_extern
13334 || thread_p)
13335 storage_class = sc_none;
13338 else if (storage_class == sc_extern && funcdef_flag
13339 && ! toplevel_bindings_p ())
13340 error ("nested function %qs declared %<extern%>", name);
13341 else if (toplevel_bindings_p ())
13343 if (storage_class == sc_auto)
13344 error_at (declspecs->locations[ds_storage_class],
13345 "top-level declaration of %qs specifies %<auto%>", name);
13347 else if (thread_p
13348 && storage_class != sc_extern
13349 && storage_class != sc_static)
13351 if (declspecs->gnu_thread_keyword_p)
13352 pedwarn (declspecs->locations[ds_thread],
13353 0, "function-scope %qs implicitly auto and "
13354 "declared %<__thread%>", name);
13356 /* When thread_local is applied to a variable of block scope the
13357 storage-class-specifier static is implied if it does not appear
13358 explicitly. */
13359 storage_class = declspecs->storage_class = sc_static;
13360 staticp = 1;
13363 if (storage_class && friendp)
13365 error_at (min_location (declspecs->locations[ds_thread],
13366 declspecs->locations[ds_storage_class]),
13367 "storage class specifiers invalid in friend function "
13368 "declarations");
13369 storage_class = sc_none;
13370 staticp = 0;
13373 if (!id_declarator)
13374 unqualified_id = NULL_TREE;
13375 else
13377 unqualified_id = id_declarator->u.id.unqualified_name;
13378 switch (TREE_CODE (unqualified_id))
13380 case BIT_NOT_EXPR:
13381 unqualified_id = TREE_OPERAND (unqualified_id, 0);
13382 if (TYPE_P (unqualified_id))
13383 unqualified_id = constructor_name (unqualified_id);
13384 break;
13386 case IDENTIFIER_NODE:
13387 case TEMPLATE_ID_EXPR:
13388 break;
13390 default:
13391 gcc_unreachable ();
13395 if (declspecs->std_attributes
13396 && !diagnose_misapplied_contracts (declspecs->std_attributes))
13398 location_t attr_loc = declspecs->locations[ds_std_attribute];
13399 auto_diagnostic_group d;
13400 if (any_nonignored_attribute_p (declspecs->std_attributes)
13401 && warning_at (attr_loc, OPT_Wattributes, "attribute ignored"))
13402 inform (attr_loc, "an attribute that appertains to a type-specifier "
13403 "is ignored");
13406 if (attrlist)
13407 diagnose_misapplied_contracts (*attrlist);
13409 /* Skip over build_memfn_type when a FUNCTION_DECL is an xobj memfn. */
13410 bool is_xobj_member_function = false;
13411 /* Determine the type of the entity declared by recurring on the
13412 declarator. */
13413 for (; declarator; declarator = declarator->declarator)
13415 const cp_declarator *inner_declarator;
13416 tree attrs;
13418 if (type == error_mark_node)
13419 return error_mark_node;
13421 attrs = declarator->attributes;
13422 if (attrs)
13424 int attr_flags;
13426 attr_flags = 0;
13427 if (declarator->kind == cdk_id)
13428 attr_flags |= (int) ATTR_FLAG_DECL_NEXT;
13429 if (declarator->kind == cdk_function)
13430 attr_flags |= (int) ATTR_FLAG_FUNCTION_NEXT;
13431 if (declarator->kind == cdk_array)
13432 attr_flags |= (int) ATTR_FLAG_ARRAY_NEXT;
13433 tree late_attrs = NULL_TREE;
13434 if (decl_context != PARM && decl_context != TYPENAME)
13435 /* Assume that any attributes that get applied late to
13436 templates will DTRT when applied to the declaration
13437 as a whole. */
13438 late_attrs = splice_template_attributes (&attrs, type);
13439 returned_attrs = decl_attributes (&type,
13440 attr_chainon (returned_attrs,
13441 attrs),
13442 attr_flags);
13443 returned_attrs = attr_chainon (late_attrs, returned_attrs);
13446 inner_declarator = declarator->declarator;
13448 /* Check that contracts aren't misapplied. */
13449 if (tree contract_attr = find_contract (declarator->std_attributes))
13450 if (declarator->kind != cdk_function
13451 || innermost_code != cdk_function)
13452 diagnose_misapplied_contracts (contract_attr);
13454 /* We don't want to warn in parameter context because we don't
13455 yet know if the parse will succeed, and this might turn out
13456 to be a constructor call. */
13457 if (decl_context != PARM
13458 && decl_context != TYPENAME
13459 && !typedef_p
13460 && declarator->parenthesized != UNKNOWN_LOCATION
13461 /* If the type is class-like and the inner name used a
13462 global namespace qualifier, we need the parens.
13463 Unfortunately all we can tell is whether a qualified name
13464 was used or not. */
13465 && !(inner_declarator
13466 && inner_declarator->kind == cdk_id
13467 && inner_declarator->u.id.qualifying_scope
13468 && (MAYBE_CLASS_TYPE_P (type)
13469 || TREE_CODE (type) == ENUMERAL_TYPE)))
13471 auto_diagnostic_group d;
13472 if (warning_at (declarator->parenthesized, OPT_Wparentheses,
13473 "unnecessary parentheses in declaration of %qs",
13474 name))
13476 gcc_rich_location iloc (declarator->parenthesized);
13477 iloc.add_fixit_remove (get_start (declarator->parenthesized));
13478 iloc.add_fixit_remove (get_finish (declarator->parenthesized));
13479 inform (&iloc, "remove parentheses");
13482 if (declarator->kind == cdk_id || declarator->kind == cdk_decomp)
13483 break;
13485 switch (declarator->kind)
13487 case cdk_array:
13488 type = create_array_type_for_decl (dname, type,
13489 declarator->u.array.bounds,
13490 declarator->id_loc);
13491 if (!valid_array_size_p (dname
13492 ? declarator->id_loc : input_location,
13493 type, dname))
13494 type = error_mark_node;
13496 if (declarator->std_attributes)
13497 /* [dcl.array]/1:
13499 The optional attribute-specifier-seq appertains to the
13500 array type. */
13501 decl_attributes (&type, declarator->std_attributes, 0);
13502 break;
13504 case cdk_function:
13506 tree arg_types;
13507 int funcdecl_p;
13509 /* Declaring a function type. */
13511 /* Pick up type qualifiers which should be applied to `this'. */
13512 memfn_quals = declarator->u.function.qualifiers;
13513 /* Pick up virt-specifiers. */
13514 virt_specifiers = declarator->u.function.virt_specifiers;
13515 /* And ref-qualifier, too */
13516 rqual = declarator->u.function.ref_qualifier;
13517 /* And tx-qualifier. */
13518 tree tx_qual = declarator->u.function.tx_qualifier;
13519 /* Pick up the exception specifications. */
13520 raises = declarator->u.function.exception_specification;
13521 /* If the exception-specification is ill-formed, let's pretend
13522 there wasn't one. */
13523 if (raises == error_mark_node)
13524 raises = NULL_TREE;
13526 auto find_xobj_parm = [](tree parm_list)
13528 /* There is no need to iterate over the list,
13529 only the first parm can be a valid xobj parm. */
13530 if (!parm_list || TREE_PURPOSE (parm_list) != this_identifier)
13531 return NULL_TREE;
13532 /* If we make it here, we are looking at an xobj parm.
13534 Non-null 'purpose' usually means the parm has a default
13535 argument, we don't want to violate this assumption. */
13536 TREE_PURPOSE (parm_list) = NULL_TREE;
13537 return TREE_VALUE (parm_list);
13540 tree xobj_parm
13541 = find_xobj_parm (declarator->u.function.parameters);
13542 is_xobj_member_function = xobj_parm;
13544 if (xobj_parm && cxx_dialect < cxx23)
13545 pedwarn (DECL_SOURCE_LOCATION (xobj_parm), OPT_Wc__23_extensions,
13546 "explicit object member function only available "
13547 "with %<-std=c++23%> or %<-std=gnu++23%>");
13549 if (xobj_parm && decl_context == TYPENAME)
13551 /* We inform in every case, just differently depending on what
13552 case it is. */
13553 auto_diagnostic_group d;
13554 bool ptr_type = true;
13555 /* If declarator->kind is cdk_function and we are at the end of
13556 the declarator chain, we are looking at a function type. */
13557 if (!declarator->declarator)
13559 error_at (DECL_SOURCE_LOCATION (xobj_parm),
13560 "a function type cannot "
13561 "have an explicit object parameter");
13562 ptr_type = false;
13564 else if (declarator->declarator->kind == cdk_pointer)
13565 error_at (DECL_SOURCE_LOCATION (xobj_parm),
13566 "a pointer to function type cannot "
13567 "have an explicit object parameter");
13568 else if (declarator->declarator->kind == cdk_ptrmem)
13569 error_at (DECL_SOURCE_LOCATION (xobj_parm),
13570 "a pointer to member function type "
13571 "cannot have an explicit object parameter");
13572 else
13573 gcc_unreachable ();
13575 /* The locations being used here are probably not correct. */
13576 if (ptr_type)
13577 inform (DECL_SOURCE_LOCATION (xobj_parm),
13578 "the type of a pointer to explicit object member "
13579 "function is a regular pointer to function type");
13580 else
13581 inform (DECL_SOURCE_LOCATION (xobj_parm),
13582 "the type of an explicit object "
13583 "member function is a regular function type");
13584 /* Ideally we should synthesize the correct syntax
13585 for the user, perhaps this could be added later. */
13587 /* Since a valid xobj parm has its purpose cleared in find_xobj_parm
13588 the first parm node will never erroneously be detected here. */
13590 auto_diagnostic_group d;
13591 bool bad_xobj_parm_encountered = false;
13592 for (tree parm = declarator->u.function.parameters;
13593 parm && parm != void_list_node;
13594 parm = TREE_CHAIN (parm))
13596 if (TREE_PURPOSE (parm) != this_identifier)
13597 continue;
13598 bad_xobj_parm_encountered = true;
13599 TREE_PURPOSE (parm) = NULL_TREE;
13600 gcc_rich_location bad_xobj_parm
13601 (DECL_SOURCE_LOCATION (TREE_VALUE (parm)));
13602 error_at (&bad_xobj_parm,
13603 "only the first parameter of a member function "
13604 "can be declared as an explicit object parameter");
13606 if (bad_xobj_parm_encountered && xobj_parm)
13607 inform (DECL_SOURCE_LOCATION (xobj_parm),
13608 "valid explicit object parameter declared here");
13611 if (reqs)
13612 error_at (location_of (reqs), "requires-clause on return type");
13613 reqs = declarator->u.function.requires_clause;
13615 /* Say it's a definition only for the CALL_EXPR
13616 closest to the identifier. */
13617 funcdecl_p = inner_declarator && inner_declarator->kind == cdk_id;
13619 /* Handle a late-specified return type. */
13620 tree late_return_type = declarator->u.function.late_return_type;
13621 if (tree auto_node = type_uses_auto (type))
13623 if (!late_return_type)
13625 if (!funcdecl_p)
13626 /* auto (*fp)() = f; is OK. */;
13627 else if (current_class_type
13628 && LAMBDA_TYPE_P (current_class_type))
13629 /* OK for C++11 lambdas. */;
13630 else if (cxx_dialect < cxx14)
13632 auto_diagnostic_group d;
13633 error_at (typespec_loc, "%qs function uses "
13634 "%<auto%> type specifier without "
13635 "trailing return type", name);
13636 inform (typespec_loc,
13637 "deduced return type only available "
13638 "with %<-std=c++14%> or %<-std=gnu++14%>");
13640 else if (virtualp)
13642 error_at (typespec_loc, "virtual function "
13643 "cannot have deduced return type");
13644 virtualp = false;
13647 else if (!is_auto (type) && sfk != sfk_conversion)
13649 error_at (typespec_loc, "%qs function with trailing "
13650 "return type has %qT as its type rather "
13651 "than plain %<auto%>", name, type);
13652 return error_mark_node;
13654 else if (is_auto (type) && AUTO_IS_DECLTYPE (type))
13656 if (funcdecl_p)
13657 error_at (typespec_loc,
13658 "%qs function with trailing return type "
13659 "has %<decltype(auto)%> as its type "
13660 "rather than plain %<auto%>", name);
13661 else
13662 error_at (typespec_loc,
13663 "invalid use of %<decltype(auto)%>");
13664 return error_mark_node;
13666 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node);
13667 if (!tmpl)
13668 if (tree late_auto = type_uses_auto (late_return_type))
13669 tmpl = CLASS_PLACEHOLDER_TEMPLATE (late_auto);
13670 if (tmpl)
13672 if (!funcdecl_p || !dguide_name_p (unqualified_id))
13674 auto_diagnostic_group g;
13675 error_at (typespec_loc, "deduced class "
13676 "type %qD in function return type",
13677 DECL_NAME (tmpl));
13678 inform (DECL_SOURCE_LOCATION (tmpl),
13679 "%qD declared here", tmpl);
13680 return error_mark_node;
13682 else if (!late_return_type)
13684 auto_diagnostic_group d;
13685 error_at (declarator->id_loc, "deduction guide "
13686 "for %qT must have trailing return "
13687 "type", TREE_TYPE (tmpl));
13688 inform (DECL_SOURCE_LOCATION (tmpl),
13689 "%qD declared here", tmpl);
13690 return error_mark_node;
13692 else if (CLASS_TYPE_P (late_return_type)
13693 && CLASSTYPE_TEMPLATE_INFO (late_return_type)
13694 && (CLASSTYPE_TI_TEMPLATE (late_return_type)
13695 == tmpl))
13696 /* OK */;
13697 else
13698 error ("trailing return type %qT of deduction guide "
13699 "is not a specialization of %qT",
13700 late_return_type, TREE_TYPE (tmpl));
13703 else if (late_return_type
13704 && sfk != sfk_conversion)
13706 if (late_return_type == error_mark_node)
13707 return error_mark_node;
13708 if (cxx_dialect < cxx11)
13709 /* Not using maybe_warn_cpp0x because this should
13710 always be an error. */
13711 error_at (typespec_loc,
13712 "trailing return type only available "
13713 "with %<-std=c++11%> or %<-std=gnu++11%>");
13714 else
13715 error_at (typespec_loc, "%qs function with trailing "
13716 "return type not declared with %<auto%> "
13717 "type specifier", name);
13718 return error_mark_node;
13720 if (late_return_type && sfk == sfk_conversion)
13722 error ("a conversion function cannot have a trailing return type");
13723 return error_mark_node;
13725 type = splice_late_return_type (type, late_return_type);
13726 if (type == error_mark_node)
13727 return error_mark_node;
13729 if (late_return_type)
13731 late_return_type_p = true;
13732 type_quals = cp_type_quals (type);
13735 if (type_quals != TYPE_UNQUALIFIED)
13737 /* It's wrong, for instance, to issue a -Wignored-qualifiers
13738 warning for
13739 static_assert(!is_same_v<void(*)(), const void(*)()>);
13740 because there the qualifier matters. */
13741 if (funcdecl_p && (SCALAR_TYPE_P (type) || VOID_TYPE_P (type)))
13742 warning_at (typespec_loc, OPT_Wignored_qualifiers, "type "
13743 "qualifiers ignored on function return type");
13744 /* [dcl.fct] "A volatile-qualified return type is
13745 deprecated." */
13746 if (type_quals & TYPE_QUAL_VOLATILE)
13747 warning_at (typespec_loc, OPT_Wvolatile,
13748 "%<volatile%>-qualified return type is "
13749 "deprecated");
13751 /* We now know that the TYPE_QUALS don't apply to the
13752 decl, but to its return type. */
13753 type_quals = TYPE_UNQUALIFIED;
13756 /* Error about some types functions can't return. */
13758 if (TREE_CODE (type) == FUNCTION_TYPE)
13760 error_at (typespec_loc, "%qs declared as function returning "
13761 "a function", name);
13762 return error_mark_node;
13764 if (TREE_CODE (type) == ARRAY_TYPE)
13766 error_at (typespec_loc, "%qs declared as function returning "
13767 "an array", name);
13768 return error_mark_node;
13770 if (constinit_p && funcdecl_p)
13772 error_at (declspecs->locations[ds_constinit],
13773 "%<constinit%> on function return type is not "
13774 "allowed");
13775 return error_mark_node;
13778 if (check_decltype_auto (typespec_loc, type))
13779 return error_mark_node;
13781 if (ctype == NULL_TREE
13782 && decl_context == FIELD
13783 && funcdecl_p
13784 && friendp == 0)
13785 ctype = current_class_type;
13787 if (ctype && (sfk == sfk_constructor
13788 || sfk == sfk_destructor))
13790 /* We are within a class's scope. If our declarator name
13791 is the same as the class name, and we are defining
13792 a function, then it is a constructor/destructor, and
13793 therefore returns a void type. */
13795 /* ISO C++ 12.4/2. A destructor may not be declared
13796 const or volatile. A destructor may not be static.
13797 A destructor may not be declared with ref-qualifier.
13799 ISO C++ 12.1. A constructor may not be declared
13800 const or volatile. A constructor may not be
13801 virtual. A constructor may not be static.
13802 A constructor may not be declared with ref-qualifier. */
13803 if (staticp == 2)
13804 error_at (declspecs->locations[ds_storage_class],
13805 (flags == DTOR_FLAG)
13806 ? G_("destructor cannot be static member "
13807 "function")
13808 : G_("constructor cannot be static member "
13809 "function"));
13810 if (memfn_quals)
13812 error ((flags == DTOR_FLAG)
13813 ? G_("destructors may not be cv-qualified")
13814 : G_("constructors may not be cv-qualified"));
13815 memfn_quals = TYPE_UNQUALIFIED;
13818 if (rqual)
13820 maybe_warn_cpp0x (CPP0X_REF_QUALIFIER);
13821 error ((flags == DTOR_FLAG)
13822 ? G_("destructors may not be ref-qualified")
13823 : G_("constructors may not be ref-qualified"));
13824 rqual = REF_QUAL_NONE;
13827 if (decl_context == FIELD
13828 && !member_function_or_else (ctype,
13829 current_class_type,
13830 flags))
13831 return error_mark_node;
13833 if (flags != DTOR_FLAG)
13835 /* It's a constructor. */
13836 if (explicitp == 1)
13837 explicitp = 2;
13838 if (virtualp)
13840 permerror (declspecs->locations[ds_virtual],
13841 "constructors cannot be declared %<virtual%>");
13842 virtualp = 0;
13844 if (decl_context == FIELD
13845 && sfk != sfk_constructor)
13846 return error_mark_node;
13848 if (decl_context == FIELD)
13849 staticp = 0;
13851 else if (friendp)
13853 if (virtualp)
13855 /* Cannot be both friend and virtual. */
13856 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
13857 richloc.add_range (declspecs->locations[ds_friend]);
13858 error_at (&richloc, "virtual functions cannot be friends");
13859 friendp = 0;
13861 if (decl_context == NORMAL)
13862 error_at (declarator->id_loc,
13863 "friend declaration not in class definition");
13864 if (current_function_decl && funcdef_flag)
13866 error_at (declarator->id_loc,
13867 "cannot define friend function %qs in a local "
13868 "class definition", name);
13869 friendp = 0;
13871 /* [class.friend]/6: A function can be defined in a friend
13872 declaration if the function name is unqualified. */
13873 if (funcdef_flag && in_namespace)
13875 if (in_namespace == global_namespace)
13876 error_at (declarator->id_loc,
13877 "friend function definition %qs cannot have "
13878 "a name qualified with %<::%>", name);
13879 else
13880 error_at (declarator->id_loc,
13881 "friend function definition %qs cannot have "
13882 "a name qualified with %<%D::%>", name,
13883 in_namespace);
13886 else if (ctype && sfk == sfk_conversion)
13888 if (explicitp == 1)
13890 maybe_warn_cpp0x (CPP0X_EXPLICIT_CONVERSION);
13891 explicitp = 2;
13894 else if (sfk == sfk_deduction_guide)
13896 if (explicitp == 1)
13897 explicitp = 2;
13900 if (xobj_parm)
13902 if (!ctype
13903 && decl_context == NORMAL
13904 && (in_namespace
13905 || !declarator->declarator->u.id.qualifying_scope))
13906 error_at (DECL_SOURCE_LOCATION (xobj_parm),
13907 "a non-member function cannot have "
13908 "an explicit object parameter");
13909 else
13911 if (virtualp)
13913 auto_diagnostic_group d;
13914 error_at (declspecs->locations[ds_virtual],
13915 "an explicit object member function cannot "
13916 "be %<virtual%>");
13917 inform (DECL_SOURCE_LOCATION (xobj_parm),
13918 "explicit object parameter declared here");
13919 virtualp = false;
13921 if (staticp >= 2)
13923 auto_diagnostic_group d;
13924 error_at (declspecs->locations[ds_storage_class],
13925 "an explicit object member function cannot "
13926 "be %<static%>");
13927 inform (DECL_SOURCE_LOCATION (xobj_parm),
13928 "explicit object parameter declared here");
13930 if (unqualified_id
13931 && identifier_p (unqualified_id)
13932 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
13933 error_at (DECL_SOURCE_LOCATION (xobj_parm),
13934 "%qD cannot be an explicit object member "
13935 "function", unqualified_id);
13938 tree pushed_scope = NULL_TREE;
13939 if (funcdecl_p
13940 && decl_context != FIELD
13941 && inner_declarator->u.id.qualifying_scope
13942 && CLASS_TYPE_P (inner_declarator->u.id.qualifying_scope))
13943 pushed_scope
13944 = push_scope (inner_declarator->u.id.qualifying_scope);
13946 arg_types = grokparms (declarator->u.function.parameters, &parms);
13948 if (pushed_scope)
13949 pop_scope (pushed_scope);
13951 if (inner_declarator
13952 && inner_declarator->kind == cdk_id
13953 && inner_declarator->u.id.sfk == sfk_destructor
13954 && arg_types != void_list_node)
13956 error_at (declarator->id_loc,
13957 "destructors may not have parameters");
13958 arg_types = void_list_node;
13959 parms = NULL_TREE;
13960 is_xobj_member_function = false;
13963 type = build_function_type (type, arg_types);
13965 tree attrs = declarator->std_attributes;
13966 if (tx_qual)
13968 tree att = build_tree_list (tx_qual, NULL_TREE);
13969 /* transaction_safe applies to the type, but
13970 transaction_safe_dynamic applies to the function. */
13971 if (is_attribute_p ("transaction_safe", tx_qual))
13972 attrs = attr_chainon (attrs, att);
13973 else
13974 returned_attrs = attr_chainon (returned_attrs, att);
13977 /* Actually apply the contract attributes to the declaration. */
13978 for (tree *p = &attrs; *p;)
13980 tree l = *p;
13981 if (cxx_contract_attribute_p (l))
13983 *p = TREE_CHAIN (l);
13984 /* Intentionally reverse order of contracts so they're
13985 reversed back into their lexical order. */
13986 TREE_CHAIN (l) = NULL_TREE;
13987 returned_attrs = chainon (l, returned_attrs);
13989 else
13990 p = &TREE_CHAIN (l);
13993 if (attrs)
13994 /* [dcl.fct]/2:
13996 The optional attribute-specifier-seq appertains to
13997 the function type. */
13998 cplus_decl_attributes (&type, attrs, 0);
14000 if (raises)
14001 type = build_exception_variant (type, raises);
14003 break;
14005 case cdk_pointer:
14006 case cdk_reference:
14007 case cdk_ptrmem:
14008 /* Filter out pointers-to-references and references-to-references.
14009 We can get these if a TYPE_DECL is used. */
14011 if (TYPE_REF_P (type))
14013 if (declarator->kind != cdk_reference)
14015 error ("cannot declare pointer to %q#T", type);
14016 type = TREE_TYPE (type);
14019 /* In C++0x, we allow reference to reference declarations
14020 that occur indirectly through typedefs [7.1.3/8 dcl.typedef]
14021 and template type arguments [14.3.1/4 temp.arg.type]. The
14022 check for direct reference to reference declarations, which
14023 are still forbidden, occurs below. Reasoning behind the change
14024 can be found in DR106, DR540, and the rvalue reference
14025 proposals. */
14026 else if (cxx_dialect == cxx98)
14028 error ("cannot declare reference to %q#T", type);
14029 type = TREE_TYPE (type);
14032 else if (VOID_TYPE_P (type))
14034 if (declarator->kind == cdk_reference)
14035 error ("cannot declare reference to %q#T", type);
14036 else if (declarator->kind == cdk_ptrmem)
14037 error ("cannot declare pointer to %q#T member", type);
14040 /* We now know that the TYPE_QUALS don't apply to the decl,
14041 but to the target of the pointer. */
14042 type_quals = TYPE_UNQUALIFIED;
14044 /* This code used to handle METHOD_TYPE, but I don't think it's
14045 possible to get it here anymore. */
14046 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
14047 if (declarator->kind == cdk_ptrmem
14048 && TREE_CODE (type) == FUNCTION_TYPE)
14050 memfn_quals |= type_memfn_quals (type);
14051 type = build_memfn_type (type,
14052 declarator->u.pointer.class_type,
14053 memfn_quals,
14054 rqual);
14055 if (type == error_mark_node)
14056 return error_mark_node;
14058 rqual = REF_QUAL_NONE;
14059 memfn_quals = TYPE_UNQUALIFIED;
14062 if (TREE_CODE (type) == FUNCTION_TYPE
14063 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
14064 || type_memfn_rqual (type) != REF_QUAL_NONE))
14065 error (declarator->kind == cdk_reference
14066 ? G_("cannot declare reference to qualified function type %qT")
14067 : G_("cannot declare pointer to qualified function type %qT"),
14068 type);
14070 /* When the pointed-to type involves components of variable size,
14071 care must be taken to ensure that the size evaluation code is
14072 emitted early enough to dominate all the possible later uses
14073 and late enough for the variables on which it depends to have
14074 been assigned.
14076 This is expected to happen automatically when the pointed-to
14077 type has a name/declaration of it's own, but special attention
14078 is required if the type is anonymous.
14080 We handle the NORMAL and FIELD contexts here by inserting a
14081 dummy statement that just evaluates the size at a safe point
14082 and ensures it is not deferred until e.g. within a deeper
14083 conditional context (c++/43555).
14085 We expect nothing to be needed here for PARM or TYPENAME.
14086 Evaluating the size at this point for TYPENAME would
14087 actually be incorrect, as we might be in the middle of an
14088 expression with side effects on the pointed-to type size
14089 "arguments" prior to the pointer declaration point and the
14090 size evaluation could end up prior to the side effects. */
14092 if (!TYPE_NAME (type)
14093 && (decl_context == NORMAL || decl_context == FIELD)
14094 && at_function_scope_p ()
14095 && variably_modified_type_p (type, NULL_TREE))
14097 TYPE_NAME (type) = build_decl (UNKNOWN_LOCATION, TYPE_DECL,
14098 NULL_TREE, type);
14099 add_decl_expr (TYPE_NAME (type));
14102 if (declarator->kind == cdk_reference)
14104 /* In C++0x, the type we are creating a reference to might be
14105 a typedef which is itself a reference type. In that case,
14106 we follow the reference collapsing rules in
14107 [7.1.3/8 dcl.typedef] to create the final reference type:
14109 "If a typedef TD names a type that is a reference to a type
14110 T, an attempt to create the type 'lvalue reference to cv TD'
14111 creates the type 'lvalue reference to T,' while an attempt
14112 to create the type "rvalue reference to cv TD' creates the
14113 type TD."
14115 if (VOID_TYPE_P (type))
14116 /* We already gave an error. */;
14117 else if (TYPE_REF_P (type))
14119 if (declarator->u.reference.rvalue_ref)
14120 /* Leave type alone. */;
14121 else
14122 type = cp_build_reference_type (TREE_TYPE (type), false);
14124 else
14125 type = cp_build_reference_type
14126 (type, declarator->u.reference.rvalue_ref);
14128 /* In C++0x, we need this check for direct reference to
14129 reference declarations, which are forbidden by
14130 [8.3.2/5 dcl.ref]. Reference to reference declarations
14131 are only allowed indirectly through typedefs and template
14132 type arguments. Example:
14134 void foo(int & &); // invalid ref-to-ref decl
14136 typedef int & int_ref;
14137 void foo(int_ref &); // valid ref-to-ref decl
14139 if (inner_declarator && inner_declarator->kind == cdk_reference)
14140 error ("cannot declare reference to %q#T, which is not "
14141 "a typedef or a template type argument", type);
14143 else if (TREE_CODE (type) == METHOD_TYPE)
14144 type = build_ptrmemfunc_type (build_pointer_type (type));
14145 else if (declarator->kind == cdk_ptrmem)
14147 gcc_assert (TREE_CODE (declarator->u.pointer.class_type)
14148 != NAMESPACE_DECL);
14149 if (declarator->u.pointer.class_type == error_mark_node)
14150 /* We will already have complained. */
14151 type = error_mark_node;
14152 else
14153 type = build_ptrmem_type (declarator->u.pointer.class_type,
14154 type);
14156 else
14157 type = build_pointer_type (type);
14159 /* Process a list of type modifier keywords (such as
14160 const or volatile) that were given inside the `*' or `&'. */
14162 if (declarator->u.pointer.qualifiers)
14164 type
14165 = cp_build_qualified_type (type,
14166 declarator->u.pointer.qualifiers);
14167 type_quals = cp_type_quals (type);
14170 /* Apply C++11 attributes to the pointer, and not to the
14171 type pointed to. This is unlike what is done for GNU
14172 attributes above. It is to comply with [dcl.ptr]/1:
14174 [the optional attribute-specifier-seq (7.6.1) appertains
14175 to the pointer and not to the object pointed to]. */
14176 if (declarator->std_attributes)
14177 decl_attributes (&type, declarator->std_attributes,
14180 ctype = NULL_TREE;
14181 break;
14183 case cdk_error:
14184 break;
14186 default:
14187 gcc_unreachable ();
14191 id_loc = declarator ? declarator->id_loc : input_location;
14193 if (innermost_code != cdk_function
14194 /* Don't check this if it can be the artifical decltype(auto)
14195 we created when building a constraint in a compound-requirement:
14196 that the type-constraint is plain is going to be checked in
14197 cp_parser_compound_requirement. */
14198 && decl_context != TYPENAME
14199 && check_decltype_auto (id_loc, type))
14200 return error_mark_node;
14202 /* A `constexpr' specifier used in an object declaration declares
14203 the object as `const'. */
14204 if (constexpr_p && innermost_code != cdk_function)
14206 /* DR1688 says that a `constexpr' specifier in combination with
14207 `volatile' is valid. */
14209 if (!TYPE_REF_P (type))
14211 type_quals |= TYPE_QUAL_CONST;
14212 type = cp_build_qualified_type (type, type_quals);
14216 if (unqualified_id && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR
14217 && !FUNC_OR_METHOD_TYPE_P (type)
14218 && !variable_template_p (TREE_OPERAND (unqualified_id, 0)))
14220 error ("template-id %qD used as a declarator",
14221 unqualified_id);
14222 unqualified_id = dname;
14225 /* If TYPE is a FUNCTION_TYPE, but the function name was explicitly
14226 qualified with a class-name, turn it into a METHOD_TYPE, unless
14227 we know that the function is static. We take advantage of this
14228 opportunity to do other processing that pertains to entities
14229 explicitly declared to be class members. Note that if DECLARATOR
14230 is non-NULL, we know it is a cdk_id declarator; otherwise, we
14231 would not have exited the loop above. */
14232 if (declarator
14233 && declarator->kind == cdk_id
14234 && declarator->u.id.qualifying_scope
14235 && MAYBE_CLASS_TYPE_P (declarator->u.id.qualifying_scope))
14237 ctype = declarator->u.id.qualifying_scope;
14238 ctype = TYPE_MAIN_VARIANT (ctype);
14239 template_count = num_template_headers_for_class (ctype);
14241 if (ctype == current_class_type)
14243 if (friendp)
14245 permerror (declspecs->locations[ds_friend],
14246 "member functions are implicitly "
14247 "friends of their class");
14248 friendp = 0;
14250 else
14251 permerror (id_loc, "extra qualification %<%T::%> on member %qs",
14252 ctype, name);
14254 else if (/* If the qualifying type is already complete, then we
14255 can skip the following checks. */
14256 !COMPLETE_TYPE_P (ctype)
14257 && (/* If the function is being defined, then
14258 qualifying type must certainly be complete. */
14259 funcdef_flag
14260 /* A friend declaration of "T::f" is OK, even if
14261 "T" is a template parameter. But, if this
14262 function is not a friend, the qualifying type
14263 must be a class. */
14264 || (!friendp && !CLASS_TYPE_P (ctype))
14265 /* For a declaration, the type need not be
14266 complete, if either it is dependent (since there
14267 is no meaningful definition of complete in that
14268 case) or the qualifying class is currently being
14269 defined. */
14270 || !(dependent_type_p (ctype)
14271 || currently_open_class (ctype)))
14272 /* Check that the qualifying type is complete. */
14273 && !complete_type_or_else (ctype, NULL_TREE))
14274 return error_mark_node;
14275 else if (TREE_CODE (type) == FUNCTION_TYPE)
14277 if (current_class_type
14278 && (!friendp || funcdef_flag || initialized))
14280 error_at (id_loc, funcdef_flag || initialized
14281 ? G_("cannot define member function %<%T::%s%> "
14282 "within %qT")
14283 : G_("cannot declare member function %<%T::%s%> "
14284 "within %qT"),
14285 ctype, name, current_class_type);
14286 return error_mark_node;
14289 else if (typedef_p && current_class_type)
14291 error_at (id_loc, "cannot declare member %<%T::%s%> within %qT",
14292 ctype, name, current_class_type);
14293 return error_mark_node;
14297 if (ctype == NULL_TREE && decl_context == FIELD && friendp == 0)
14298 ctype = current_class_type;
14300 /* Now TYPE has the actual type. */
14302 if (returned_attrs)
14304 if (attrlist)
14305 *attrlist = attr_chainon (returned_attrs, *attrlist);
14306 else
14307 attrlist = &returned_attrs;
14310 if (declarator
14311 && declarator->kind == cdk_id
14312 && declarator->std_attributes
14313 && attrlist != NULL)
14315 /* [dcl.meaning]/1: The optional attribute-specifier-seq following
14316 a declarator-id appertains to the entity that is declared. */
14317 if (declarator->std_attributes != error_mark_node)
14318 *attrlist = attr_chainon (declarator->std_attributes, *attrlist);
14319 else
14320 /* We should have already diagnosed the issue (c++/78344). */
14321 gcc_assert (seen_error ());
14324 /* Handle parameter packs. */
14325 if (parameter_pack_p)
14327 if (decl_context == PARM)
14328 /* Turn the type into a pack expansion.*/
14329 type = make_pack_expansion (type);
14330 else
14331 error ("non-parameter %qs cannot be a parameter pack", name);
14334 if ((decl_context == FIELD || decl_context == PARM)
14335 && !processing_template_decl
14336 && variably_modified_type_p (type, NULL_TREE))
14338 if (decl_context == FIELD)
14339 error_at (id_loc,
14340 "data member may not have variably modified type %qT", type);
14341 else
14342 error_at (id_loc,
14343 "parameter may not have variably modified type %qT", type);
14344 type = error_mark_node;
14347 if (explicitp == 1 || (explicitp && friendp))
14349 /* [dcl.fct.spec] (C++11) The explicit specifier shall be used only
14350 in the declaration of a constructor or conversion function within
14351 a class definition. */
14352 if (!current_class_type)
14353 error_at (declspecs->locations[ds_explicit],
14354 "%<explicit%> outside class declaration");
14355 else if (friendp)
14356 error_at (declspecs->locations[ds_explicit],
14357 "%<explicit%> in friend declaration");
14358 else
14359 error_at (declspecs->locations[ds_explicit],
14360 "only declarations of constructors and conversion operators "
14361 "can be %<explicit%>");
14362 explicitp = 0;
14365 if (storage_class == sc_mutable)
14367 location_t sloc = declspecs->locations[ds_storage_class];
14368 if (decl_context != FIELD || friendp)
14370 error_at (sloc, "non-member %qs cannot be declared %<mutable%>",
14371 name);
14372 storage_class = sc_none;
14374 else if (decl_context == TYPENAME || typedef_p)
14376 error_at (sloc,
14377 "non-object member %qs cannot be declared %<mutable%>",
14378 name);
14379 storage_class = sc_none;
14381 else if (FUNC_OR_METHOD_TYPE_P (type))
14383 error_at (sloc, "function %qs cannot be declared %<mutable%>",
14384 name);
14385 storage_class = sc_none;
14387 else if (staticp)
14389 error_at (sloc, "%<static%> %qs cannot be declared %<mutable%>",
14390 name);
14391 storage_class = sc_none;
14393 else if (type_quals & TYPE_QUAL_CONST)
14395 error_at (sloc, "%<const%> %qs cannot be declared %<mutable%>",
14396 name);
14397 storage_class = sc_none;
14399 else if (TYPE_REF_P (type))
14401 permerror (sloc, "reference %qs cannot be declared %<mutable%>",
14402 name);
14403 storage_class = sc_none;
14407 /* If this is declaring a typedef name, return a TYPE_DECL. */
14408 if (typedef_p && decl_context != TYPENAME)
14410 bool alias_p = decl_spec_seq_has_spec_p (declspecs, ds_alias);
14411 tree decl;
14413 if (funcdef_flag)
14415 if (decl_context == NORMAL)
14416 error_at (id_loc,
14417 "typedef may not be a function definition");
14418 else
14419 error_at (id_loc,
14420 "typedef may not be a member function definition");
14421 return error_mark_node;
14424 /* This declaration:
14426 typedef void f(int) const;
14428 declares a function type which is not a member of any
14429 particular class, but which is cv-qualified; for
14430 example "f S::*" declares a pointer to a const-qualified
14431 member function of S. We record the cv-qualification in the
14432 function type. */
14433 if ((rqual || memfn_quals) && TREE_CODE (type) == FUNCTION_TYPE)
14435 type = apply_memfn_quals (type, memfn_quals, rqual);
14437 /* We have now dealt with these qualifiers. */
14438 memfn_quals = TYPE_UNQUALIFIED;
14439 rqual = REF_QUAL_NONE;
14442 if (type_uses_auto (type))
14444 if (alias_p)
14445 error_at (declspecs->locations[ds_type_spec],
14446 "%<auto%> not allowed in alias declaration");
14447 else
14448 error_at (declspecs->locations[ds_type_spec],
14449 "typedef declared %<auto%>");
14450 type = error_mark_node;
14453 if (reqs)
14454 error_at (location_of (reqs), "requires-clause on typedef");
14456 if (id_declarator && declarator->u.id.qualifying_scope)
14458 error_at (id_loc, "typedef name may not be a nested-name-specifier");
14459 type = error_mark_node;
14462 if (decl_context == FIELD)
14463 decl = build_lang_decl_loc (id_loc, TYPE_DECL, unqualified_id, type);
14464 else
14465 decl = build_decl (id_loc, TYPE_DECL, unqualified_id, type);
14467 if (decl_context != FIELD)
14469 if (!current_function_decl)
14470 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
14471 else if (DECL_MAYBE_IN_CHARGE_CDTOR_P (current_function_decl))
14472 /* The TYPE_DECL is "abstract" because there will be
14473 clones of this constructor/destructor, and there will
14474 be copies of this TYPE_DECL generated in those
14475 clones. The decloning optimization (for space) may
14476 revert this subsequently if it determines that
14477 the clones should share a common implementation. */
14478 DECL_ABSTRACT_P (decl) = true;
14480 set_originating_module (decl);
14482 else if (current_class_type
14483 && constructor_name_p (unqualified_id, current_class_type))
14484 permerror (id_loc, "ISO C++ forbids nested type %qD with same name "
14485 "as enclosing class",
14486 unqualified_id);
14488 /* If the user declares "typedef struct {...} foo" then the
14489 struct will have an anonymous name. Fill that name in now.
14490 Nothing can refer to it, so nothing needs know about the name
14491 change. */
14492 if (type != error_mark_node
14493 && unqualified_id
14494 && TYPE_NAME (type)
14495 && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL
14496 && TYPE_UNNAMED_P (type)
14497 && declspecs->type_definition_p
14498 && attributes_naming_typedef_ok (*attrlist)
14499 && cp_type_quals (type) == TYPE_UNQUALIFIED)
14500 name_unnamed_type (type, decl);
14502 if (signed_p
14503 || (typedef_decl && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl)))
14504 C_TYPEDEF_EXPLICITLY_SIGNED (decl) = 1;
14506 bad_specifiers (decl, BSP_TYPE, virtualp,
14507 memfn_quals != TYPE_UNQUALIFIED,
14508 inlinep, friendp, raises != NULL_TREE,
14509 declspecs->locations);
14511 if (alias_p)
14512 /* Acknowledge that this was written:
14513 `using analias = atype;'. */
14514 TYPE_DECL_ALIAS_P (decl) = 1;
14516 return decl;
14519 /* Detect the case of an array type of unspecified size
14520 which came, as such, direct from a typedef name.
14521 We must copy the type, so that the array's domain can be
14522 individually set by the object's initializer. */
14524 if (type && typedef_type
14525 && TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type)
14526 && TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (typedef_type))
14527 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
14529 /* Detect where we're using a typedef of function type to declare a
14530 function. PARMS will not be set, so we must create it now. */
14532 if (type == typedef_type && TREE_CODE (type) == FUNCTION_TYPE)
14534 tree decls = NULL_TREE;
14535 tree args;
14537 for (args = TYPE_ARG_TYPES (type);
14538 args && args != void_list_node;
14539 args = TREE_CHAIN (args))
14541 tree decl = cp_build_parm_decl (NULL_TREE, NULL_TREE,
14542 TREE_VALUE (args));
14544 DECL_CHAIN (decl) = decls;
14545 decls = decl;
14548 parms = nreverse (decls);
14550 if (decl_context != TYPENAME)
14552 /* The qualifiers on the function type become the qualifiers on
14553 the non-static member function. */
14554 memfn_quals |= type_memfn_quals (type);
14555 rqual = type_memfn_rqual (type);
14556 type_quals = TYPE_UNQUALIFIED;
14557 raises = TYPE_RAISES_EXCEPTIONS (type);
14561 /* If this is a type name (such as, in a cast or sizeof),
14562 compute the type and return it now. */
14564 if (decl_context == TYPENAME)
14566 /* Note that here we don't care about type_quals. */
14568 /* Special case: "friend class foo" looks like a TYPENAME context. */
14569 if (friendp)
14571 if (inlinep)
14573 error ("%<inline%> specified for friend class declaration");
14574 inlinep = 0;
14577 if (!current_aggr)
14579 /* Don't allow friend declaration without a class-key. */
14580 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
14581 permerror (input_location, "template parameters cannot be friends");
14582 else if (TREE_CODE (type) == TYPENAME_TYPE)
14583 permerror (input_location, "friend declaration requires class-key, "
14584 "i.e. %<friend class %T::%D%>",
14585 TYPE_CONTEXT (type), TYPENAME_TYPE_FULLNAME (type));
14586 else
14587 permerror (input_location, "friend declaration requires class-key, "
14588 "i.e. %<friend %#T%>",
14589 type);
14592 /* Only try to do this stuff if we didn't already give up. */
14593 if (type != integer_type_node)
14595 /* A friendly class? */
14596 if (current_class_type)
14597 make_friend_class (current_class_type, TYPE_MAIN_VARIANT (type),
14598 /*complain=*/true);
14599 else
14600 error ("trying to make class %qT a friend of global scope",
14601 type);
14603 type = void_type_node;
14606 else if (memfn_quals || rqual)
14608 if (ctype == NULL_TREE
14609 && TREE_CODE (type) == METHOD_TYPE)
14610 ctype = TYPE_METHOD_BASETYPE (type);
14612 if (ctype)
14613 type = build_memfn_type (type, ctype, memfn_quals, rqual);
14614 /* Core issue #547: need to allow this in template type args.
14615 Allow it in general in C++11 for alias-declarations. */
14616 else if ((template_type_arg || cxx_dialect >= cxx11)
14617 && TREE_CODE (type) == FUNCTION_TYPE)
14618 type = apply_memfn_quals (type, memfn_quals, rqual);
14619 else
14620 error ("invalid qualifiers on non-member function type");
14623 if (reqs)
14624 error_at (location_of (reqs), "requires-clause on type-id");
14626 return type;
14628 else if (unqualified_id == NULL_TREE && decl_context != PARM
14629 && decl_context != CATCHPARM
14630 && TREE_CODE (type) != UNION_TYPE
14631 && ! bitfield
14632 && innermost_code != cdk_decomp)
14634 error ("abstract declarator %qT used as declaration", type);
14635 return error_mark_node;
14638 if (!FUNC_OR_METHOD_TYPE_P (type))
14640 /* Only functions may be declared using an operator-function-id. */
14641 if (dname && IDENTIFIER_ANY_OP_P (dname))
14643 error_at (id_loc, "declaration of %qD as non-function", dname);
14644 return error_mark_node;
14647 if (reqs)
14648 error_at (location_of (reqs),
14649 "requires-clause on declaration of non-function type %qT",
14650 type);
14653 /* We don't check parameter types here because we can emit a better
14654 error message later. */
14655 if (decl_context != PARM)
14657 type = check_var_type (unqualified_id, type, id_loc);
14658 if (type == error_mark_node)
14659 return error_mark_node;
14662 /* Now create the decl, which may be a VAR_DECL, a PARM_DECL
14663 or a FUNCTION_DECL, depending on DECL_CONTEXT and TYPE. */
14665 if (decl_context == PARM || decl_context == CATCHPARM)
14667 if (ctype || in_namespace)
14668 error ("cannot use %<::%> in parameter declaration");
14670 tree auto_node = type_uses_auto (type);
14671 if (auto_node && !(cxx_dialect >= cxx17 && template_parm_flag))
14673 bool err_p = true;
14674 if (cxx_dialect >= cxx14)
14676 if (decl_context == PARM && AUTO_IS_DECLTYPE (auto_node))
14677 error_at (typespec_loc,
14678 "cannot declare a parameter with %<decltype(auto)%>");
14679 else if (tree c = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14681 auto_diagnostic_group g;
14682 gcc_rich_location richloc (typespec_loc);
14683 richloc.add_fixit_insert_after ("<>");
14684 error_at (&richloc,
14685 "missing template argument list after %qE; template "
14686 "placeholder not permitted in parameter", c);
14687 if (decl_context == PARM && cxx_dialect >= cxx20)
14688 inform (typespec_loc, "or use %<auto%> for an "
14689 "abbreviated function template");
14690 inform (DECL_SOURCE_LOCATION (c), "%qD declared here", c);
14692 else if (decl_context == CATCHPARM || template_parm_flag)
14693 error_at (typespec_loc,
14694 "%<auto%> parameter not permitted in this context");
14695 else
14696 /* Do not issue an error while tentatively parsing a function
14697 parameter: for T t(auto(a), 42);, when we just saw the 1st
14698 parameter, we don't know yet that this construct won't be
14699 a function declaration. Defer the checking to
14700 cp_parser_parameter_declaration_clause. */
14701 err_p = false;
14703 else
14704 error_at (typespec_loc, "parameter declared %<auto%>");
14705 if (err_p)
14706 type = error_mark_node;
14709 /* A parameter declared as an array of T is really a pointer to T.
14710 One declared as a function is really a pointer to a function.
14711 One declared as a member is really a pointer to member. */
14713 if (TREE_CODE (type) == ARRAY_TYPE)
14715 /* Transfer const-ness of array into that of type pointed to. */
14716 type = build_pointer_type (TREE_TYPE (type));
14717 type_quals = TYPE_UNQUALIFIED;
14718 array_parameter_p = true;
14720 else if (TREE_CODE (type) == FUNCTION_TYPE)
14721 type = build_pointer_type (type);
14724 if (ctype && TREE_CODE (type) == FUNCTION_TYPE && staticp < 2
14725 /* Don't convert xobj member functions to METHOD_TYPE. */
14726 && !is_xobj_member_function
14727 && !(unqualified_id
14728 && identifier_p (unqualified_id)
14729 && IDENTIFIER_NEWDEL_OP_P (unqualified_id)))
14731 cp_cv_quals real_quals = memfn_quals;
14732 if (cxx_dialect < cxx14 && constexpr_p
14733 && sfk != sfk_constructor && sfk != sfk_destructor)
14734 real_quals |= TYPE_QUAL_CONST;
14735 type = build_memfn_type (type, ctype, real_quals, rqual);
14739 tree decl = NULL_TREE;
14741 if (decl_context == PARM)
14743 decl = cp_build_parm_decl (NULL_TREE, unqualified_id, type);
14744 DECL_ARRAY_PARAMETER_P (decl) = array_parameter_p;
14746 bad_specifiers (decl, BSP_PARM, virtualp,
14747 memfn_quals != TYPE_UNQUALIFIED,
14748 inlinep, friendp, raises != NULL_TREE,
14749 declspecs->locations);
14751 else if (decl_context == FIELD)
14753 if (!staticp && !friendp && !FUNC_OR_METHOD_TYPE_P (type))
14754 if (tree auto_node = type_uses_auto (type))
14756 location_t tloc = declspecs->locations[ds_type_spec];
14757 if (CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14758 error_at (tloc, "invalid use of template-name %qE without an "
14759 "argument list",
14760 CLASS_PLACEHOLDER_TEMPLATE (auto_node));
14761 else
14762 error_at (tloc, "non-static data member declared with "
14763 "placeholder %qT", auto_node);
14764 type = error_mark_node;
14767 /* The C99 flexible array extension. */
14768 if (!staticp && TREE_CODE (type) == ARRAY_TYPE
14769 && TYPE_DOMAIN (type) == NULL_TREE)
14771 if (ctype
14772 && (TREE_CODE (ctype) == UNION_TYPE
14773 || TREE_CODE (ctype) == QUAL_UNION_TYPE))
14774 pedwarn (id_loc, OPT_Wpedantic,
14775 "flexible array member in union is a GCC extension");
14777 else
14779 /* Array is a flexible member. */
14780 if (name)
14781 pedwarn (id_loc, OPT_Wpedantic,
14782 "ISO C++ forbids flexible array member %qs", name);
14783 else
14784 pedwarn (input_location, OPT_Wpedantic,
14785 "ISO C++ forbids flexible array members");
14787 /* Flexible array member has a null domain. */
14788 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
14792 if (type == error_mark_node)
14794 /* Happens when declaring arrays of sizes which
14795 are error_mark_node, for example. */
14796 decl = NULL_TREE;
14798 else if (in_namespace && !friendp)
14800 /* Something like struct S { int N::j; }; */
14801 error_at (id_loc, "invalid use of %<::%>");
14802 return error_mark_node;
14804 else if (FUNC_OR_METHOD_TYPE_P (type) && unqualified_id)
14806 int publicp = 0;
14807 tree function_context;
14809 if (friendp == 0)
14811 /* This should never happen in pure C++ (the check
14812 could be an assert). It could happen in
14813 Objective-C++ if someone writes invalid code that
14814 uses a function declaration for an instance
14815 variable or property (instance variables and
14816 properties are parsed as FIELD_DECLs, but they are
14817 part of an Objective-C class, not a C++ class).
14818 That code is invalid and is caught by this
14819 check. */
14820 if (!ctype)
14822 error ("declaration of function %qD in invalid context",
14823 unqualified_id);
14824 return error_mark_node;
14827 /* ``A union may [ ... ] not [ have ] virtual functions.''
14828 ARM 9.5 */
14829 if (virtualp && TREE_CODE (ctype) == UNION_TYPE)
14831 error_at (declspecs->locations[ds_virtual],
14832 "function %qD declared %<virtual%> inside a union",
14833 unqualified_id);
14834 return error_mark_node;
14837 if (virtualp
14838 && identifier_p (unqualified_id)
14839 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14841 error_at (declspecs->locations[ds_virtual],
14842 "%qD cannot be declared %<virtual%>, since it "
14843 "is always static", unqualified_id);
14844 virtualp = 0;
14848 /* Check that the name used for a destructor makes sense. */
14849 if (sfk == sfk_destructor)
14851 tree uqname = id_declarator->u.id.unqualified_name;
14853 if (!ctype)
14855 gcc_assert (friendp);
14856 error_at (id_loc, "expected qualified name in friend "
14857 "declaration for destructor %qD", uqname);
14858 return error_mark_node;
14861 if (!check_dtor_name (ctype, TREE_OPERAND (uqname, 0)))
14863 error_at (id_loc, "declaration of %qD as member of %qT",
14864 uqname, ctype);
14865 return error_mark_node;
14867 if (concept_p)
14869 error_at (declspecs->locations[ds_concept],
14870 "a destructor cannot be %qs", "concept");
14871 return error_mark_node;
14873 if (constexpr_p && cxx_dialect < cxx20)
14875 error_at (declspecs->locations[ds_constexpr],
14876 "%<constexpr%> destructors only available"
14877 " with %<-std=c++20%> or %<-std=gnu++20%>");
14878 return error_mark_node;
14880 if (consteval_p)
14882 error_at (declspecs->locations[ds_consteval],
14883 "a destructor cannot be %qs", "consteval");
14884 return error_mark_node;
14887 else if (sfk == sfk_constructor && friendp && !ctype)
14889 error ("expected qualified name in friend declaration "
14890 "for constructor %qD",
14891 id_declarator->u.id.unqualified_name);
14892 return error_mark_node;
14894 if (sfk == sfk_constructor)
14895 if (concept_p)
14897 error_at (declspecs->locations[ds_concept],
14898 "a constructor cannot be %<concept%>");
14899 return error_mark_node;
14901 if (concept_p)
14903 error_at (declspecs->locations[ds_concept],
14904 "a concept cannot be a member function");
14905 concept_p = false;
14907 else if (consteval_p
14908 && identifier_p (unqualified_id)
14909 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14911 error_at (declspecs->locations[ds_consteval],
14912 "%qD cannot be %qs", unqualified_id, "consteval");
14913 consteval_p = false;
14916 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14918 tree tmpl = TREE_OPERAND (unqualified_id, 0);
14919 if (variable_template_p (tmpl))
14921 auto_diagnostic_group d;
14922 error_at (id_loc, "specialization of variable template "
14923 "%qD declared as function", tmpl);
14924 inform (DECL_SOURCE_LOCATION (tmpl),
14925 "variable template declared here");
14926 return error_mark_node;
14930 /* Tell grokfndecl if it needs to set TREE_PUBLIC on the node. */
14931 function_context
14932 = (ctype != NULL_TREE
14933 ? decl_function_context (TYPE_MAIN_DECL (ctype)) : NULL_TREE);
14934 publicp = ((! friendp || ! staticp)
14935 && function_context == NULL_TREE);
14937 decl = grokfndecl (ctype, type,
14938 TREE_CODE (unqualified_id) != TEMPLATE_ID_EXPR
14939 ? unqualified_id : dname,
14940 parms,
14941 unqualified_id,
14942 declspecs,
14943 reqs,
14944 virtualp, flags, memfn_quals, rqual, raises,
14945 friendp ? -1 : 0, friendp, publicp,
14946 inlinep | (2 * constexpr_p) | (4 * concept_p)
14947 | (8 * consteval_p),
14948 initialized == SD_DELETED,
14949 is_xobj_member_function, sfk,
14950 funcdef_flag, late_return_type_p,
14951 template_count, in_namespace,
14952 attrlist, id_loc);
14953 decl = set_virt_specifiers (decl, virt_specifiers);
14954 if (decl == NULL_TREE)
14955 return error_mark_node;
14956 #if 0
14957 /* This clobbers the attrs stored in `decl' from `attrlist'. */
14958 /* The decl and setting of decl_attr is also turned off. */
14959 decl = build_decl_attribute_variant (decl, decl_attr);
14960 #endif
14962 /* [class.conv.ctor]
14964 A constructor declared without the function-specifier
14965 explicit that can be called with a single parameter
14966 specifies a conversion from the type of its first
14967 parameter to the type of its class. Such a constructor
14968 is called a converting constructor. */
14969 if (explicitp == 2)
14970 DECL_NONCONVERTING_P (decl) = 1;
14972 if (declspecs->explicit_specifier)
14973 store_explicit_specifier (decl, declspecs->explicit_specifier);
14975 else if (!staticp
14976 && ((current_class_type
14977 && same_type_p (type, current_class_type))
14978 || (!dependent_type_p (type)
14979 && !COMPLETE_TYPE_P (complete_type (type))
14980 && (!complete_or_array_type_p (type)
14981 || initialized == SD_UNINITIALIZED))))
14983 if (TREE_CODE (type) != ARRAY_TYPE
14984 || !COMPLETE_TYPE_P (TREE_TYPE (type)))
14986 if (unqualified_id)
14988 auto_diagnostic_group d;
14989 error_at (id_loc, "field %qD has incomplete type %qT",
14990 unqualified_id, type);
14991 cxx_incomplete_type_inform (strip_array_types (type));
14993 else
14994 error ("name %qT has incomplete type", type);
14996 type = error_mark_node;
14997 decl = NULL_TREE;
15000 else if (!verify_type_context (input_location,
15001 staticp
15002 ? TCTX_STATIC_STORAGE
15003 : TCTX_FIELD, type))
15005 type = error_mark_node;
15006 decl = NULL_TREE;
15008 else
15010 if (friendp)
15012 if (unqualified_id)
15013 error_at (id_loc,
15014 "%qE is neither function nor member function; "
15015 "cannot be declared friend", unqualified_id);
15016 else
15017 error ("unnamed field is neither function nor member "
15018 "function; cannot be declared friend");
15019 return error_mark_node;
15021 decl = NULL_TREE;
15024 if (friendp)
15026 /* Packages tend to use GNU attributes on friends, so we only
15027 warn for standard attributes. */
15028 if (attrlist
15029 && !funcdef_flag
15030 && cxx11_attribute_p (*attrlist)
15031 && !all_attributes_are_contracts_p (*attrlist))
15033 *attrlist = NULL_TREE;
15034 auto_diagnostic_group d;
15035 if (warning_at (id_loc, OPT_Wattributes, "attribute ignored"))
15036 inform (id_loc, "an attribute that appertains to a friend "
15037 "declaration that is not a definition is ignored");
15039 /* Friends are treated specially. */
15040 if (ctype == current_class_type)
15041 ; /* We already issued a permerror. */
15042 else if (decl && DECL_NAME (decl))
15044 set_originating_module (decl, true);
15046 if (initialized)
15047 /* Kludge: We need funcdef_flag to be true in do_friend for
15048 in-class defaulted functions, but that breaks grokfndecl.
15049 So set it here. */
15050 funcdef_flag = true;
15052 cplus_decl_attributes (&decl, *attrlist, 0);
15053 *attrlist = NULL_TREE;
15055 tree scope = ctype ? ctype : in_namespace;
15056 decl = do_friend (scope, unqualified_id, decl,
15057 flags, funcdef_flag);
15058 return decl;
15060 else
15061 return error_mark_node;
15064 /* Structure field. It may not be a function, except for C++. */
15066 if (decl == NULL_TREE)
15068 if (staticp)
15070 /* C++ allows static class members. All other work
15071 for this is done by grokfield. */
15072 decl = build_lang_decl_loc (id_loc, VAR_DECL,
15073 dname, type);
15074 if (unqualified_id
15075 && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
15077 decl = check_explicit_specialization (unqualified_id, decl,
15078 template_count,
15079 concept_p * 8);
15080 if (decl == error_mark_node)
15081 return error_mark_node;
15083 set_linkage_for_static_data_member (decl);
15084 if (concept_p)
15085 error_at (declspecs->locations[ds_concept],
15086 "static data member %qE declared %qs",
15087 unqualified_id, "concept");
15088 else if (constexpr_p && !initialized)
15090 error_at (DECL_SOURCE_LOCATION (decl),
15091 "%<constexpr%> static data member %qD must "
15092 "have an initializer", decl);
15093 constexpr_p = false;
15095 if (consteval_p)
15096 error_at (declspecs->locations[ds_consteval],
15097 "static data member %qE declared %qs",
15098 unqualified_id, "consteval");
15100 if (inlinep)
15101 mark_inline_variable (decl, declspecs->locations[ds_inline]);
15103 if (!DECL_VAR_DECLARED_INLINE_P (decl)
15104 && !(cxx_dialect >= cxx17 && constexpr_p))
15105 /* Even if there is an in-class initialization, DECL
15106 is considered undefined until an out-of-class
15107 definition is provided, unless this is an inline
15108 variable. */
15109 DECL_EXTERNAL (decl) = 1;
15111 if (thread_p)
15113 CP_DECL_THREAD_LOCAL_P (decl) = true;
15114 if (!processing_template_decl)
15115 set_decl_tls_model (decl, decl_default_tls_model (decl));
15116 if (declspecs->gnu_thread_keyword_p)
15117 SET_DECL_GNU_TLS_P (decl);
15120 /* Set the constraints on the declaration. */
15121 bool memtmpl = (current_template_depth
15122 > template_class_depth (current_class_type));
15123 if (memtmpl)
15125 tree ci = current_template_constraints ();
15126 set_constraints (decl, ci);
15129 else
15131 if (concept_p)
15133 error_at (declspecs->locations[ds_concept],
15134 "non-static data member %qE declared %qs",
15135 unqualified_id, "concept");
15136 concept_p = false;
15137 constexpr_p = false;
15139 else if (constexpr_p)
15141 error_at (declspecs->locations[ds_constexpr],
15142 "non-static data member %qE declared %qs",
15143 unqualified_id, "constexpr");
15144 constexpr_p = false;
15146 if (constinit_p)
15148 error_at (declspecs->locations[ds_constinit],
15149 "non-static data member %qE declared %qs",
15150 unqualified_id, "constinit");
15151 constinit_p = false;
15153 if (consteval_p)
15155 error_at (declspecs->locations[ds_consteval],
15156 "non-static data member %qE declared %qs",
15157 unqualified_id, "consteval");
15158 consteval_p = false;
15160 decl = build_decl (id_loc, FIELD_DECL, unqualified_id, type);
15161 DECL_NONADDRESSABLE_P (decl) = bitfield;
15162 if (bitfield && !unqualified_id)
15163 DECL_PADDING_P (decl) = 1;
15165 if (storage_class == sc_mutable)
15167 DECL_MUTABLE_P (decl) = 1;
15168 storage_class = sc_none;
15171 if (initialized)
15173 /* An attempt is being made to initialize a non-static
15174 member. This is new in C++11. */
15175 maybe_warn_cpp0x (CPP0X_NSDMI, init_loc);
15177 /* If this has been parsed with static storage class, but
15178 errors forced staticp to be cleared, ensure NSDMI is
15179 not present. */
15180 if (declspecs->storage_class == sc_static)
15181 DECL_INITIAL (decl) = error_mark_node;
15185 bad_specifiers (decl, BSP_FIELD, virtualp,
15186 memfn_quals != TYPE_UNQUALIFIED,
15187 staticp ? false : inlinep, friendp,
15188 raises != NULL_TREE,
15189 declspecs->locations);
15192 else if (FUNC_OR_METHOD_TYPE_P (type))
15194 tree original_name;
15195 int publicp = 0;
15197 if (!unqualified_id)
15198 return error_mark_node;
15200 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
15201 original_name = dname;
15202 else
15203 original_name = unqualified_id;
15204 // FIXME:gcc_assert (original_name == dname);
15206 if (storage_class == sc_auto)
15207 error_at (declspecs->locations[ds_storage_class],
15208 "storage class %<auto%> invalid for function %qs", name);
15209 else if (storage_class == sc_register)
15210 error_at (declspecs->locations[ds_storage_class],
15211 "storage class %<register%> invalid for function %qs",
15212 name);
15213 else if (thread_p)
15215 if (declspecs->gnu_thread_keyword_p)
15216 error_at (declspecs->locations[ds_thread],
15217 "storage class %<__thread%> invalid for function %qs",
15218 name);
15219 else
15220 error_at (declspecs->locations[ds_thread],
15221 "storage class %<thread_local%> invalid for "
15222 "function %qs", name);
15224 else if (constinit_p)
15225 error_at (declspecs->locations[ds_constinit],
15226 "%<constinit%> specifier invalid for function %qs", name);
15228 if (virt_specifiers)
15229 error ("virt-specifiers in %qs not allowed outside a class "
15230 "definition", name);
15231 /* Function declaration not at top level.
15232 Storage classes other than `extern' are not allowed
15233 and `extern' makes no difference. */
15234 if (! toplevel_bindings_p ()
15235 && (storage_class == sc_static
15236 || decl_spec_seq_has_spec_p (declspecs, ds_inline))
15237 && pedantic)
15239 if (storage_class == sc_static)
15240 pedwarn (declspecs->locations[ds_storage_class], OPT_Wpedantic,
15241 "%<static%> specifier invalid for function %qs "
15242 "declared out of global scope", name);
15243 else
15244 pedwarn (declspecs->locations[ds_inline], OPT_Wpedantic,
15245 "%<inline%> specifier invalid for function %qs "
15246 "declared out of global scope", name);
15249 if (ctype == NULL_TREE)
15251 if (virtualp)
15253 error ("virtual non-class function %qs", name);
15254 virtualp = 0;
15256 else if (sfk == sfk_constructor
15257 || sfk == sfk_destructor)
15259 error (funcdef_flag
15260 ? G_("%qs defined in a non-class scope")
15261 : G_("%qs declared in a non-class scope"), name);
15262 sfk = sfk_none;
15265 if (consteval_p
15266 && identifier_p (unqualified_id)
15267 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
15269 error_at (declspecs->locations[ds_consteval],
15270 "%qD cannot be %qs", unqualified_id, "consteval");
15271 consteval_p = false;
15274 /* Record whether the function is public. */
15275 publicp = (ctype != NULL_TREE
15276 || storage_class != sc_static);
15278 decl = grokfndecl (ctype, type, original_name, parms, unqualified_id,
15279 declspecs,
15280 reqs, virtualp, flags, memfn_quals, rqual, raises,
15281 1, friendp,
15282 publicp,
15283 inlinep | (2 * constexpr_p) | (4 * concept_p)
15284 | (8 * consteval_p),
15285 initialized == SD_DELETED,
15286 is_xobj_member_function, sfk,
15287 funcdef_flag,
15288 late_return_type_p,
15289 template_count, in_namespace, attrlist,
15290 id_loc);
15291 if (decl == NULL_TREE)
15292 return error_mark_node;
15294 if (explicitp == 2)
15295 DECL_NONCONVERTING_P (decl) = 1;
15296 if (staticp == 1)
15298 int invalid_static = 0;
15300 /* Don't allow a static member function in a class, and forbid
15301 declaring main to be static. */
15302 if (TREE_CODE (type) == METHOD_TYPE)
15304 permerror (input_location, "cannot declare member function %qD to have "
15305 "static linkage", decl);
15306 invalid_static = 1;
15308 else if (current_function_decl)
15310 /* 7.1.1: There can be no static function declarations within a
15311 block. */
15312 error_at (declspecs->locations[ds_storage_class],
15313 "cannot declare static function inside another function");
15314 invalid_static = 1;
15317 if (invalid_static)
15319 staticp = 0;
15320 storage_class = sc_none;
15323 if (declspecs->explicit_specifier)
15324 store_explicit_specifier (decl, declspecs->explicit_specifier);
15326 else
15328 /* It's a variable. */
15330 /* An uninitialized decl with `extern' is a reference. */
15331 decl = grokvardecl (type, dname, unqualified_id,
15332 declspecs,
15333 initialized,
15334 type_quals,
15335 inlinep,
15336 concept_p,
15337 template_count,
15338 ctype ? ctype : in_namespace,
15339 id_loc);
15340 if (decl == NULL_TREE)
15341 return error_mark_node;
15343 bad_specifiers (decl, BSP_VAR, virtualp,
15344 memfn_quals != TYPE_UNQUALIFIED,
15345 inlinep, friendp, raises != NULL_TREE,
15346 declspecs->locations);
15348 if (ctype)
15350 DECL_CONTEXT (decl) = ctype;
15351 if (staticp == 1)
15353 permerror (declspecs->locations[ds_storage_class],
15354 "%<static%> may not be used when defining "
15355 "(as opposed to declaring) a static data member");
15356 staticp = 0;
15357 storage_class = sc_none;
15359 if (storage_class == sc_register && TREE_STATIC (decl))
15361 error ("static member %qD declared %<register%>", decl);
15362 storage_class = sc_none;
15364 if (storage_class == sc_extern && pedantic)
15366 pedwarn (input_location, OPT_Wpedantic,
15367 "cannot explicitly declare member %q#D to have "
15368 "extern linkage", decl);
15369 storage_class = sc_none;
15372 else if (constexpr_p && DECL_EXTERNAL (decl))
15374 error_at (DECL_SOURCE_LOCATION (decl),
15375 "declaration of %<constexpr%> variable %qD "
15376 "is not a definition", decl);
15377 constexpr_p = false;
15379 if (consteval_p)
15381 error_at (DECL_SOURCE_LOCATION (decl),
15382 "a variable cannot be declared %<consteval%>");
15383 consteval_p = false;
15386 if (inlinep)
15387 mark_inline_variable (decl, declspecs->locations[ds_inline]);
15388 if (innermost_code == cdk_decomp)
15390 gcc_assert (declarator && declarator->kind == cdk_decomp);
15391 DECL_SOURCE_LOCATION (decl) = id_loc;
15392 DECL_ARTIFICIAL (decl) = 1;
15393 fit_decomposition_lang_decl (decl, NULL_TREE);
15397 if (VAR_P (decl) && !initialized)
15398 if (tree auto_node = type_uses_auto (type))
15399 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
15401 location_t loc = declspecs->locations[ds_type_spec];
15402 error_at (loc, "declaration of %q#D has no initializer", decl);
15403 TREE_TYPE (decl) = error_mark_node;
15406 if (storage_class == sc_extern && initialized && !funcdef_flag)
15408 if (toplevel_bindings_p ())
15410 /* It's common practice (and completely valid) to have a const
15411 be initialized and declared extern. */
15412 if (!(type_quals & TYPE_QUAL_CONST))
15413 warning_at (DECL_SOURCE_LOCATION (decl), 0,
15414 "%qs initialized and declared %<extern%>", name);
15416 else
15418 error_at (DECL_SOURCE_LOCATION (decl),
15419 "%qs has both %<extern%> and initializer", name);
15420 return error_mark_node;
15424 /* Record `register' declaration for warnings on &
15425 and in case doing stupid register allocation. */
15427 if (storage_class == sc_register)
15429 DECL_REGISTER (decl) = 1;
15430 /* Warn about register storage specifiers on PARM_DECLs. */
15431 if (TREE_CODE (decl) == PARM_DECL)
15433 if (cxx_dialect >= cxx17)
15434 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
15435 "ISO C++17 does not allow %<register%> storage "
15436 "class specifier");
15437 else
15438 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
15439 "%<register%> storage class specifier used");
15442 else if (storage_class == sc_extern)
15443 DECL_THIS_EXTERN (decl) = 1;
15444 else if (storage_class == sc_static)
15445 DECL_THIS_STATIC (decl) = 1;
15447 if (VAR_P (decl))
15449 /* Set constexpr flag on vars (functions got it in grokfndecl). */
15450 if (constexpr_p)
15451 DECL_DECLARED_CONSTEXPR_P (decl) = true;
15452 /* And the constinit flag (which only applies to variables). */
15453 else if (constinit_p)
15454 DECL_DECLARED_CONSTINIT_P (decl) = true;
15456 else if (TREE_CODE (decl) == FUNCTION_DECL)
15458 /* If we saw a return type, record its location. */
15459 location_t loc = declspecs->locations[ds_type_spec];
15460 if (loc == UNKNOWN_LOCATION)
15461 /* Build DECL_RESULT in start_preparsed_function. */;
15462 else if (!DECL_RESULT (decl))
15464 tree restype = TREE_TYPE (TREE_TYPE (decl));
15465 tree resdecl = build_decl (loc, RESULT_DECL, 0, restype);
15466 DECL_ARTIFICIAL (resdecl) = 1;
15467 DECL_IGNORED_P (resdecl) = 1;
15468 DECL_RESULT (decl) = resdecl;
15470 else if (funcdef_flag)
15471 DECL_SOURCE_LOCATION (DECL_RESULT (decl)) = loc;
15474 /* Record constancy and volatility on the DECL itself . There's
15475 no need to do this when processing a template; we'll do this
15476 for the instantiated declaration based on the type of DECL. */
15477 if (!processing_template_decl
15478 /* Don't do it for instantiated variable templates either,
15479 cp_apply_type_quals_to_decl should have been called on it
15480 already and might have been overridden in cp_finish_decl
15481 if initializer needs runtime initialization. */
15482 && (!VAR_P (decl) || !DECL_TEMPLATE_INSTANTIATED (decl)))
15483 cp_apply_type_quals_to_decl (type_quals, decl);
15485 return decl;
15489 /* Subroutine of start_function. Ensure that each of the parameter
15490 types (as listed in PARMS) is complete, as is required for a
15491 function definition. */
15493 static void
15494 require_complete_types_for_parms (tree parms)
15496 for (; parms; parms = DECL_CHAIN (parms))
15498 if (dependent_type_p (TREE_TYPE (parms)))
15499 continue;
15500 if (!VOID_TYPE_P (TREE_TYPE (parms))
15501 && complete_type_or_else (TREE_TYPE (parms), parms))
15503 relayout_decl (parms);
15504 DECL_ARG_TYPE (parms) = type_passed_as (TREE_TYPE (parms));
15506 abstract_virtuals_error (parms, TREE_TYPE (parms));
15507 maybe_warn_parm_abi (TREE_TYPE (parms),
15508 DECL_SOURCE_LOCATION (parms));
15510 else
15511 /* grokparms or complete_type_or_else will have already issued
15512 an error. */
15513 TREE_TYPE (parms) = error_mark_node;
15517 /* Returns nonzero if T is a local variable. */
15520 local_variable_p (const_tree t)
15522 if ((VAR_P (t)
15523 && (DECL_LOCAL_DECL_P (t)
15524 || !DECL_CONTEXT (t)
15525 || TREE_CODE (DECL_CONTEXT (t)) == FUNCTION_DECL))
15526 || (TREE_CODE (t) == PARM_DECL))
15527 return 1;
15529 return 0;
15532 /* Like local_variable_p, but suitable for use as a tree-walking
15533 function. */
15535 static tree
15536 local_variable_p_walkfn (tree *tp, int *walk_subtrees,
15537 void * /*data*/)
15539 if (unevaluated_p (TREE_CODE (*tp)))
15541 /* DR 2082 permits local variables in unevaluated contexts
15542 within a default argument. */
15543 *walk_subtrees = 0;
15544 return NULL_TREE;
15547 if (local_variable_p (*tp)
15548 && (!DECL_ARTIFICIAL (*tp) || DECL_NAME (*tp) == this_identifier))
15549 return *tp;
15550 else if (TYPE_P (*tp))
15551 *walk_subtrees = 0;
15553 return NULL_TREE;
15556 /* Check that ARG, which is a default-argument expression for a
15557 parameter DECL, is valid. Returns ARG, or ERROR_MARK_NODE, if
15558 something goes wrong. DECL may also be a _TYPE node, rather than a
15559 DECL, if there is no DECL available. */
15561 tree
15562 check_default_argument (tree decl, tree arg, tsubst_flags_t complain)
15564 tree var;
15565 tree decl_type;
15567 if (TREE_CODE (arg) == DEFERRED_PARSE)
15568 /* We get a DEFERRED_PARSE when looking at an in-class declaration
15569 with a default argument. Ignore the argument for now; we'll
15570 deal with it after the class is complete. */
15571 return arg;
15573 if (TYPE_P (decl))
15575 decl_type = decl;
15576 decl = NULL_TREE;
15578 else
15579 decl_type = TREE_TYPE (decl);
15581 if (arg == error_mark_node
15582 || decl == error_mark_node
15583 || TREE_TYPE (arg) == error_mark_node
15584 || decl_type == error_mark_node)
15585 /* Something already went wrong. There's no need to check
15586 further. */
15587 return error_mark_node;
15589 /* [dcl.fct.default]
15591 A default argument expression is implicitly converted to the
15592 parameter type. */
15593 ++cp_unevaluated_operand;
15594 /* Avoid digest_init clobbering the initializer. */
15595 tree carg = BRACE_ENCLOSED_INITIALIZER_P (arg) ? unshare_expr (arg): arg;
15596 perform_implicit_conversion_flags (decl_type, carg, complain,
15597 LOOKUP_IMPLICIT);
15598 --cp_unevaluated_operand;
15600 /* Avoid redundant -Wzero-as-null-pointer-constant warnings at
15601 the call sites. */
15602 if (TYPE_PTR_OR_PTRMEM_P (decl_type)
15603 && null_ptr_cst_p (arg)
15604 /* Don't lose side-effects as in PR90473. */
15605 && !TREE_SIDE_EFFECTS (arg))
15606 return nullptr_node;
15608 /* [dcl.fct.default]
15610 Local variables shall not be used in default argument
15611 expressions.
15613 The keyword `this' shall not be used in a default argument of a
15614 member function. */
15615 var = cp_walk_tree_without_duplicates (&arg, local_variable_p_walkfn, NULL);
15616 if (var)
15618 if (complain & tf_warning_or_error)
15620 if (DECL_NAME (var) == this_identifier)
15621 permerror (input_location, "default argument %qE uses %qD",
15622 arg, var);
15623 else
15624 error ("default argument %qE uses local variable %qD", arg, var);
15626 return error_mark_node;
15629 /* All is well. */
15630 return arg;
15633 /* Returns a deprecated type used within TYPE, or NULL_TREE if none. */
15635 static tree
15636 type_is_deprecated (tree type)
15638 enum tree_code code;
15639 if (TREE_DEPRECATED (type))
15640 return type;
15641 if (TYPE_NAME (type))
15643 if (TREE_DEPRECATED (TYPE_NAME (type)))
15644 return type;
15645 else
15647 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
15648 return NULL_TREE;
15652 /* Do warn about using typedefs to a deprecated class. */
15653 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
15654 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
15656 code = TREE_CODE (type);
15658 if (code == POINTER_TYPE || code == REFERENCE_TYPE
15659 || code == OFFSET_TYPE || code == FUNCTION_TYPE
15660 || code == METHOD_TYPE || code == ARRAY_TYPE)
15661 return type_is_deprecated (TREE_TYPE (type));
15663 if (TYPE_PTRMEMFUNC_P (type))
15664 return type_is_deprecated
15665 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
15667 return NULL_TREE;
15670 /* Returns an unavailable type used within TYPE, or NULL_TREE if none. */
15672 static tree
15673 type_is_unavailable (tree type)
15675 enum tree_code code;
15676 if (TREE_UNAVAILABLE (type))
15677 return type;
15678 if (TYPE_NAME (type))
15680 if (TREE_UNAVAILABLE (TYPE_NAME (type)))
15681 return type;
15682 else
15684 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
15685 return NULL_TREE;
15689 /* Do warn about using typedefs to a deprecated class. */
15690 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
15691 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
15693 code = TREE_CODE (type);
15695 if (code == POINTER_TYPE || code == REFERENCE_TYPE
15696 || code == OFFSET_TYPE || code == FUNCTION_TYPE
15697 || code == METHOD_TYPE || code == ARRAY_TYPE)
15698 return type_is_unavailable (TREE_TYPE (type));
15700 if (TYPE_PTRMEMFUNC_P (type))
15701 return type_is_unavailable
15702 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
15704 return NULL_TREE;
15707 /* Decode the list of parameter types for a function type.
15708 Given the list of things declared inside the parens,
15709 return a list of types.
15711 If this parameter does not end with an ellipsis, we append
15712 void_list_node.
15714 *PARMS is set to the chain of PARM_DECLs created. */
15716 tree
15717 grokparms (tree parmlist, tree *parms)
15719 tree result = NULL_TREE;
15720 tree decls = NULL_TREE;
15721 tree parm;
15722 int any_error = 0;
15724 for (parm = parmlist; parm != NULL_TREE; parm = TREE_CHAIN (parm))
15726 tree type = NULL_TREE;
15727 tree init = TREE_PURPOSE (parm);
15728 tree decl = TREE_VALUE (parm);
15730 if (parm == void_list_node || parm == explicit_void_list_node)
15731 break;
15733 if (! decl || TREE_TYPE (decl) == error_mark_node)
15735 any_error = 1;
15736 continue;
15739 type = TREE_TYPE (decl);
15740 if (VOID_TYPE_P (type))
15742 if (same_type_p (type, void_type_node)
15743 && !init
15744 && !DECL_NAME (decl) && !result
15745 && TREE_CHAIN (parm) == void_list_node)
15746 /* DR 577: A parameter list consisting of a single
15747 unnamed parameter of non-dependent type 'void'. */
15748 break;
15749 else if (cv_qualified_p (type))
15750 error_at (DECL_SOURCE_LOCATION (decl),
15751 "invalid use of cv-qualified type %qT in "
15752 "parameter declaration", type);
15753 else
15754 error_at (DECL_SOURCE_LOCATION (decl),
15755 "invalid use of type %<void%> in parameter "
15756 "declaration");
15757 /* It's not a good idea to actually create parameters of
15758 type `void'; other parts of the compiler assume that a
15759 void type terminates the parameter list. */
15760 type = error_mark_node;
15761 TREE_TYPE (decl) = error_mark_node;
15764 if (type != error_mark_node)
15766 if (deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
15768 tree unavailtype = type_is_unavailable (type);
15769 if (unavailtype)
15770 cp_handle_deprecated_or_unavailable (unavailtype);
15772 if (deprecated_state != DEPRECATED_SUPPRESS
15773 && deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
15775 tree deptype = type_is_deprecated (type);
15776 if (deptype)
15777 cp_handle_deprecated_or_unavailable (deptype);
15780 /* [dcl.fct] "A parameter with volatile-qualified type is
15781 deprecated." */
15782 if (CP_TYPE_VOLATILE_P (type))
15783 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wvolatile,
15784 "%<volatile%>-qualified parameter is "
15785 "deprecated");
15787 /* Top-level qualifiers on the parameters are
15788 ignored for function types. */
15789 type = cp_build_qualified_type (type, 0);
15790 if (TREE_CODE (type) == METHOD_TYPE)
15792 error ("parameter %qD invalidly declared method type", decl);
15793 type = build_pointer_type (type);
15794 TREE_TYPE (decl) = type;
15796 else if (cxx_dialect < cxx17 && INDIRECT_TYPE_P (type))
15798 /* Before C++17 DR 393:
15799 [dcl.fct]/6, parameter types cannot contain pointers
15800 (references) to arrays of unknown bound. */
15801 tree t = TREE_TYPE (type);
15802 int ptr = TYPE_PTR_P (type);
15804 while (1)
15806 if (TYPE_PTR_P (t))
15807 ptr = 1;
15808 else if (TREE_CODE (t) != ARRAY_TYPE)
15809 break;
15810 else if (!TYPE_DOMAIN (t))
15811 break;
15812 t = TREE_TYPE (t);
15814 if (TREE_CODE (t) == ARRAY_TYPE)
15815 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
15817 ? G_("parameter %qD includes pointer to array of "
15818 "unknown bound %qT")
15819 : G_("parameter %qD includes reference to array of "
15820 "unknown bound %qT"),
15821 decl, t);
15824 if (init && !processing_template_decl)
15825 init = check_default_argument (decl, init, tf_warning_or_error);
15828 DECL_CHAIN (decl) = decls;
15829 decls = decl;
15830 result = tree_cons (init, type, result);
15832 decls = nreverse (decls);
15833 result = nreverse (result);
15834 if (parm)
15835 result = chainon (result, void_list_node);
15836 *parms = decls;
15837 if (any_error)
15838 result = NULL_TREE;
15840 if (any_error)
15841 /* We had parm errors, recover by giving the function (...) type. */
15842 result = NULL_TREE;
15844 return result;
15848 /* D is a constructor or overloaded `operator='.
15850 Let T be the class in which D is declared. Then, this function
15851 returns:
15853 -1 if D's is an ill-formed constructor or copy assignment operator
15854 whose first parameter is of type `T'.
15855 0 if D is not a copy constructor or copy assignment
15856 operator.
15857 1 if D is a copy constructor or copy assignment operator whose
15858 first parameter is a reference to non-const qualified T.
15859 2 if D is a copy constructor or copy assignment operator whose
15860 first parameter is a reference to const qualified T.
15862 This function can be used as a predicate. Positive values indicate
15863 a copy constructor and nonzero values indicate a copy assignment
15864 operator. */
15867 copy_fn_p (const_tree d)
15869 tree args;
15870 tree arg_type;
15871 int result = 1;
15873 gcc_assert (DECL_FUNCTION_MEMBER_P (d));
15875 if (TREE_CODE (d) == TEMPLATE_DECL
15876 || (DECL_TEMPLATE_INFO (d)
15877 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
15878 /* Instantiations of template member functions are never copy
15879 functions. Note that member functions of templated classes are
15880 represented as template functions internally, and we must
15881 accept those as copy functions. */
15882 return 0;
15884 if (!DECL_CONSTRUCTOR_P (d)
15885 && DECL_NAME (d) != assign_op_identifier)
15886 return 0;
15888 if (DECL_XOBJ_MEMBER_FUNCTION_P (d))
15890 tree object_param = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (d)));
15891 if (!TYPE_REF_P (object_param)
15892 || TYPE_REF_IS_RVALUE (object_param)
15893 /* Reject unrelated object parameters. */
15894 || TYPE_MAIN_VARIANT (TREE_TYPE (object_param)) != DECL_CONTEXT (d)
15895 || CP_TYPE_CONST_P (TREE_TYPE (object_param)))
15896 return 0;
15897 args = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (d)));
15899 else
15900 args = FUNCTION_FIRST_USER_PARMTYPE (d);
15901 if (!args)
15902 return 0;
15904 arg_type = TREE_VALUE (args);
15905 if (arg_type == error_mark_node)
15906 return 0;
15908 if (TYPE_MAIN_VARIANT (arg_type) == DECL_CONTEXT (d))
15910 /* Pass by value copy assignment operator. */
15911 result = -1;
15913 else if (TYPE_REF_P (arg_type)
15914 && !TYPE_REF_IS_RVALUE (arg_type)
15915 && TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)) == DECL_CONTEXT (d))
15917 if (CP_TYPE_CONST_P (TREE_TYPE (arg_type)))
15918 result = 2;
15920 else
15921 return 0;
15923 args = TREE_CHAIN (args);
15925 if (args && args != void_list_node && !TREE_PURPOSE (args))
15926 /* There are more non-optional args. */
15927 return 0;
15929 return result;
15932 /* D is a constructor or overloaded `operator='.
15934 Let T be the class in which D is declared. Then, this function
15935 returns true when D is a move constructor or move assignment
15936 operator, false otherwise. */
15938 bool
15939 move_fn_p (const_tree d)
15941 if (cxx_dialect == cxx98)
15942 /* There are no move constructors if we are in C++98 mode. */
15943 return false;
15945 if (TREE_CODE (d) == TEMPLATE_DECL
15946 || (DECL_TEMPLATE_INFO (d)
15947 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
15948 /* Instantiations of template member functions are never move
15949 functions. Note that member functions of templated classes are
15950 represented as template functions internally, and we must
15951 accept those as move functions. */
15952 return 0;
15954 return move_signature_fn_p (d);
15957 /* D is a constructor or overloaded `operator='.
15959 Then, this function returns true when D has the same signature as a move
15960 constructor or move assignment operator (because either it is such a
15961 ctor/op= or it is a template specialization with the same signature),
15962 false otherwise. */
15964 bool
15965 move_signature_fn_p (const_tree d)
15967 tree args;
15968 tree arg_type;
15969 bool result = false;
15971 if (!DECL_CONSTRUCTOR_P (d)
15972 && DECL_NAME (d) != assign_op_identifier)
15973 return 0;
15975 if (DECL_XOBJ_MEMBER_FUNCTION_P (d))
15977 tree object_param = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (d)));
15978 if (!TYPE_REF_P (object_param)
15979 || TYPE_REF_IS_RVALUE (object_param)
15980 /* Reject unrelated object parameters. */
15981 || TYPE_MAIN_VARIANT (TREE_TYPE (object_param)) != DECL_CONTEXT (d)
15982 || CP_TYPE_CONST_P (TREE_TYPE (object_param)))
15983 return 0;
15984 args = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (d)));
15986 else
15987 args = FUNCTION_FIRST_USER_PARMTYPE (d);
15988 if (!args)
15989 return 0;
15991 arg_type = TREE_VALUE (args);
15992 if (arg_type == error_mark_node)
15993 return 0;
15995 if (TYPE_REF_P (arg_type)
15996 && TYPE_REF_IS_RVALUE (arg_type)
15997 && same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)),
15998 DECL_CONTEXT (d)))
15999 result = true;
16001 args = TREE_CHAIN (args);
16003 if (args && args != void_list_node && !TREE_PURPOSE (args))
16004 /* There are more non-optional args. */
16005 return false;
16007 return result;
16010 /* Remember any special properties of member function DECL. */
16012 void
16013 grok_special_member_properties (tree decl)
16015 tree class_type;
16017 if (TREE_CODE (decl) == USING_DECL
16018 || !DECL_OBJECT_MEMBER_FUNCTION_P (decl))
16019 return;
16021 class_type = DECL_CONTEXT (decl);
16022 if (IDENTIFIER_CTOR_P (DECL_NAME (decl)))
16024 int ctor = copy_fn_p (decl);
16026 if (!DECL_ARTIFICIAL (decl))
16027 TYPE_HAS_USER_CONSTRUCTOR (class_type) = 1;
16029 if (ctor > 0)
16031 /* [class.copy]
16033 A non-template constructor for class X is a copy
16034 constructor if its first parameter is of type X&, const
16035 X&, volatile X& or const volatile X&, and either there
16036 are no other parameters or else all other parameters have
16037 default arguments. */
16038 TYPE_HAS_COPY_CTOR (class_type) = 1;
16039 if (ctor > 1)
16040 TYPE_HAS_CONST_COPY_CTOR (class_type) = 1;
16043 if (sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (decl)))
16044 TYPE_HAS_DEFAULT_CONSTRUCTOR (class_type) = 1;
16046 if (is_list_ctor (decl))
16047 TYPE_HAS_LIST_CTOR (class_type) = 1;
16049 if (maybe_constexpr_fn (decl)
16050 && !ctor && !move_fn_p (decl))
16051 TYPE_HAS_CONSTEXPR_CTOR (class_type) = 1;
16053 else if (DECL_NAME (decl) == assign_op_identifier)
16055 /* [class.copy]
16057 A non-template assignment operator for class X is a copy
16058 assignment operator if its parameter is of type X, X&, const
16059 X&, volatile X& or const volatile X&. */
16061 int assop = copy_fn_p (decl);
16063 if (assop)
16065 TYPE_HAS_COPY_ASSIGN (class_type) = 1;
16066 if (assop != 1)
16067 TYPE_HAS_CONST_COPY_ASSIGN (class_type) = 1;
16070 else if (IDENTIFIER_CONV_OP_P (DECL_NAME (decl)))
16071 TYPE_HAS_CONVERSION (class_type) = true;
16073 /* Destructors are handled in check_methods. */
16076 /* Check a constructor DECL has the correct form. Complains
16077 if the class has a constructor of the form X(X). */
16079 bool
16080 grok_ctor_properties (const_tree ctype, const_tree decl)
16082 int ctor_parm = copy_fn_p (decl);
16084 if (ctor_parm < 0)
16086 /* [class.copy]
16088 A declaration of a constructor for a class X is ill-formed if
16089 its first parameter is of type (optionally cv-qualified) X
16090 and either there are no other parameters or else all other
16091 parameters have default arguments.
16093 We *don't* complain about member template instantiations that
16094 have this form, though; they can occur as we try to decide
16095 what constructor to use during overload resolution. Since
16096 overload resolution will never prefer such a constructor to
16097 the non-template copy constructor (which is either explicitly
16098 or implicitly defined), there's no need to worry about their
16099 existence. Theoretically, they should never even be
16100 instantiated, but that's hard to forestall. */
16101 error_at (DECL_SOURCE_LOCATION (decl),
16102 "invalid constructor; you probably meant %<%T (const %T&)%>",
16103 ctype, ctype);
16104 return false;
16107 return true;
16110 /* DECL is a declaration for an overloaded or conversion operator. If
16111 COMPLAIN is true, errors are issued for invalid declarations. */
16113 bool
16114 grok_op_properties (tree decl, bool complain)
16116 tree argtypes = TYPE_ARG_TYPES (TREE_TYPE (decl));
16117 bool const methodp = DECL_IOBJ_MEMBER_FUNCTION_P (decl);
16118 tree name = DECL_NAME (decl);
16119 location_t loc = DECL_SOURCE_LOCATION (decl);
16121 tree class_type = DECL_CONTEXT (decl);
16122 if (class_type && !CLASS_TYPE_P (class_type))
16123 class_type = NULL_TREE;
16125 tree_code operator_code;
16126 unsigned op_flags;
16127 if (IDENTIFIER_CONV_OP_P (name))
16129 /* Conversion operators are TYPE_EXPR for the purposes of this
16130 function. */
16131 operator_code = TYPE_EXPR;
16132 op_flags = OVL_OP_FLAG_UNARY;
16134 else
16136 const ovl_op_info_t *ovl_op = IDENTIFIER_OVL_OP_INFO (name);
16138 operator_code = ovl_op->tree_code;
16139 op_flags = ovl_op->flags;
16140 gcc_checking_assert (operator_code != ERROR_MARK);
16141 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
16144 if (op_flags & OVL_OP_FLAG_ALLOC)
16146 /* operator new and operator delete are quite special. */
16147 if (class_type)
16148 switch (op_flags)
16150 case OVL_OP_FLAG_ALLOC:
16151 TYPE_HAS_NEW_OPERATOR (class_type) = 1;
16152 break;
16154 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE:
16155 TYPE_GETS_DELETE (class_type) |= 1;
16156 break;
16158 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_VEC:
16159 TYPE_HAS_ARRAY_NEW_OPERATOR (class_type) = 1;
16160 break;
16162 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE | OVL_OP_FLAG_VEC:
16163 TYPE_GETS_DELETE (class_type) |= 2;
16164 break;
16166 default:
16167 gcc_unreachable ();
16170 /* [basic.std.dynamic.allocation]/1:
16172 A program is ill-formed if an allocation function is declared
16173 in a namespace scope other than global scope or declared
16174 static in global scope.
16176 The same also holds true for deallocation functions. */
16177 if (DECL_NAMESPACE_SCOPE_P (decl))
16179 if (CP_DECL_CONTEXT (decl) != global_namespace)
16181 error_at (loc, "%qD may not be declared within a namespace",
16182 decl);
16183 return false;
16186 if (!TREE_PUBLIC (decl))
16188 error_at (loc, "%qD may not be declared as static", decl);
16189 return false;
16193 if (op_flags & OVL_OP_FLAG_DELETE)
16195 DECL_SET_IS_OPERATOR_DELETE (decl, true);
16196 coerce_delete_type (decl, loc);
16198 else
16200 DECL_SET_IS_OPERATOR_NEW (decl, true);
16201 TREE_TYPE (decl) = coerce_new_type (TREE_TYPE (decl), loc);
16204 return true;
16207 /* An operator function must either be a non-static member function
16208 or have at least one parameter of a class, a reference to a class,
16209 an enumeration, or a reference to an enumeration. 13.4.0.6 */
16210 if (!DECL_OBJECT_MEMBER_FUNCTION_P (decl))
16212 if (operator_code == TYPE_EXPR
16213 || operator_code == COMPONENT_REF
16214 || operator_code == NOP_EXPR)
16216 error_at (loc, "%qD must be a non-static member function", decl);
16217 return false;
16220 if (operator_code == CALL_EXPR || operator_code == ARRAY_REF)
16222 if (! DECL_STATIC_FUNCTION_P (decl))
16224 error_at (loc, "%qD must be a member function", decl);
16225 return false;
16227 if (cxx_dialect < cxx23
16228 /* For lambdas we diagnose static lambda specifier elsewhere. */
16229 && (operator_code == ARRAY_REF || ! LAMBDA_FUNCTION_P (decl))
16230 /* For instantiations, we have diagnosed this already. */
16231 && ! DECL_USE_TEMPLATE (decl))
16232 pedwarn (loc, OPT_Wc__23_extensions, "%qD may be a static member "
16233 "function only with %<-std=c++23%> or %<-std=gnu++23%>",
16234 decl);
16235 if (operator_code == ARRAY_REF)
16236 /* static operator[] should have exactly one argument
16237 for C++20 and earlier, so that it isn't multidimensional. */
16238 op_flags = OVL_OP_FLAG_UNARY;
16240 else if (DECL_STATIC_FUNCTION_P (decl))
16242 error_at (loc, "%qD must be either a non-static member "
16243 "function or a non-member function", decl);
16244 return false;
16246 else
16247 for (tree arg = argtypes; ; arg = TREE_CHAIN (arg))
16249 if (!arg || arg == void_list_node)
16251 if (complain)
16252 error_at (loc, "%qD must have an argument of class or "
16253 "enumerated type", decl);
16254 return false;
16257 tree type = non_reference (TREE_VALUE (arg));
16258 if (type == error_mark_node)
16259 return false;
16261 /* MAYBE_CLASS_TYPE_P, rather than CLASS_TYPE_P, is used
16262 because these checks are performed even on template
16263 functions. */
16264 if (MAYBE_CLASS_TYPE_P (type)
16265 || TREE_CODE (type) == ENUMERAL_TYPE)
16266 break;
16270 if (operator_code == CALL_EXPR)
16271 /* There are no further restrictions on the arguments to an overloaded
16272 "operator ()". */
16273 return true;
16275 /* C++23 allows an arbitrary number of parameters and default arguments for
16276 operator[], and none of the other checks below apply. */
16277 if (operator_code == ARRAY_REF && cxx_dialect >= cxx23)
16278 return true;
16280 if (operator_code == COND_EXPR)
16282 /* 13.4.0.3 */
16283 error_at (loc, "ISO C++ prohibits overloading %<operator ?:%>");
16284 return false;
16287 /* Count the number of arguments and check for ellipsis. */
16288 int arity = 0;
16289 for (tree arg = argtypes; arg != void_list_node; arg = TREE_CHAIN (arg))
16291 if (!arg)
16293 error_at (loc, "%qD must not have variable number of arguments",
16294 decl);
16295 return false;
16297 ++arity;
16299 /* FIXME: We need tests for these errors with xobj member functions. */
16300 /* Verify correct number of arguments. */
16301 switch (op_flags)
16303 case OVL_OP_FLAG_AMBIARY:
16304 if (arity == 1)
16306 /* We have a unary instance of an ambi-ary op. Remap to the
16307 unary one. */
16308 unsigned alt = ovl_op_alternate[ovl_op_mapping [operator_code]];
16309 const ovl_op_info_t *ovl_op = &ovl_op_info[false][alt];
16310 gcc_checking_assert (ovl_op->flags == OVL_OP_FLAG_UNARY);
16311 operator_code = ovl_op->tree_code;
16312 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
16314 else if (arity != 2)
16316 /* This was an ambiguous operator but is invalid. */
16317 error_at (loc,
16318 methodp
16319 ? G_("%qD must have either zero or one argument")
16320 : G_("%qD must have either one or two arguments"), decl);
16321 return false;
16323 else if ((operator_code == POSTINCREMENT_EXPR
16324 || operator_code == POSTDECREMENT_EXPR)
16325 && ! processing_template_decl
16326 /* x++ and x--'s second argument must be an int. */
16327 && ! same_type_p (TREE_VALUE (TREE_CHAIN (argtypes)),
16328 integer_type_node))
16330 error_at (loc,
16331 methodp
16332 ? G_("postfix %qD must have %<int%> as its argument")
16333 : G_("postfix %qD must have %<int%> as its second argument"),
16334 decl);
16335 return false;
16337 break;
16339 case OVL_OP_FLAG_UNARY:
16340 if (arity != 1)
16342 error_at (loc,
16343 methodp
16344 ? G_("%qD must have no arguments")
16345 : G_("%qD must have exactly one argument"), decl);
16346 return false;
16348 break;
16350 case OVL_OP_FLAG_BINARY:
16351 if (arity != 2)
16353 error_at (loc,
16354 methodp
16355 ? G_("%qD must have exactly one argument")
16356 : G_("%qD must have exactly two arguments"), decl);
16357 return false;
16359 break;
16361 default:
16362 gcc_unreachable ();
16365 /* There can be no default arguments. */
16366 for (tree arg = argtypes; arg && arg != void_list_node;
16367 arg = TREE_CHAIN (arg))
16368 if (TREE_PURPOSE (arg))
16370 TREE_PURPOSE (arg) = NULL_TREE;
16371 error_at (loc, "%qD cannot have default arguments", decl);
16372 return false;
16375 /* At this point the declaration is well-formed. It may not be
16376 sensible though. */
16378 /* Check member function warnings only on the in-class declaration.
16379 There's no point warning on an out-of-class definition. */
16380 if (class_type && class_type != current_class_type)
16381 return true;
16383 /* Warn about conversion operators that will never be used. */
16384 if (IDENTIFIER_CONV_OP_P (name)
16385 && ! DECL_TEMPLATE_INFO (decl)
16386 && warn_class_conversion)
16388 tree t = TREE_TYPE (name);
16389 int ref = TYPE_REF_P (t);
16391 if (ref)
16392 t = TYPE_MAIN_VARIANT (TREE_TYPE (t));
16394 if (VOID_TYPE_P (t))
16395 warning_at (loc, OPT_Wclass_conversion, "converting %qT to %<void%> "
16396 "will never use a type conversion operator", class_type);
16397 else if (class_type)
16399 if (same_type_ignoring_top_level_qualifiers_p (t, class_type))
16400 warning_at (loc, OPT_Wclass_conversion,
16402 ? G_("converting %qT to a reference to the same type "
16403 "will never use a type conversion operator")
16404 : G_("converting %qT to the same type "
16405 "will never use a type conversion operator"),
16406 class_type);
16407 /* Don't force t to be complete here. */
16408 else if (MAYBE_CLASS_TYPE_P (t)
16409 && COMPLETE_TYPE_P (t)
16410 && DERIVED_FROM_P (t, class_type))
16411 warning_at (loc, OPT_Wclass_conversion,
16413 ? G_("converting %qT to a reference to a base class "
16414 "%qT will never use a type conversion operator")
16415 : G_("converting %qT to a base class %qT "
16416 "will never use a type conversion operator"),
16417 class_type, t);
16421 if (!warn_ecpp)
16422 return true;
16424 /* Effective C++ rules below. */
16426 /* More Effective C++ rule 7. */
16427 if (operator_code == TRUTH_ANDIF_EXPR
16428 || operator_code == TRUTH_ORIF_EXPR
16429 || operator_code == COMPOUND_EXPR)
16430 warning_at (loc, OPT_Weffc__,
16431 "user-defined %qD always evaluates both arguments", decl);
16433 /* More Effective C++ rule 6. */
16434 if (operator_code == POSTINCREMENT_EXPR
16435 || operator_code == POSTDECREMENT_EXPR
16436 || operator_code == PREINCREMENT_EXPR
16437 || operator_code == PREDECREMENT_EXPR)
16439 tree arg = TREE_VALUE (argtypes);
16440 tree ret = TREE_TYPE (TREE_TYPE (decl));
16441 if (methodp || TYPE_REF_P (arg))
16442 arg = TREE_TYPE (arg);
16443 arg = TYPE_MAIN_VARIANT (arg);
16445 if (operator_code == PREINCREMENT_EXPR
16446 || operator_code == PREDECREMENT_EXPR)
16448 if (!TYPE_REF_P (ret)
16449 || !same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (ret)), arg))
16450 warning_at (loc, OPT_Weffc__, "prefix %qD should return %qT", decl,
16451 build_reference_type (arg));
16453 else
16455 if (!same_type_p (TYPE_MAIN_VARIANT (ret), arg))
16456 warning_at (loc, OPT_Weffc__,
16457 "postfix %qD should return %qT", decl, arg);
16461 /* Effective C++ rule 23. */
16462 if (!DECL_ASSIGNMENT_OPERATOR_P (decl)
16463 && (operator_code == PLUS_EXPR
16464 || operator_code == MINUS_EXPR
16465 || operator_code == TRUNC_DIV_EXPR
16466 || operator_code == MULT_EXPR
16467 || operator_code == TRUNC_MOD_EXPR)
16468 && TYPE_REF_P (TREE_TYPE (TREE_TYPE (decl))))
16469 warning_at (loc, OPT_Weffc__, "%qD should return by value", decl);
16471 return true;
16474 /* Return a string giving the keyword associate with CODE. */
16476 static const char *
16477 tag_name (enum tag_types code)
16479 switch (code)
16481 case record_type:
16482 return "struct";
16483 case class_type:
16484 return "class";
16485 case union_type:
16486 return "union";
16487 case enum_type:
16488 return "enum";
16489 case typename_type:
16490 return "typename";
16491 default:
16492 gcc_unreachable ();
16496 /* Name lookup in an elaborated-type-specifier (after the keyword
16497 indicated by TAG_CODE) has found the TYPE_DECL DECL. If the
16498 elaborated-type-specifier is invalid, issue a diagnostic and return
16499 error_mark_node; otherwise, return the *_TYPE to which it referred.
16500 If ALLOW_TEMPLATE_P is true, TYPE may be a class template. */
16502 tree
16503 check_elaborated_type_specifier (enum tag_types tag_code,
16504 tree decl,
16505 bool allow_template_p)
16507 tree type;
16509 /* In the case of:
16511 struct S { struct S *p; };
16513 name lookup will find the TYPE_DECL for the implicit "S::S"
16514 typedef. Adjust for that here. */
16515 if (DECL_SELF_REFERENCE_P (decl))
16516 decl = TYPE_NAME (TREE_TYPE (decl));
16518 type = TREE_TYPE (decl);
16520 /* Check TEMPLATE_TYPE_PARM first because DECL_IMPLICIT_TYPEDEF_P
16521 is false for this case as well. */
16522 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16524 error ("using template type parameter %qT after %qs",
16525 type, tag_name (tag_code));
16526 return error_mark_node;
16528 /* Accept template template parameters. */
16529 else if (allow_template_p
16530 && (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
16531 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM))
16533 /* [dcl.type.elab]
16535 If the identifier resolves to a typedef-name or the
16536 simple-template-id resolves to an alias template
16537 specialization, the elaborated-type-specifier is ill-formed.
16539 In other words, the only legitimate declaration to use in the
16540 elaborated type specifier is the implicit typedef created when
16541 the type is declared. */
16542 else if (!DECL_IMPLICIT_TYPEDEF_P (decl)
16543 && !DECL_SELF_REFERENCE_P (decl)
16544 && tag_code != typename_type)
16546 auto_diagnostic_group d;
16547 if (alias_template_specialization_p (type, nt_opaque))
16548 error ("using alias template specialization %qT after %qs",
16549 type, tag_name (tag_code));
16550 else
16551 error ("using typedef-name %qD after %qs", decl, tag_name (tag_code));
16552 inform (DECL_SOURCE_LOCATION (decl),
16553 "%qD has a previous declaration here", decl);
16554 return error_mark_node;
16556 else if (TREE_CODE (type) != RECORD_TYPE
16557 && TREE_CODE (type) != UNION_TYPE
16558 && tag_code != enum_type
16559 && tag_code != typename_type)
16561 auto_diagnostic_group d;
16562 error ("%qT referred to as %qs", type, tag_name (tag_code));
16563 inform (location_of (type), "%qT has a previous declaration here", type);
16564 return error_mark_node;
16566 else if (TREE_CODE (type) != ENUMERAL_TYPE
16567 && tag_code == enum_type)
16569 auto_diagnostic_group d;
16570 error ("%qT referred to as enum", type);
16571 inform (location_of (type), "%qT has a previous declaration here", type);
16572 return error_mark_node;
16574 else if (!allow_template_p
16575 && TREE_CODE (type) == RECORD_TYPE
16576 && CLASSTYPE_IS_TEMPLATE (type))
16578 /* If a class template appears as elaborated type specifier
16579 without a template header such as:
16581 template <class T> class C {};
16582 void f(class C); // No template header here
16584 then the required template argument is missing. */
16585 error ("template argument required for %<%s %T%>",
16586 tag_name (tag_code),
16587 DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)));
16588 return error_mark_node;
16591 return type;
16594 /* Lookup NAME of an elaborated type specifier according to SCOPE and
16595 issue diagnostics if necessary. Return *_TYPE node upon success,
16596 NULL_TREE when the NAME is not found, and ERROR_MARK_NODE for type
16597 error. */
16599 static tree
16600 lookup_and_check_tag (enum tag_types tag_code, tree name,
16601 TAG_how how, bool template_header_p)
16603 tree decl;
16604 if (how == TAG_how::GLOBAL)
16606 /* First try ordinary name lookup, ignoring hidden class name
16607 injected via friend declaration. */
16608 decl = lookup_name (name, LOOK_want::TYPE);
16609 /* If that fails, the name will be placed in the smallest
16610 non-class, non-function-prototype scope according to 3.3.1/5.
16611 We may already have a hidden name declared as friend in this
16612 scope. So lookup again but not ignoring hidden names.
16613 If we find one, that name will be made visible rather than
16614 creating a new tag. */
16615 if (!decl)
16616 decl = lookup_elaborated_type (name, TAG_how::INNERMOST_NON_CLASS);
16618 else
16619 decl = lookup_elaborated_type (name, how);
16621 if (!decl)
16622 /* We found nothing. */
16623 return NULL_TREE;
16625 if (TREE_CODE (decl) == TREE_LIST)
16627 auto_diagnostic_group d;
16628 error ("reference to %qD is ambiguous", name);
16629 print_candidates (decl);
16630 return error_mark_node;
16633 if (DECL_CLASS_TEMPLATE_P (decl)
16634 && !template_header_p
16635 && how == TAG_how::CURRENT_ONLY)
16637 auto_diagnostic_group d;
16638 error ("class template %qD redeclared as non-template", name);
16639 inform (location_of (decl), "previous declaration here");
16640 CLASSTYPE_ERRONEOUS (TREE_TYPE (decl)) = true;
16641 return error_mark_node;
16644 if (DECL_CLASS_TEMPLATE_P (decl)
16645 /* If scope is TAG_how::CURRENT_ONLY we're defining a class,
16646 so ignore a template template parameter. */
16647 || (how != TAG_how::CURRENT_ONLY && DECL_TEMPLATE_TEMPLATE_PARM_P (decl)))
16648 decl = DECL_TEMPLATE_RESULT (decl);
16650 if (TREE_CODE (decl) != TYPE_DECL)
16651 /* Found not-a-type. */
16652 return NULL_TREE;
16654 /* Look for invalid nested type:
16655 class C {
16656 class C {};
16657 }; */
16658 if (how == TAG_how::CURRENT_ONLY && DECL_SELF_REFERENCE_P (decl))
16660 error ("%qD has the same name as the class in which it is "
16661 "declared", decl);
16662 return error_mark_node;
16665 /* Two cases we need to consider when deciding if a class
16666 template is allowed as an elaborated type specifier:
16667 1. It is a self reference to its own class.
16668 2. It comes with a template header.
16670 For example:
16672 template <class T> class C {
16673 class C *c1; // DECL_SELF_REFERENCE_P is true
16674 class D;
16676 template <class U> class C; // template_header_p is true
16677 template <class T> class C<T>::D {
16678 class C *c2; // DECL_SELF_REFERENCE_P is true
16679 }; */
16681 tree t = check_elaborated_type_specifier (tag_code, decl,
16682 template_header_p
16683 | DECL_SELF_REFERENCE_P (decl));
16684 if (template_header_p && t && CLASS_TYPE_P (t)
16685 && (!CLASSTYPE_TEMPLATE_INFO (t)
16686 || (!PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))))
16688 auto_diagnostic_group d;
16689 error ("%qT is not a template", t);
16690 inform (location_of (t), "previous declaration here");
16691 if (TYPE_CLASS_SCOPE_P (t)
16692 && CLASSTYPE_TEMPLATE_INFO (TYPE_CONTEXT (t)))
16693 inform (input_location,
16694 "perhaps you want to explicitly add %<%T::%>",
16695 TYPE_CONTEXT (t));
16696 return error_mark_node;
16699 return t;
16702 /* Get the struct, enum or union (TAG_CODE says which) with tag NAME.
16703 Define the tag as a forward-reference if it is not defined.
16705 If a declaration is given, process it here, and report an error if
16706 multiple declarations are not identical.
16708 SCOPE is TS_CURRENT when this is also a definition. Only look in
16709 the current frame for the name (since C++ allows new names in any
16710 scope.) It is TS_WITHIN_ENCLOSING_NON_CLASS if this is a friend
16711 declaration. Only look beginning from the current scope outward up
16712 till the nearest non-class scope. Otherwise it is TS_GLOBAL.
16714 TEMPLATE_HEADER_P is true when this declaration is preceded by
16715 a set of template parameters. */
16717 tree
16718 xref_tag (enum tag_types tag_code, tree name,
16719 TAG_how how, bool template_header_p)
16721 enum tree_code code;
16722 tree context = NULL_TREE;
16724 auto_cond_timevar tv (TV_NAME_LOOKUP);
16726 gcc_assert (identifier_p (name));
16728 switch (tag_code)
16730 case record_type:
16731 case class_type:
16732 code = RECORD_TYPE;
16733 break;
16734 case union_type:
16735 code = UNION_TYPE;
16736 break;
16737 case enum_type:
16738 code = ENUMERAL_TYPE;
16739 break;
16740 default:
16741 gcc_unreachable ();
16744 /* In case of anonymous name, xref_tag is only called to
16745 make type node and push name. Name lookup is not required. */
16746 tree t = NULL_TREE;
16747 if (!IDENTIFIER_ANON_P (name))
16748 t = lookup_and_check_tag (tag_code, name, how, template_header_p);
16750 if (t == error_mark_node)
16751 return error_mark_node;
16753 if (how != TAG_how::CURRENT_ONLY && t && current_class_type
16754 && template_class_depth (current_class_type)
16755 && template_header_p)
16757 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
16758 return t;
16760 /* Since HOW is not TAG_how::CURRENT_ONLY, we are not looking at
16761 a definition of this tag. Since, in addition, we are
16762 currently processing a (member) template declaration of a
16763 template class, we must be very careful; consider:
16765 template <class X> struct S1
16767 template <class U> struct S2
16769 template <class V> friend struct S1;
16772 Here, the S2::S1 declaration should not be confused with the
16773 outer declaration. In particular, the inner version should
16774 have a template parameter of level 2, not level 1.
16776 On the other hand, when presented with:
16778 template <class T> struct S1
16780 template <class U> struct S2 {};
16781 template <class U> friend struct S2;
16784 the friend must find S1::S2 eventually. We accomplish this
16785 by making sure that the new type we create to represent this
16786 declaration has the right TYPE_CONTEXT. */
16787 context = TYPE_CONTEXT (t);
16788 t = NULL_TREE;
16791 if (! t)
16793 /* If no such tag is yet defined, create a forward-reference node
16794 and record it as the "definition".
16795 When a real declaration of this type is found,
16796 the forward-reference will be altered into a real type. */
16797 if (code == ENUMERAL_TYPE)
16799 error ("use of enum %q#D without previous declaration", name);
16800 return error_mark_node;
16803 t = make_class_type (code);
16804 TYPE_CONTEXT (t) = context;
16805 if (IDENTIFIER_LAMBDA_P (name))
16806 /* Mark it as a lambda type right now. Our caller will
16807 correct the value. */
16808 CLASSTYPE_LAMBDA_EXPR (t) = error_mark_node;
16809 t = pushtag (name, t, how);
16811 else
16813 if (template_header_p && MAYBE_CLASS_TYPE_P (t))
16815 /* Check that we aren't trying to overload a class with different
16816 constraints. */
16817 if (!redeclare_class_template (t, current_template_parms,
16818 current_template_constraints ()))
16819 return error_mark_node;
16821 else if (!processing_template_decl
16822 && CLASS_TYPE_P (t)
16823 && CLASSTYPE_IS_TEMPLATE (t))
16825 auto_diagnostic_group d;
16826 error ("redeclaration of %qT as a non-template", t);
16827 inform (location_of (t), "previous declaration %qD", t);
16828 return error_mark_node;
16831 if (modules_p ()
16832 && how == TAG_how::CURRENT_ONLY)
16834 tree decl = TYPE_NAME (t);
16835 if (!module_may_redeclare (decl))
16836 return error_mark_node;
16838 tree not_tmpl = STRIP_TEMPLATE (decl);
16839 if (DECL_LANG_SPECIFIC (not_tmpl)
16840 && DECL_MODULE_ATTACH_P (not_tmpl)
16841 && !DECL_MODULE_EXPORT_P (not_tmpl)
16842 && module_exporting_p ())
16844 auto_diagnostic_group d;
16845 error ("conflicting exporting for declaration %qD", decl);
16846 inform (DECL_SOURCE_LOCATION (decl),
16847 "previously declared here without exporting");
16850 tree maybe_tmpl = decl;
16851 if (CLASS_TYPE_P (t) && CLASSTYPE_IS_TEMPLATE (t))
16852 maybe_tmpl = CLASSTYPE_TI_TEMPLATE (t);
16854 /* FIXME: we should do a more precise check for redefinitions
16855 of a conflicting using-declaration here, as these diagnostics
16856 are not ideal. */
16857 if (DECL_LANG_SPECIFIC (decl)
16858 && DECL_MODULE_IMPORT_P (decl)
16859 && CP_DECL_CONTEXT (decl) == current_namespace)
16861 /* Push it into this TU's symbol slot. */
16862 if (maybe_tmpl != decl)
16863 /* We're in the template parm binding level.
16864 Pushtag has logic to slide under that, but we're
16865 not pushing a *new* type. */
16866 push_nested_namespace (CP_DECL_CONTEXT (decl));
16868 pushdecl (maybe_tmpl);
16869 if (maybe_tmpl != decl)
16870 pop_nested_namespace (CP_DECL_CONTEXT (decl));
16873 set_instantiating_module (maybe_tmpl);
16877 return t;
16880 /* Create the binfo hierarchy for REF with (possibly NULL) base list
16881 BASE_LIST. For each element on BASE_LIST the TREE_PURPOSE is an
16882 access_* node, and the TREE_VALUE is the type of the base-class.
16883 Non-NULL TREE_TYPE indicates virtual inheritance. */
16885 void
16886 xref_basetypes (tree ref, tree base_list)
16888 tree *basep;
16889 tree binfo, base_binfo;
16890 unsigned max_vbases = 0; /* Maximum direct & indirect virtual bases. */
16891 unsigned max_bases = 0; /* Maximum direct bases. */
16892 unsigned max_dvbases = 0; /* Maximum direct virtual bases. */
16893 int i;
16894 tree default_access;
16895 tree igo_prev; /* Track Inheritance Graph Order. */
16897 if (ref == error_mark_node)
16898 return;
16900 /* The base of a derived class is private by default, all others are
16901 public. */
16902 default_access = (TREE_CODE (ref) == RECORD_TYPE
16903 && CLASSTYPE_DECLARED_CLASS (ref)
16904 ? access_private_node : access_public_node);
16906 /* First, make sure that any templates in base-classes are
16907 instantiated. This ensures that if we call ourselves recursively
16908 we do not get confused about which classes are marked and which
16909 are not. */
16910 basep = &base_list;
16911 while (*basep)
16913 tree basetype = TREE_VALUE (*basep);
16915 /* The dependent_type_p call below should really be dependent_scope_p
16916 so that we give a hard error about using an incomplete type as a
16917 base, but we allow it with a pedwarn for backward
16918 compatibility. */
16919 if (processing_template_decl
16920 && CLASS_TYPE_P (basetype) && TYPE_BEING_DEFINED (basetype))
16921 cxx_incomplete_type_diagnostic (NULL_TREE, basetype, DK_PEDWARN);
16922 if (!dependent_type_p (basetype)
16923 && !complete_type_or_else (basetype, NULL))
16924 /* An incomplete type. Remove it from the list. */
16925 *basep = TREE_CHAIN (*basep);
16926 else
16928 max_bases++;
16929 if (TREE_TYPE (*basep))
16930 max_dvbases++;
16931 if (CLASS_TYPE_P (basetype))
16932 max_vbases += vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
16933 basep = &TREE_CHAIN (*basep);
16936 max_vbases += max_dvbases;
16938 TYPE_MARKED_P (ref) = 1;
16940 /* The binfo slot should be empty, unless this is an (ill-formed)
16941 redefinition. */
16942 gcc_assert (!TYPE_BINFO (ref) || TYPE_SIZE (ref));
16944 gcc_assert (TYPE_MAIN_VARIANT (ref) == ref);
16946 binfo = make_tree_binfo (max_bases);
16948 TYPE_BINFO (ref) = binfo;
16949 BINFO_OFFSET (binfo) = size_zero_node;
16950 BINFO_TYPE (binfo) = ref;
16952 /* Apply base-class info set up to the variants of this type. */
16953 fixup_type_variants (ref);
16955 if (max_bases)
16957 vec_alloc (BINFO_BASE_ACCESSES (binfo), max_bases);
16958 /* A C++98 POD cannot have base classes. */
16959 CLASSTYPE_NON_LAYOUT_POD_P (ref) = true;
16961 if (TREE_CODE (ref) == UNION_TYPE)
16963 error ("derived union %qT invalid", ref);
16964 return;
16968 if (max_bases > 1)
16969 warning (OPT_Wmultiple_inheritance,
16970 "%qT defined with multiple direct bases", ref);
16972 if (max_vbases)
16974 /* An aggregate can't have virtual base classes. */
16975 CLASSTYPE_NON_AGGREGATE (ref) = true;
16977 vec_alloc (CLASSTYPE_VBASECLASSES (ref), max_vbases);
16979 if (max_dvbases)
16980 warning (OPT_Wvirtual_inheritance,
16981 "%qT defined with direct virtual base", ref);
16984 for (igo_prev = binfo; base_list; base_list = TREE_CHAIN (base_list))
16986 tree access = TREE_PURPOSE (base_list);
16987 int via_virtual = TREE_TYPE (base_list) != NULL_TREE;
16988 tree basetype = TREE_VALUE (base_list);
16990 if (access == access_default_node)
16991 access = default_access;
16993 /* Before C++17, an aggregate cannot have base classes. In C++17, an
16994 aggregate can't have virtual, private, or protected base classes. */
16995 if (cxx_dialect < cxx17
16996 || access != access_public_node
16997 || via_virtual)
16998 CLASSTYPE_NON_AGGREGATE (ref) = true;
17000 if (PACK_EXPANSION_P (basetype))
17001 basetype = PACK_EXPANSION_PATTERN (basetype);
17002 if (TREE_CODE (basetype) == TYPE_DECL)
17003 basetype = TREE_TYPE (basetype);
17004 if (!MAYBE_CLASS_TYPE_P (basetype) || TREE_CODE (basetype) == UNION_TYPE)
17006 error ("base type %qT fails to be a struct or class type",
17007 basetype);
17008 goto dropped_base;
17011 base_binfo = NULL_TREE;
17012 if (CLASS_TYPE_P (basetype) && !dependent_scope_p (basetype))
17014 base_binfo = TYPE_BINFO (basetype);
17015 /* The original basetype could have been a typedef'd type. */
17016 basetype = BINFO_TYPE (base_binfo);
17018 /* Inherit flags from the base. */
17019 TYPE_HAS_NEW_OPERATOR (ref)
17020 |= TYPE_HAS_NEW_OPERATOR (basetype);
17021 TYPE_HAS_ARRAY_NEW_OPERATOR (ref)
17022 |= TYPE_HAS_ARRAY_NEW_OPERATOR (basetype);
17023 TYPE_GETS_DELETE (ref) |= TYPE_GETS_DELETE (basetype);
17024 TYPE_HAS_CONVERSION (ref) |= TYPE_HAS_CONVERSION (basetype);
17025 CLASSTYPE_DIAMOND_SHAPED_P (ref)
17026 |= CLASSTYPE_DIAMOND_SHAPED_P (basetype);
17027 CLASSTYPE_REPEATED_BASE_P (ref)
17028 |= CLASSTYPE_REPEATED_BASE_P (basetype);
17031 /* We must do this test after we've seen through a typedef
17032 type. */
17033 if (TYPE_MARKED_P (basetype))
17035 if (basetype == ref)
17036 error ("recursive type %qT undefined", basetype);
17037 else
17038 error ("duplicate base type %qT invalid", basetype);
17039 goto dropped_base;
17042 if (PACK_EXPANSION_P (TREE_VALUE (base_list)))
17043 /* Regenerate the pack expansion for the bases. */
17044 basetype = make_pack_expansion (basetype);
17046 TYPE_MARKED_P (basetype) = 1;
17048 base_binfo = copy_binfo (base_binfo, basetype, ref,
17049 &igo_prev, via_virtual);
17050 if (!BINFO_INHERITANCE_CHAIN (base_binfo))
17051 BINFO_INHERITANCE_CHAIN (base_binfo) = binfo;
17053 BINFO_BASE_APPEND (binfo, base_binfo);
17054 BINFO_BASE_ACCESS_APPEND (binfo, access);
17055 continue;
17057 dropped_base:
17058 /* Update max_vbases to reflect the reality that we are dropping
17059 this base: if it reaches zero we want to undo the vec_alloc
17060 above to avoid inconsistencies during error-recovery: eg, in
17061 build_special_member_call, CLASSTYPE_VBASECLASSES non null
17062 and vtt null (c++/27952). */
17063 if (via_virtual)
17064 max_vbases--;
17065 if (CLASS_TYPE_P (basetype))
17066 max_vbases
17067 -= vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
17070 if (CLASSTYPE_VBASECLASSES (ref)
17071 && max_vbases == 0)
17072 vec_free (CLASSTYPE_VBASECLASSES (ref));
17074 if (vec_safe_length (CLASSTYPE_VBASECLASSES (ref)) < max_vbases)
17075 /* If we didn't get max_vbases vbases, we must have shared at
17076 least one of them, and are therefore diamond shaped. */
17077 CLASSTYPE_DIAMOND_SHAPED_P (ref) = 1;
17079 /* Unmark all the types. */
17080 for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
17081 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
17082 TYPE_MARKED_P (ref) = 0;
17084 /* Now see if we have a repeated base type. */
17085 if (!CLASSTYPE_REPEATED_BASE_P (ref))
17087 for (base_binfo = binfo; base_binfo;
17088 base_binfo = TREE_CHAIN (base_binfo))
17090 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
17092 CLASSTYPE_REPEATED_BASE_P (ref) = 1;
17093 break;
17095 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 1;
17097 for (base_binfo = binfo; base_binfo;
17098 base_binfo = TREE_CHAIN (base_binfo))
17099 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
17100 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
17101 else
17102 break;
17107 /* Copies the enum-related properties from type SRC to type DST.
17108 Used with the underlying type of an enum and the enum itself. */
17109 static void
17110 copy_type_enum (tree dst, tree src)
17112 tree t;
17113 for (t = dst; t; t = TYPE_NEXT_VARIANT (t))
17115 TYPE_MIN_VALUE (t) = TYPE_MIN_VALUE (src);
17116 TYPE_MAX_VALUE (t) = TYPE_MAX_VALUE (src);
17117 TYPE_SIZE (t) = TYPE_SIZE (src);
17118 TYPE_SIZE_UNIT (t) = TYPE_SIZE_UNIT (src);
17119 SET_TYPE_MODE (dst, TYPE_MODE (src));
17120 TYPE_PRECISION (t) = TYPE_PRECISION (src);
17121 unsigned valign = TYPE_ALIGN (src);
17122 if (TYPE_USER_ALIGN (t))
17123 valign = MAX (valign, TYPE_ALIGN (t));
17124 else
17125 TYPE_USER_ALIGN (t) = TYPE_USER_ALIGN (src);
17126 SET_TYPE_ALIGN (t, valign);
17127 TYPE_UNSIGNED (t) = TYPE_UNSIGNED (src);
17131 /* Begin compiling the definition of an enumeration type.
17132 NAME is its name,
17134 if ENUMTYPE is not NULL_TREE then the type has alredy been found.
17136 UNDERLYING_TYPE is the type that will be used as the storage for
17137 the enumeration type. This should be NULL_TREE if no storage type
17138 was specified.
17140 ATTRIBUTES are any attributes specified after the enum-key.
17142 SCOPED_ENUM_P is true if this is a scoped enumeration type.
17144 if IS_NEW is not NULL, gets TRUE iff a new type is created.
17146 Returns the type object, as yet incomplete.
17147 Also records info about it so that build_enumerator
17148 may be used to declare the individual values as they are read. */
17150 tree
17151 start_enum (tree name, tree enumtype, tree underlying_type,
17152 tree attributes, bool scoped_enum_p, bool *is_new)
17154 tree prevtype = NULL_TREE;
17155 gcc_assert (identifier_p (name));
17157 if (is_new)
17158 *is_new = false;
17159 /* [C++0x dcl.enum]p5:
17161 If not explicitly specified, the underlying type of a scoped
17162 enumeration type is int. */
17163 if (!underlying_type && scoped_enum_p)
17164 underlying_type = integer_type_node;
17166 if (underlying_type)
17167 underlying_type = cv_unqualified (underlying_type);
17169 /* If this is the real definition for a previous forward reference,
17170 fill in the contents in the same object that used to be the
17171 forward reference. */
17172 if (!enumtype)
17173 enumtype = lookup_and_check_tag (enum_type, name,
17174 /*tag_scope=*/TAG_how::CURRENT_ONLY,
17175 /*template_header_p=*/false);
17177 /* In case of a template_decl, the only check that should be deferred
17178 to instantiation time is the comparison of underlying types. */
17179 if (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE)
17181 /* Attempt to set the declaring module. */
17182 if (modules_p ())
17184 tree decl = TYPE_NAME (enumtype);
17185 if (!module_may_redeclare (decl))
17186 enumtype = error_mark_node;
17187 else
17188 set_instantiating_module (decl);
17191 if (enumtype == error_mark_node)
17193 else if (scoped_enum_p != SCOPED_ENUM_P (enumtype))
17195 auto_diagnostic_group d;
17196 error_at (input_location, "scoped/unscoped mismatch "
17197 "in enum %q#T", enumtype);
17198 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
17199 "previous definition here");
17200 enumtype = error_mark_node;
17202 else if (ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) != !! underlying_type)
17204 auto_diagnostic_group d;
17205 error_at (input_location, "underlying type mismatch "
17206 "in enum %q#T", enumtype);
17207 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
17208 "previous definition here");
17209 enumtype = error_mark_node;
17211 else if (underlying_type && ENUM_UNDERLYING_TYPE (enumtype)
17212 && !same_type_p (underlying_type,
17213 ENUM_UNDERLYING_TYPE (enumtype)))
17215 auto_diagnostic_group d;
17216 error_at (input_location, "different underlying type "
17217 "in enum %q#T", enumtype);
17218 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
17219 "previous definition here");
17220 underlying_type = NULL_TREE;
17224 if (!enumtype || TREE_CODE (enumtype) != ENUMERAL_TYPE
17225 || processing_template_decl)
17227 /* In case of error, make a dummy enum to allow parsing to
17228 continue. */
17229 if (enumtype == error_mark_node)
17231 name = make_anon_name ();
17232 enumtype = NULL_TREE;
17235 /* enumtype may be an ENUMERAL_TYPE if this is a redefinition
17236 of an opaque enum, or an opaque enum of an already defined
17237 enumeration (C++11).
17238 In any other case, it'll be NULL_TREE. */
17239 if (!enumtype)
17241 if (is_new)
17242 *is_new = true;
17244 prevtype = enumtype;
17246 /* Do not push the decl more than once. */
17247 if (!enumtype
17248 || TREE_CODE (enumtype) != ENUMERAL_TYPE)
17250 enumtype = cxx_make_type (ENUMERAL_TYPE);
17251 enumtype = pushtag (name, enumtype);
17253 if (enumtype != error_mark_node)
17255 /* The enum is considered opaque until the opening '{' of the
17256 enumerator list. */
17257 SET_OPAQUE_ENUM_P (enumtype, true);
17258 ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) = !! underlying_type;
17260 /* std::byte aliases anything. */
17261 if (TYPE_CONTEXT (enumtype) == std_node
17262 && !strcmp ("byte", TYPE_NAME_STRING (enumtype)))
17263 TYPE_ALIAS_SET (enumtype) = 0;
17266 else
17267 enumtype = xref_tag (enum_type, name);
17269 if (enumtype == error_mark_node)
17270 return error_mark_node;
17273 SET_SCOPED_ENUM_P (enumtype, scoped_enum_p);
17275 cplus_decl_attributes (&enumtype, attributes, (int)ATTR_FLAG_TYPE_IN_PLACE);
17277 if (underlying_type)
17279 if (ENUM_UNDERLYING_TYPE (enumtype))
17280 /* We already checked that it matches, don't change it to a different
17281 typedef variant. */;
17282 else if (CP_INTEGRAL_TYPE_P (underlying_type))
17284 copy_type_enum (enumtype, underlying_type);
17285 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
17287 else if (dependent_type_p (underlying_type))
17288 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
17289 else
17291 error ("underlying type %qT of %qT must be an integral type",
17292 underlying_type, enumtype);
17293 ENUM_UNDERLYING_TYPE (enumtype) = integer_type_node;
17297 /* If into a template class, the returned enum is always the first
17298 declaration (opaque or not) seen. This way all the references to
17299 this type will be to the same declaration. The following ones are used
17300 only to check for definition errors. */
17301 if (prevtype && processing_template_decl)
17302 return prevtype;
17303 else
17304 return enumtype;
17307 /* After processing and defining all the values of an enumeration type,
17308 install their decls in the enumeration type.
17309 ENUMTYPE is the type object. */
17311 void
17312 finish_enum_value_list (tree enumtype)
17314 tree values;
17315 tree underlying_type;
17316 tree decl;
17317 tree value;
17318 tree minnode, maxnode;
17319 tree t;
17321 bool fixed_underlying_type_p
17322 = ENUM_UNDERLYING_TYPE (enumtype) != NULL_TREE;
17324 /* We built up the VALUES in reverse order. */
17325 TYPE_VALUES (enumtype) = nreverse (TYPE_VALUES (enumtype));
17327 /* For an enum defined in a template, just set the type of the values;
17328 all further processing is postponed until the template is
17329 instantiated. We need to set the type so that tsubst of a CONST_DECL
17330 works. */
17331 if (processing_template_decl)
17333 for (values = TYPE_VALUES (enumtype);
17334 values;
17335 values = TREE_CHAIN (values))
17336 TREE_TYPE (TREE_VALUE (values)) = enumtype;
17337 return;
17340 /* Determine the minimum and maximum values of the enumerators. */
17341 if (TYPE_VALUES (enumtype))
17343 minnode = maxnode = NULL_TREE;
17345 for (values = TYPE_VALUES (enumtype);
17346 values;
17347 values = TREE_CHAIN (values))
17349 decl = TREE_VALUE (values);
17351 /* [dcl.enum]: Following the closing brace of an enum-specifier,
17352 each enumerator has the type of its enumeration. Prior to the
17353 closing brace, the type of each enumerator is the type of its
17354 initializing value. */
17355 TREE_TYPE (decl) = enumtype;
17357 /* Update the minimum and maximum values, if appropriate. */
17358 value = DECL_INITIAL (decl);
17359 if (TREE_CODE (value) != INTEGER_CST)
17360 value = integer_zero_node;
17361 /* Figure out what the minimum and maximum values of the
17362 enumerators are. */
17363 if (!minnode)
17364 minnode = maxnode = value;
17365 else if (tree_int_cst_lt (maxnode, value))
17366 maxnode = value;
17367 else if (tree_int_cst_lt (value, minnode))
17368 minnode = value;
17371 else
17372 /* [dcl.enum]
17374 If the enumerator-list is empty, the underlying type is as if
17375 the enumeration had a single enumerator with value 0. */
17376 minnode = maxnode = integer_zero_node;
17378 if (!fixed_underlying_type_p)
17380 /* Compute the number of bits require to represent all values of the
17381 enumeration. We must do this before the type of MINNODE and
17382 MAXNODE are transformed, since tree_int_cst_min_precision relies
17383 on the TREE_TYPE of the value it is passed. */
17384 signop sgn = tree_int_cst_sgn (minnode) >= 0 ? UNSIGNED : SIGNED;
17385 int lowprec = tree_int_cst_min_precision (minnode, sgn);
17386 int highprec = tree_int_cst_min_precision (maxnode, sgn);
17387 int precision = MAX (lowprec, highprec);
17388 unsigned int itk;
17389 bool use_short_enum;
17391 /* Determine the underlying type of the enumeration.
17393 [dcl.enum]
17395 The underlying type of an enumeration is an integral type that
17396 can represent all the enumerator values defined in the
17397 enumeration. It is implementation-defined which integral type is
17398 used as the underlying type for an enumeration except that the
17399 underlying type shall not be larger than int unless the value of
17400 an enumerator cannot fit in an int or unsigned int.
17402 We use "int" or an "unsigned int" as the underlying type, even if
17403 a smaller integral type would work, unless the user has
17404 explicitly requested that we use the smallest possible type. The
17405 user can request that for all enumerations with a command line
17406 flag, or for just one enumeration with an attribute. */
17408 use_short_enum = flag_short_enums
17409 || lookup_attribute ("packed", TYPE_ATTRIBUTES (enumtype));
17411 /* If the precision of the type was specified with an attribute and it
17412 was too small, give an error. Otherwise, use it. */
17413 if (TYPE_PRECISION (enumtype))
17415 if (precision > TYPE_PRECISION (enumtype))
17416 error ("specified mode too small for enumerated values");
17417 else
17419 use_short_enum = true;
17420 precision = TYPE_PRECISION (enumtype);
17424 for (itk = (use_short_enum ? itk_char : itk_int);
17425 itk != itk_none;
17426 itk++)
17428 underlying_type = integer_types[itk];
17429 if (underlying_type != NULL_TREE
17430 && TYPE_PRECISION (underlying_type) >= precision
17431 && TYPE_SIGN (underlying_type) == sgn)
17432 break;
17434 if (itk == itk_none)
17436 /* DR 377
17438 IF no integral type can represent all the enumerator values, the
17439 enumeration is ill-formed. */
17440 error ("no integral type can represent all of the enumerator values "
17441 "for %qT", enumtype);
17442 precision = TYPE_PRECISION (long_long_integer_type_node);
17443 underlying_type = integer_types[itk_unsigned_long_long];
17446 /* [dcl.enum]
17448 The value of sizeof() applied to an enumeration type, an object
17449 of an enumeration type, or an enumerator, is the value of sizeof()
17450 applied to the underlying type. */
17451 copy_type_enum (enumtype, underlying_type);
17453 /* Compute the minimum and maximum values for the type.
17455 [dcl.enum]
17457 For an enumeration where emin is the smallest enumerator and emax
17458 is the largest, the values of the enumeration are the values of the
17459 underlying type in the range bmin to bmax, where bmin and bmax are,
17460 respectively, the smallest and largest values of the smallest bit-
17461 field that can store emin and emax. */
17463 /* The middle-end currently assumes that types with TYPE_PRECISION
17464 narrower than their underlying type are suitably zero or sign
17465 extended to fill their mode. Similarly, it assumes that the front
17466 end assures that a value of a particular type must be within
17467 TYPE_MIN_VALUE and TYPE_MAX_VALUE.
17469 We used to set these fields based on bmin and bmax, but that led
17470 to invalid assumptions like optimizing away bounds checking. So
17471 now we just set the TYPE_PRECISION, TYPE_MIN_VALUE, and
17472 TYPE_MAX_VALUE to the values for the mode above and only restrict
17473 the ENUM_UNDERLYING_TYPE for the benefit of diagnostics. */
17474 ENUM_UNDERLYING_TYPE (enumtype)
17475 = build_distinct_type_copy (underlying_type);
17476 TYPE_PRECISION (ENUM_UNDERLYING_TYPE (enumtype)) = precision;
17477 set_min_and_max_values_for_integral_type
17478 (ENUM_UNDERLYING_TYPE (enumtype), precision, sgn);
17480 /* If -fstrict-enums, still constrain TYPE_MIN/MAX_VALUE. */
17481 if (flag_strict_enums)
17482 set_min_and_max_values_for_integral_type (enumtype, precision, sgn);
17484 if (use_short_enum)
17486 TYPE_PACKED (enumtype) = use_short_enum;
17487 fixup_attribute_variants (enumtype);
17490 else
17491 underlying_type = ENUM_UNDERLYING_TYPE (enumtype);
17493 /* If the enum is exported, mark the consts too. */
17494 bool export_p = (UNSCOPED_ENUM_P (enumtype)
17495 && DECL_MODULE_EXPORT_P (TYPE_STUB_DECL (enumtype))
17496 && at_namespace_scope_p ());
17498 /* Convert each of the enumerators to the type of the underlying
17499 type of the enumeration. */
17500 for (values = TYPE_VALUES (enumtype); values; values = TREE_CHAIN (values))
17502 decl = TREE_VALUE (values);
17503 iloc_sentinel ils (DECL_SOURCE_LOCATION (decl));
17504 if (fixed_underlying_type_p)
17505 /* If the enumeration type has a fixed underlying type, we
17506 already checked all of the enumerator values. */
17507 value = DECL_INITIAL (decl);
17508 else
17509 value = perform_implicit_conversion (underlying_type,
17510 DECL_INITIAL (decl),
17511 tf_warning_or_error);
17512 /* Do not clobber shared ints. */
17513 if (value != error_mark_node)
17515 value = copy_node (value);
17517 TREE_TYPE (value) = enumtype;
17519 DECL_INITIAL (decl) = value;
17520 if (export_p)
17521 DECL_MODULE_EXPORT_P (decl) = true;
17524 /* Fix up all variant types of this enum type. */
17525 for (t = TYPE_MAIN_VARIANT (enumtype); t; t = TYPE_NEXT_VARIANT (t))
17526 TYPE_VALUES (t) = TYPE_VALUES (enumtype);
17528 if (at_class_scope_p ()
17529 && COMPLETE_TYPE_P (current_class_type)
17530 && UNSCOPED_ENUM_P (enumtype))
17532 insert_late_enum_def_bindings (current_class_type, enumtype);
17533 /* TYPE_FIELDS needs fixup. */
17534 fixup_type_variants (current_class_type);
17537 /* Finish debugging output for this type. */
17538 rest_of_type_compilation (enumtype, namespace_bindings_p ());
17540 /* Each enumerator now has the type of its enumeration. Clear the cache
17541 so that this change in types doesn't confuse us later on. */
17542 clear_cv_and_fold_caches ();
17545 /* Finishes the enum type. This is called only the first time an
17546 enumeration is seen, be it opaque or odinary.
17547 ENUMTYPE is the type object. */
17549 void
17550 finish_enum (tree enumtype)
17552 if (processing_template_decl)
17554 if (at_function_scope_p ())
17555 add_stmt (build_min (TAG_DEFN, enumtype));
17556 return;
17559 /* If this is a forward declaration, there should not be any variants,
17560 though we can get a variant in the middle of an enum-specifier with
17561 wacky code like 'enum E { e = sizeof(const E*) };' */
17562 gcc_assert (enumtype == TYPE_MAIN_VARIANT (enumtype)
17563 && (TYPE_VALUES (enumtype)
17564 || !TYPE_NEXT_VARIANT (enumtype)));
17567 /* Build and install a CONST_DECL for an enumeration constant of the
17568 enumeration type ENUMTYPE whose NAME and VALUE (if any) are provided.
17569 Apply ATTRIBUTES if available. LOC is the location of NAME.
17570 Assignment of sequential values by default is handled here. */
17572 tree
17573 build_enumerator (tree name, tree value, tree enumtype, tree attributes,
17574 location_t loc)
17576 tree decl;
17577 tree context;
17578 tree type;
17580 /* scalar_constant_value will pull out this expression, so make sure
17581 it's folded as appropriate.
17583 Creating a TARGET_EXPR in a template breaks when substituting, and
17584 here we would create it for instance when using a class prvalue with
17585 a user-defined conversion function. So don't use such a tree. We
17586 instantiate VALUE here to get errors about bad enumerators even in
17587 a template that does not get instantiated. */
17588 if (processing_template_decl)
17589 value = maybe_fold_non_dependent_expr (value);
17591 /* If the VALUE was erroneous, pretend it wasn't there; that will
17592 result in the enum being assigned the next value in sequence. */
17593 if (value == error_mark_node)
17594 value = NULL_TREE;
17596 /* Remove no-op casts from the value. */
17597 if (value)
17598 STRIP_TYPE_NOPS (value);
17600 if (! processing_template_decl)
17602 /* Validate and default VALUE. */
17603 if (value != NULL_TREE)
17605 if (!ENUM_UNDERLYING_TYPE (enumtype))
17607 tree tmp_value = build_expr_type_conversion (WANT_INT | WANT_ENUM,
17608 value, true);
17609 if (tmp_value)
17610 value = tmp_value;
17612 else if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
17613 (TREE_TYPE (value)))
17614 value = perform_implicit_conversion_flags
17615 (ENUM_UNDERLYING_TYPE (enumtype), value, tf_warning_or_error,
17616 LOOKUP_IMPLICIT | LOOKUP_NO_NARROWING);
17618 if (value == error_mark_node)
17619 value = NULL_TREE;
17621 if (value != NULL_TREE)
17623 if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
17624 (TREE_TYPE (value)))
17626 error_at (cp_expr_loc_or_input_loc (value),
17627 "enumerator value for %qD must have integral or "
17628 "unscoped enumeration type", name);
17629 value = NULL_TREE;
17631 else
17633 value = cxx_constant_value (value);
17635 if (TREE_CODE (value) != INTEGER_CST)
17637 error ("enumerator value for %qD is not an integer "
17638 "constant", name);
17639 value = NULL_TREE;
17645 /* Default based on previous value. */
17646 if (value == NULL_TREE)
17648 if (TYPE_VALUES (enumtype))
17650 tree prev_value;
17652 /* C++03 7.2/4: If no initializer is specified for the first
17653 enumerator, the type is an unspecified integral
17654 type. Otherwise the type is the same as the type of the
17655 initializing value of the preceding enumerator unless the
17656 incremented value is not representable in that type, in
17657 which case the type is an unspecified integral type
17658 sufficient to contain the incremented value. */
17659 prev_value = DECL_INITIAL (TREE_VALUE (TYPE_VALUES (enumtype)));
17660 if (TREE_CODE (prev_value) != INTEGER_CST)
17661 value = error_mark_node;
17662 else
17664 wi::overflow_type overflowed;
17665 tree type = TREE_TYPE (prev_value);
17666 signop sgn = TYPE_SIGN (type);
17667 widest_int wi = wi::add (wi::to_widest (prev_value), 1, sgn,
17668 &overflowed);
17669 if (!overflowed)
17671 bool pos = !wi::neg_p (wi, sgn);
17672 if (!wi::fits_to_tree_p (wi, type))
17674 unsigned int itk;
17675 for (itk = itk_int; itk != itk_none; itk++)
17677 type = integer_types[itk];
17678 if (type != NULL_TREE
17679 && (pos || !TYPE_UNSIGNED (type))
17680 && wi::fits_to_tree_p (wi, type))
17681 break;
17683 if (type && cxx_dialect < cxx11
17684 && itk > itk_unsigned_long)
17685 pedwarn (input_location, OPT_Wlong_long,
17686 pos ? G_("\
17687 incremented enumerator value is too large for %<unsigned long%>") : G_("\
17688 incremented enumerator value is too large for %<long%>"));
17690 if (type == NULL_TREE)
17691 overflowed = wi::OVF_UNKNOWN;
17692 else
17693 value = wide_int_to_tree (type, wi);
17696 if (overflowed)
17698 error ("overflow in enumeration values at %qD", name);
17699 value = error_mark_node;
17703 else
17704 value = integer_zero_node;
17707 /* Remove no-op casts from the value. */
17708 STRIP_TYPE_NOPS (value);
17710 /* If the underlying type of the enum is fixed, check whether
17711 the enumerator values fits in the underlying type. If it
17712 does not fit, the program is ill-formed [C++0x dcl.enum]. */
17713 if (ENUM_UNDERLYING_TYPE (enumtype)
17714 && value
17715 && TREE_CODE (value) == INTEGER_CST)
17717 if (!int_fits_type_p (value, ENUM_UNDERLYING_TYPE (enumtype)))
17718 error ("enumerator value %qE is outside the range of underlying "
17719 "type %qT", value, ENUM_UNDERLYING_TYPE (enumtype));
17721 /* Convert the value to the appropriate type. */
17722 value = fold_convert (ENUM_UNDERLYING_TYPE (enumtype), value);
17726 /* C++ associates enums with global, function, or class declarations. */
17727 context = current_scope ();
17729 /* Build the actual enumeration constant. Note that the enumeration
17730 constants have the underlying type of the enum (if it is fixed)
17731 or the type of their initializer (if the underlying type of the
17732 enum is not fixed):
17734 [ C++0x dcl.enum ]
17736 If the underlying type is fixed, the type of each enumerator
17737 prior to the closing brace is the underlying type; if the
17738 initializing value of an enumerator cannot be represented by
17739 the underlying type, the program is ill-formed. If the
17740 underlying type is not fixed, the type of each enumerator is
17741 the type of its initializing value.
17743 If the underlying type is not fixed, it will be computed by
17744 finish_enum and we will reset the type of this enumerator. Of
17745 course, if we're processing a template, there may be no value. */
17746 type = value ? TREE_TYPE (value) : NULL_TREE;
17748 decl = build_decl (loc, CONST_DECL, name, type);
17750 DECL_CONTEXT (decl) = enumtype;
17751 TREE_CONSTANT (decl) = 1;
17752 TREE_READONLY (decl) = 1;
17753 DECL_INITIAL (decl) = value;
17755 if (attributes)
17756 cplus_decl_attributes (&decl, attributes, 0);
17758 if (context && context == current_class_type && !SCOPED_ENUM_P (enumtype))
17760 /* In something like `struct S { enum E { i = 7 }; };' we put `i'
17761 on the TYPE_FIELDS list for `S'. (That's so that you can say
17762 things like `S::i' later.) */
17764 /* The enumerator may be getting declared outside of its enclosing
17765 class, like so:
17767 class S { public: enum E : int; }; enum S::E : int { i = 7; };
17769 For which case we need to make sure that the access of `S::i'
17770 matches the access of `S::E'. */
17771 auto cas = make_temp_override (current_access_specifier);
17772 set_current_access_from_decl (TYPE_NAME (enumtype));
17773 finish_member_declaration (decl);
17775 else
17776 pushdecl (decl);
17778 /* Add this enumeration constant to the list for this type. */
17779 TYPE_VALUES (enumtype) = tree_cons (name, decl, TYPE_VALUES (enumtype));
17781 return decl;
17784 /* Look for an enumerator with the given NAME within the enumeration
17785 type ENUMTYPE. This routine is used primarily for qualified name
17786 lookup into an enumerator in C++0x, e.g.,
17788 enum class Color { Red, Green, Blue };
17790 Color color = Color::Red;
17792 Returns the value corresponding to the enumerator, or
17793 NULL_TREE if no such enumerator was found. */
17794 tree
17795 lookup_enumerator (tree enumtype, tree name)
17797 tree e;
17798 gcc_assert (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE);
17800 e = purpose_member (name, TYPE_VALUES (enumtype));
17801 return e? TREE_VALUE (e) : NULL_TREE;
17804 /* Implement LANG_HOOKS_SIMULATE_ENUM_DECL. */
17806 tree
17807 cxx_simulate_enum_decl (location_t loc, const char *name,
17808 vec<string_int_pair> *values)
17810 location_t saved_loc = input_location;
17811 input_location = loc;
17813 tree enumtype = start_enum (get_identifier (name), NULL_TREE, NULL_TREE,
17814 NULL_TREE, false, NULL);
17815 if (!OPAQUE_ENUM_P (enumtype))
17817 auto_diagnostic_group d;
17818 error_at (loc, "multiple definition of %q#T", enumtype);
17819 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
17820 "previous definition here");
17821 return enumtype;
17823 SET_OPAQUE_ENUM_P (enumtype, false);
17824 DECL_SOURCE_LOCATION (TYPE_NAME (enumtype)) = loc;
17826 for (const string_int_pair &value : values)
17827 build_enumerator (get_identifier (value.first),
17828 build_int_cst (integer_type_node, value.second),
17829 enumtype, NULL_TREE, loc);
17831 finish_enum_value_list (enumtype);
17832 finish_enum (enumtype);
17834 input_location = saved_loc;
17835 return enumtype;
17838 /* Implement LANG_HOOKS_SIMULATE_RECORD_DECL. */
17840 tree
17841 cxx_simulate_record_decl (location_t loc, const char *name,
17842 array_slice<const tree> fields)
17844 iloc_sentinel ils (loc);
17846 tree ident = get_identifier (name);
17847 tree type = xref_tag (/*tag_code=*/record_type, ident);
17848 if (type != error_mark_node
17849 && (TREE_CODE (type) != RECORD_TYPE || COMPLETE_TYPE_P (type)))
17851 error ("redefinition of %q#T", type);
17852 type = error_mark_node;
17854 if (type == error_mark_node)
17855 return lhd_simulate_record_decl (loc, name, fields);
17857 xref_basetypes (type, NULL_TREE);
17858 type = begin_class_definition (type);
17859 if (type == error_mark_node)
17860 return lhd_simulate_record_decl (loc, name, fields);
17862 for (tree field : fields)
17863 finish_member_declaration (field);
17865 type = finish_struct (type, NULL_TREE);
17867 tree decl = build_decl (loc, TYPE_DECL, ident, type);
17868 set_underlying_type (decl);
17869 lang_hooks.decls.pushdecl (decl);
17871 return type;
17874 /* We're defining DECL. Make sure that its type is OK. */
17876 static void
17877 check_function_type (tree decl, tree current_function_parms)
17879 tree fntype = TREE_TYPE (decl);
17880 tree return_type = complete_type (TREE_TYPE (fntype));
17882 /* In a function definition, arg types must be complete. */
17883 require_complete_types_for_parms (current_function_parms);
17885 if (dependent_type_p (return_type)
17886 || type_uses_auto (return_type))
17887 return;
17888 if (!COMPLETE_OR_VOID_TYPE_P (return_type))
17890 tree args = TYPE_ARG_TYPES (fntype);
17892 error ("return type %q#T is incomplete", return_type);
17894 /* Make it return void instead. */
17895 if (TREE_CODE (fntype) == METHOD_TYPE)
17896 fntype = build_method_type_directly (TREE_TYPE (TREE_VALUE (args)),
17897 void_type_node,
17898 TREE_CHAIN (args));
17899 else
17900 fntype = build_function_type (void_type_node, args);
17901 fntype = (cp_build_type_attribute_variant
17902 (fntype, TYPE_ATTRIBUTES (TREE_TYPE (decl))));
17903 fntype = cxx_copy_lang_qualifiers (fntype, TREE_TYPE (decl));
17904 TREE_TYPE (decl) = fntype;
17906 else
17908 abstract_virtuals_error (decl, TREE_TYPE (fntype));
17909 maybe_warn_parm_abi (TREE_TYPE (fntype),
17910 DECL_SOURCE_LOCATION (decl));
17914 /* True iff FN is an implicitly-defined default constructor. */
17916 static bool
17917 implicit_default_ctor_p (tree fn)
17919 return (DECL_CONSTRUCTOR_P (fn)
17920 && !user_provided_p (fn)
17921 && sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (fn)));
17924 /* Clobber the contents of *this to let the back end know that the object
17925 storage is dead when we enter the constructor or leave the destructor. */
17927 static tree
17928 build_clobber_this (clobber_kind kind)
17930 /* Clobbering an empty base is pointless, and harmful if its one byte
17931 TYPE_SIZE overlays real data. */
17932 if (is_empty_class (current_class_type))
17933 return void_node;
17935 /* If we have virtual bases, clobber the whole object, but only if we're in
17936 charge. If we don't have virtual bases, clobber the as-base type so we
17937 don't mess with tail padding. */
17938 bool vbases = CLASSTYPE_VBASECLASSES (current_class_type);
17940 tree ctype = current_class_type;
17941 if (!vbases)
17942 ctype = CLASSTYPE_AS_BASE (ctype);
17944 tree clobber = build_clobber (ctype, kind);
17946 tree thisref = current_class_ref;
17947 if (ctype != current_class_type)
17949 thisref = build_nop (build_reference_type (ctype), current_class_ptr);
17950 thisref = convert_from_reference (thisref);
17953 tree exprstmt = build2 (MODIFY_EXPR, void_type_node, thisref, clobber);
17954 if (vbases)
17955 exprstmt = build_if_in_charge (exprstmt);
17957 return exprstmt;
17960 /* Create the FUNCTION_DECL for a function definition.
17961 DECLSPECS and DECLARATOR are the parts of the declaration;
17962 they describe the function's name and the type it returns,
17963 but twisted together in a fashion that parallels the syntax of C.
17965 FLAGS is a bitwise or of SF_PRE_PARSED (indicating that the
17966 DECLARATOR is really the DECL for the function we are about to
17967 process and that DECLSPECS should be ignored), SF_INCLASS_INLINE
17968 indicating that the function is an inline defined in-class.
17970 This function creates a binding context for the function body
17971 as well as setting up the FUNCTION_DECL in current_function_decl.
17973 For C++, we must first check whether that datum makes any sense.
17974 For example, "class A local_a(1,2);" means that variable local_a
17975 is an aggregate of type A, which should have a constructor
17976 applied to it with the argument list [1, 2].
17978 On entry, DECL_INITIAL (decl1) should be NULL_TREE or error_mark_node,
17979 or may be a BLOCK if the function has been defined previously
17980 in this translation unit. On exit, DECL_INITIAL (decl1) will be
17981 error_mark_node if the function has never been defined, or
17982 a BLOCK if the function has been defined somewhere. */
17984 bool
17985 start_preparsed_function (tree decl1, tree attrs, int flags)
17987 tree ctype = NULL_TREE;
17988 bool doing_friend = false;
17990 /* Sanity check. */
17991 gcc_assert (VOID_TYPE_P (TREE_VALUE (void_list_node)));
17992 gcc_assert (TREE_CHAIN (void_list_node) == NULL_TREE);
17994 tree fntype = TREE_TYPE (decl1);
17995 if (DECL_CLASS_SCOPE_P (decl1))
17996 ctype = DECL_CONTEXT (decl1);
17997 else
17999 ctype = DECL_FRIEND_CONTEXT (decl1);
18001 if (ctype)
18002 doing_friend = true;
18005 /* Adjust for #pragma target/optimize if this is an artificial function that
18006 (probably) didn't go through grokfndecl. We particularly don't want this
18007 for deferred instantiations, which should match their template. */
18008 if (DECL_ARTIFICIAL (decl1))
18009 decl_attributes (&decl1, NULL_TREE, 0);
18011 if (DECL_DECLARED_INLINE_P (decl1)
18012 && lookup_attribute ("noinline", attrs))
18013 warning_at (DECL_SOURCE_LOCATION (decl1), 0,
18014 "inline function %qD given attribute %qs", decl1, "noinline");
18016 /* Handle gnu_inline attribute. */
18017 if (GNU_INLINE_P (decl1))
18019 DECL_EXTERNAL (decl1) = 1;
18020 DECL_NOT_REALLY_EXTERN (decl1) = 0;
18021 DECL_INTERFACE_KNOWN (decl1) = 1;
18022 DECL_DISREGARD_INLINE_LIMITS (decl1) = 1;
18025 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl1))
18026 /* This is a constructor, we must ensure that any default args
18027 introduced by this definition are propagated to the clones
18028 now. The clones are used directly in overload resolution. */
18029 adjust_clone_args (decl1);
18031 /* Sometimes we don't notice that a function is a static member, and
18032 build a METHOD_TYPE for it. Fix that up now. */
18033 gcc_assert (!(DECL_STATIC_FUNCTION_P (decl1)
18034 && TREE_CODE (TREE_TYPE (decl1)) == METHOD_TYPE));
18036 /* Set up current_class_type, and enter the scope of the class, if
18037 appropriate. */
18038 if (ctype)
18039 push_nested_class (ctype);
18041 /* Now that we have entered the scope of the class, we must restore
18042 the bindings for any template parameters surrounding DECL1, if it
18043 is an inline member template. (Order is important; consider the
18044 case where a template parameter has the same name as a field of
18045 the class.) It is not until after this point that
18046 PROCESSING_TEMPLATE_DECL is guaranteed to be set up correctly. */
18047 if (flags & SF_INCLASS_INLINE)
18048 maybe_begin_member_template_processing (decl1);
18050 /* Effective C++ rule 15. */
18051 if (warn_ecpp
18052 && DECL_ASSIGNMENT_OPERATOR_P (decl1)
18053 && DECL_OVERLOADED_OPERATOR_IS (decl1, NOP_EXPR)
18054 && VOID_TYPE_P (TREE_TYPE (fntype)))
18055 warning (OPT_Weffc__,
18056 "%<operator=%> should return a reference to %<*this%>");
18058 /* Make the init_value nonzero so pushdecl knows this is not tentative.
18059 error_mark_node is replaced below (in poplevel) with the BLOCK. */
18060 if (!DECL_INITIAL (decl1))
18061 DECL_INITIAL (decl1) = error_mark_node;
18063 /* This function exists in static storage.
18064 (This does not mean `static' in the C sense!) */
18065 TREE_STATIC (decl1) = 1;
18067 /* We must call push_template_decl after current_class_type is set
18068 up. (If we are processing inline definitions after exiting a
18069 class scope, current_class_type will be NULL_TREE until set above
18070 by push_nested_class.) */
18071 if (processing_template_decl)
18073 tree newdecl1 = push_template_decl (decl1, doing_friend);
18074 if (newdecl1 == error_mark_node)
18076 if (ctype)
18077 pop_nested_class ();
18078 return false;
18080 decl1 = newdecl1;
18083 /* Make sure the parameter and return types are reasonable. When
18084 you declare a function, these types can be incomplete, but they
18085 must be complete when you define the function. */
18086 check_function_type (decl1, DECL_ARGUMENTS (decl1));
18088 /* Build the return declaration for the function. */
18089 tree restype = TREE_TYPE (fntype);
18091 if (DECL_RESULT (decl1) == NULL_TREE)
18093 /* In a template instantiation, copy the return type location. When
18094 parsing, the location will be set in grokdeclarator. */
18095 location_t loc = input_location;
18096 if (DECL_TEMPLATE_INSTANTIATION (decl1))
18098 tree tmpl = template_for_substitution (decl1);
18099 if (tree res = DECL_RESULT (DECL_TEMPLATE_RESULT (tmpl)))
18100 loc = DECL_SOURCE_LOCATION (res);
18103 tree resdecl = build_decl (loc, RESULT_DECL, 0, restype);
18104 DECL_ARTIFICIAL (resdecl) = 1;
18105 DECL_IGNORED_P (resdecl) = 1;
18106 DECL_RESULT (decl1) = resdecl;
18108 cp_apply_type_quals_to_decl (cp_type_quals (restype), resdecl);
18111 /* Record the decl so that the function name is defined.
18112 If we already have a decl for this name, and it is a FUNCTION_DECL,
18113 use the old decl. */
18114 if (!processing_template_decl && !(flags & SF_PRE_PARSED))
18116 /* A specialization is not used to guide overload resolution. */
18117 if (!DECL_FUNCTION_MEMBER_P (decl1)
18118 && !(DECL_USE_TEMPLATE (decl1) &&
18119 PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl1))))
18121 tree olddecl = pushdecl (decl1);
18123 if (olddecl == error_mark_node)
18124 /* If something went wrong when registering the declaration,
18125 use DECL1; we have to have a FUNCTION_DECL to use when
18126 parsing the body of the function. */
18128 else
18130 /* Otherwise, OLDDECL is either a previous declaration
18131 of the same function or DECL1 itself. */
18133 if (warn_missing_declarations
18134 && olddecl == decl1
18135 && !DECL_MAIN_P (decl1)
18136 && TREE_PUBLIC (decl1)
18137 && !DECL_DECLARED_INLINE_P (decl1))
18139 tree context;
18141 /* Check whether DECL1 is in an anonymous
18142 namespace. */
18143 for (context = DECL_CONTEXT (decl1);
18144 context;
18145 context = DECL_CONTEXT (context))
18147 if (TREE_CODE (context) == NAMESPACE_DECL
18148 && DECL_NAME (context) == NULL_TREE)
18149 break;
18152 if (context == NULL)
18153 warning_at (DECL_SOURCE_LOCATION (decl1),
18154 OPT_Wmissing_declarations,
18155 "no previous declaration for %qD", decl1);
18158 decl1 = olddecl;
18161 else
18163 /* We need to set the DECL_CONTEXT. */
18164 if (!DECL_CONTEXT (decl1) && DECL_TEMPLATE_INFO (decl1))
18165 DECL_CONTEXT (decl1) = DECL_CONTEXT (DECL_TI_TEMPLATE (decl1));
18167 fntype = TREE_TYPE (decl1);
18168 restype = TREE_TYPE (fntype);
18170 /* If #pragma weak applies, mark the decl appropriately now.
18171 The pragma only applies to global functions. Because
18172 determining whether or not the #pragma applies involves
18173 computing the mangled name for the declaration, we cannot
18174 apply the pragma until after we have merged this declaration
18175 with any previous declarations; if the original declaration
18176 has a linkage specification, that specification applies to
18177 the definition as well, and may affect the mangled name. */
18178 if (DECL_FILE_SCOPE_P (decl1))
18179 maybe_apply_pragma_weak (decl1);
18182 /* We are now in the scope of the function being defined. */
18183 current_function_decl = decl1;
18185 /* Save the parm names or decls from this function's declarator
18186 where store_parm_decls will find them. */
18187 tree current_function_parms = DECL_ARGUMENTS (decl1);
18189 /* Let the user know we're compiling this function. */
18190 announce_function (decl1);
18192 gcc_assert (DECL_INITIAL (decl1));
18194 /* This function may already have been parsed, in which case just
18195 return; our caller will skip over the body without parsing. */
18196 if (DECL_INITIAL (decl1) != error_mark_node)
18197 return true;
18199 /* Initialize RTL machinery. We cannot do this until
18200 CURRENT_FUNCTION_DECL and DECL_RESULT are set up. We do this
18201 even when processing a template; this is how we get
18202 CFUN set up, and our per-function variables initialized.
18203 FIXME factor out the non-RTL stuff. */
18204 cp_binding_level *bl = current_binding_level;
18205 allocate_struct_function (decl1, processing_template_decl);
18207 /* Initialize the language data structures. Whenever we start
18208 a new function, we destroy temporaries in the usual way. */
18209 cfun->language = ggc_cleared_alloc<language_function> ();
18210 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
18211 current_binding_level = bl;
18213 /* If we are (erroneously) defining a function that we have already
18214 defined before, wipe out what we knew before. */
18215 gcc_checking_assert (!DECL_PENDING_INLINE_P (decl1));
18216 FNDECL_USED_AUTO (decl1) = false;
18217 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = NULL;
18219 if (!processing_template_decl && type_uses_auto (restype))
18221 FNDECL_USED_AUTO (decl1) = true;
18222 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = restype;
18225 /* Start the statement-tree, start the tree now. */
18226 DECL_SAVED_TREE (decl1) = push_stmt_list ();
18228 if (DECL_IOBJ_MEMBER_FUNCTION_P (decl1))
18230 /* We know that this was set up by `grokclassfn'. We do not
18231 wait until `store_parm_decls', since evil parse errors may
18232 never get us to that point. Here we keep the consistency
18233 between `current_class_type' and `current_class_ptr'. */
18234 tree t = DECL_ARGUMENTS (decl1);
18236 gcc_assert (t != NULL_TREE && TREE_CODE (t) == PARM_DECL);
18237 gcc_assert (TYPE_PTR_P (TREE_TYPE (t)));
18239 cp_function_chain->x_current_class_ref
18240 = cp_build_fold_indirect_ref (t);
18241 /* Set this second to avoid shortcut in cp_build_indirect_ref. */
18242 cp_function_chain->x_current_class_ptr = t;
18244 /* Constructors and destructors need to know whether they're "in
18245 charge" of initializing virtual base classes. */
18246 t = DECL_CHAIN (t);
18247 if (DECL_HAS_IN_CHARGE_PARM_P (decl1))
18249 current_in_charge_parm = t;
18250 t = DECL_CHAIN (t);
18252 if (DECL_HAS_VTT_PARM_P (decl1))
18254 gcc_assert (DECL_NAME (t) == vtt_parm_identifier);
18255 current_vtt_parm = t;
18259 bool honor_interface = (!DECL_TEMPLATE_INSTANTIATION (decl1)
18260 /* Implicitly-defined methods (like the
18261 destructor for a class in which no destructor
18262 is explicitly declared) must not be defined
18263 until their definition is needed. So, we
18264 ignore interface specifications for
18265 compiler-generated functions. */
18266 && !DECL_ARTIFICIAL (decl1));
18267 struct c_fileinfo *finfo
18268 = get_fileinfo (LOCATION_FILE (DECL_SOURCE_LOCATION (decl1)));
18270 if (processing_template_decl)
18271 /* Don't mess with interface flags. */;
18272 else if (DECL_INTERFACE_KNOWN (decl1))
18274 tree ctx = decl_function_context (decl1);
18276 if (DECL_NOT_REALLY_EXTERN (decl1))
18277 DECL_EXTERNAL (decl1) = 0;
18279 if (ctx != NULL_TREE && vague_linkage_p (ctx))
18280 /* This is a function in a local class in an extern inline
18281 or template function. */
18282 comdat_linkage (decl1);
18284 /* If this function belongs to an interface, it is public.
18285 If it belongs to someone else's interface, it is also external.
18286 This only affects inlines and template instantiations. */
18287 else if (!finfo->interface_unknown && honor_interface)
18289 if (DECL_DECLARED_INLINE_P (decl1)
18290 || DECL_TEMPLATE_INSTANTIATION (decl1))
18292 DECL_EXTERNAL (decl1)
18293 = (finfo->interface_only
18294 || (DECL_DECLARED_INLINE_P (decl1)
18295 && ! flag_implement_inlines
18296 && !DECL_VINDEX (decl1)));
18298 /* For WIN32 we also want to put these in linkonce sections. */
18299 maybe_make_one_only (decl1);
18301 else
18302 DECL_EXTERNAL (decl1) = 0;
18303 DECL_INTERFACE_KNOWN (decl1) = 1;
18304 /* If this function is in an interface implemented in this file,
18305 make sure that the back end knows to emit this function
18306 here. */
18307 if (!DECL_EXTERNAL (decl1))
18308 mark_needed (decl1);
18310 else if (finfo->interface_unknown && finfo->interface_only
18311 && honor_interface)
18313 /* If MULTIPLE_SYMBOL_SPACES is defined and we saw a #pragma
18314 interface, we will have both finfo->interface_unknown and
18315 finfo->interface_only set. In that case, we don't want to
18316 use the normal heuristics because someone will supply a
18317 #pragma implementation elsewhere, and deducing it here would
18318 produce a conflict. */
18319 comdat_linkage (decl1);
18320 DECL_EXTERNAL (decl1) = 0;
18321 DECL_INTERFACE_KNOWN (decl1) = 1;
18322 DECL_DEFER_OUTPUT (decl1) = 1;
18324 else
18326 /* This is a definition, not a reference.
18327 So clear DECL_EXTERNAL, unless this is a GNU extern inline. */
18328 if (!GNU_INLINE_P (decl1))
18329 DECL_EXTERNAL (decl1) = 0;
18331 if ((DECL_DECLARED_INLINE_P (decl1)
18332 || DECL_TEMPLATE_INSTANTIATION (decl1))
18333 && ! DECL_INTERFACE_KNOWN (decl1))
18334 DECL_DEFER_OUTPUT (decl1) = 1;
18335 else
18336 DECL_INTERFACE_KNOWN (decl1) = 1;
18339 /* Determine the ELF visibility attribute for the function. We must not
18340 do this before calling "pushdecl", as we must allow "duplicate_decls"
18341 to merge any attributes appropriately. We also need to wait until
18342 linkage is set. */
18343 if (!DECL_CLONED_FUNCTION_P (decl1))
18344 determine_visibility (decl1);
18346 if (!processing_template_decl)
18347 maybe_instantiate_noexcept (decl1);
18349 begin_scope (sk_function_parms, decl1);
18351 ++function_depth;
18353 start_fname_decls ();
18355 store_parm_decls (current_function_parms);
18357 start_function_contracts (decl1);
18359 if (!processing_template_decl
18360 && (flag_lifetime_dse > 1)
18361 && DECL_CONSTRUCTOR_P (decl1)
18362 && !DECL_CLONED_FUNCTION_P (decl1)
18363 /* Clobbering an empty base is harmful if it overlays real data. */
18364 && !is_empty_class (current_class_type)
18365 /* We can't clobber safely for an implicitly-defined default constructor
18366 because part of the initialization might happen before we enter the
18367 constructor, via AGGR_INIT_ZERO_FIRST (c++/68006). */
18368 && !implicit_default_ctor_p (decl1))
18369 finish_expr_stmt (build_clobber_this (CLOBBER_OBJECT_BEGIN));
18371 if (!processing_template_decl
18372 && DECL_CONSTRUCTOR_P (decl1)
18373 && sanitize_flags_p (SANITIZE_VPTR)
18374 && !DECL_CLONED_FUNCTION_P (decl1)
18375 && !implicit_default_ctor_p (decl1))
18376 cp_ubsan_maybe_initialize_vtbl_ptrs (current_class_ptr);
18378 if (!DECL_OMP_DECLARE_REDUCTION_P (decl1))
18379 start_lambda_scope (decl1);
18381 return true;
18385 /* Like start_preparsed_function, except that instead of a
18386 FUNCTION_DECL, this function takes DECLSPECS and DECLARATOR.
18388 Returns true on success. If the DECLARATOR is not suitable
18389 for a function, we return false, which tells the parser to
18390 skip the entire function. */
18392 bool
18393 start_function (cp_decl_specifier_seq *declspecs,
18394 const cp_declarator *declarator,
18395 tree attrs)
18397 tree decl1;
18399 decl1 = grokdeclarator (declarator, declspecs, FUNCDEF, 1, &attrs);
18400 invoke_plugin_callbacks (PLUGIN_START_PARSE_FUNCTION, decl1);
18401 if (decl1 == error_mark_node)
18402 return false;
18404 if (DECL_MAIN_P (decl1))
18405 /* main must return int. grokfndecl should have corrected it
18406 (and issued a diagnostic) if the user got it wrong. */
18407 gcc_assert (same_type_p (TREE_TYPE (TREE_TYPE (decl1)),
18408 integer_type_node));
18410 return start_preparsed_function (decl1, attrs, /*flags=*/SF_DEFAULT);
18413 /* Returns true iff an EH_SPEC_BLOCK should be created in the body of
18414 FN. */
18416 bool
18417 use_eh_spec_block (tree fn)
18419 return (flag_exceptions && flag_enforce_eh_specs
18420 && !processing_template_decl
18421 /* We insert the EH_SPEC_BLOCK only in the original
18422 function; then, it is copied automatically to the
18423 clones. */
18424 && !DECL_CLONED_FUNCTION_P (fn)
18425 /* Implicitly-generated constructors and destructors have
18426 exception specifications. However, those specifications
18427 are the union of the possible exceptions specified by the
18428 constructors/destructors for bases and members, so no
18429 unallowed exception will ever reach this function. By
18430 not creating the EH_SPEC_BLOCK we save a little memory,
18431 and we avoid spurious warnings about unreachable
18432 code. */
18433 && !DECL_DEFAULTED_FN (fn)
18434 && !type_throw_all_p (TREE_TYPE (fn)));
18437 /* Helper function to push ARGS into the current lexical scope. DECL
18438 is the function declaration. NONPARMS is used to handle enum
18439 constants. */
18441 void
18442 do_push_parm_decls (tree decl, tree args, tree *nonparms)
18444 /* If we're doing semantic analysis, then we'll call pushdecl
18445 for each of these. We must do them in reverse order so that
18446 they end in the correct forward order. */
18447 args = nreverse (args);
18449 tree next;
18450 for (tree parm = args; parm; parm = next)
18452 next = DECL_CHAIN (parm);
18453 if (TREE_CODE (parm) == PARM_DECL)
18454 pushdecl (parm);
18455 else if (nonparms)
18457 /* If we find an enum constant or a type tag, put it aside for
18458 the moment. */
18459 TREE_CHAIN (parm) = NULL_TREE;
18460 *nonparms = chainon (*nonparms, parm);
18464 /* Get the decls in their original chain order and record in the
18465 function. This is all and only the PARM_DECLs that were
18466 pushed into scope by the loop above. */
18467 DECL_ARGUMENTS (decl) = get_local_decls ();
18470 /* Store the parameter declarations into the current function declaration.
18471 This is called after parsing the parameter declarations, before
18472 digesting the body of the function.
18474 Also install to binding contour return value identifier, if any. */
18476 static void
18477 store_parm_decls (tree current_function_parms)
18479 tree fndecl = current_function_decl;
18481 /* This is a chain of any other decls that came in among the parm
18482 declarations. If a parm is declared with enum {foo, bar} x;
18483 then CONST_DECLs for foo and bar are put here. */
18484 tree nonparms = NULL_TREE;
18486 if (current_function_parms)
18488 /* This case is when the function was defined with an ANSI prototype.
18489 The parms already have decls, so we need not do anything here
18490 except record them as in effect
18491 and complain if any redundant old-style parm decls were written. */
18493 tree specparms = current_function_parms;
18495 /* Must clear this because it might contain TYPE_DECLs declared
18496 at class level. */
18497 current_binding_level->names = NULL;
18499 do_push_parm_decls (fndecl, specparms, &nonparms);
18501 else
18502 DECL_ARGUMENTS (fndecl) = NULL_TREE;
18504 /* Now store the final chain of decls for the arguments
18505 as the decl-chain of the current lexical scope.
18506 Put the enumerators in as well, at the front so that
18507 DECL_ARGUMENTS is not modified. */
18508 current_binding_level->names = chainon (nonparms, DECL_ARGUMENTS (fndecl));
18510 if (use_eh_spec_block (current_function_decl))
18511 current_eh_spec_block = begin_eh_spec_block ();
18515 /* Mark CDTOR's implicit THIS argument for returning, if required by
18516 the ABI.. Return the decl for THIS, if it is to be returned, and
18517 NULL otherwise. */
18519 tree
18520 maybe_prepare_return_this (tree cdtor)
18522 if (targetm.cxx.cdtor_returns_this ())
18523 if (tree val = DECL_ARGUMENTS (cdtor))
18525 suppress_warning (val, OPT_Wuse_after_free);
18526 return val;
18529 return NULL_TREE;
18532 /* Set the return value of the [cd]tor if the ABI wants that. */
18534 void
18535 maybe_return_this ()
18537 if (tree val = maybe_prepare_return_this (current_function_decl))
18539 /* Return the address of the object. */
18540 val = fold_convert (TREE_TYPE (DECL_RESULT (current_function_decl)), val);
18541 val = build2 (MODIFY_EXPR, TREE_TYPE (val),
18542 DECL_RESULT (current_function_decl), val);
18543 tree exprstmt = build_stmt (input_location, RETURN_EXPR, val);
18544 add_stmt (exprstmt);
18548 /* Do all the processing for the beginning of a destructor; set up the
18549 vtable pointers and cleanups for bases and members. */
18551 static void
18552 begin_destructor_body (void)
18554 tree compound_stmt;
18556 /* If the CURRENT_CLASS_TYPE is incomplete, we will have already
18557 issued an error message. We still want to try to process the
18558 body of the function, but initialize_vtbl_ptrs will crash if
18559 TYPE_BINFO is NULL. */
18560 if (COMPLETE_TYPE_P (current_class_type))
18562 compound_stmt = begin_compound_stmt (0);
18563 /* Make all virtual function table pointers in non-virtual base
18564 classes point to CURRENT_CLASS_TYPE's virtual function
18565 tables. */
18566 initialize_vtbl_ptrs (current_class_ptr);
18567 finish_compound_stmt (compound_stmt);
18569 if (flag_lifetime_dse
18570 /* Clobbering an empty base is harmful if it overlays real data. */
18571 && !is_empty_class (current_class_type))
18573 if (sanitize_flags_p (SANITIZE_VPTR)
18574 && (flag_sanitize_recover & SANITIZE_VPTR) == 0
18575 && TYPE_CONTAINS_VPTR_P (current_class_type))
18577 tree binfo = TYPE_BINFO (current_class_type);
18578 tree ref
18579 = cp_build_fold_indirect_ref (current_class_ptr);
18581 tree vtbl_ptr = build_vfield_ref (ref, TREE_TYPE (binfo));
18582 tree vtbl = build_zero_cst (TREE_TYPE (vtbl_ptr));
18583 tree stmt = cp_build_modify_expr (input_location, vtbl_ptr,
18584 NOP_EXPR, vtbl,
18585 tf_warning_or_error);
18586 /* If the vptr is shared with some virtual nearly empty base,
18587 don't clear it if not in charge, the dtor of the virtual
18588 nearly empty base will do that later. */
18589 if (CLASSTYPE_VBASECLASSES (current_class_type))
18591 tree c = current_class_type;
18592 while (CLASSTYPE_PRIMARY_BINFO (c))
18594 if (BINFO_VIRTUAL_P (CLASSTYPE_PRIMARY_BINFO (c)))
18596 stmt = convert_to_void (stmt, ICV_STATEMENT,
18597 tf_warning_or_error);
18598 stmt = build_if_in_charge (stmt);
18599 break;
18601 c = BINFO_TYPE (CLASSTYPE_PRIMARY_BINFO (c));
18604 finish_decl_cleanup (NULL_TREE, stmt);
18606 else
18607 finish_decl_cleanup (NULL_TREE,
18608 build_clobber_this (CLOBBER_OBJECT_END));
18611 /* And insert cleanups for our bases and members so that they
18612 will be properly destroyed if we throw. */
18613 push_base_cleanups ();
18617 /* Do the necessary processing for the beginning of a function body, which
18618 in this case includes member-initializers, but not the catch clauses of
18619 a function-try-block. Currently, this means opening a binding level
18620 for the member-initializers (in a ctor), member cleanups (in a dtor),
18621 and capture proxies (in a lambda operator()). */
18623 tree
18624 begin_function_body (void)
18626 if (! FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
18627 return NULL_TREE;
18629 if (processing_template_decl)
18630 /* Do nothing now. */;
18631 else
18632 /* Always keep the BLOCK node associated with the outermost pair of
18633 curly braces of a function. These are needed for correct
18634 operation of dwarfout.c. */
18635 keep_next_level (true);
18637 tree stmt = begin_compound_stmt (BCS_FN_BODY);
18638 current_binding_level->artificial = 1;
18640 if (processing_template_decl)
18641 /* Do nothing now. */;
18642 else if (DECL_DESTRUCTOR_P (current_function_decl))
18643 begin_destructor_body ();
18645 return stmt;
18648 /* Do the processing for the end of a function body. Currently, this means
18649 closing out the cleanups for fully-constructed bases and members, and in
18650 the case of the destructor, deleting the object if desired. Again, this
18651 is only meaningful for [cd]tors, since they are the only functions where
18652 there is a significant distinction between the main body and any
18653 function catch clauses. Handling, say, main() return semantics here
18654 would be wrong, as flowing off the end of a function catch clause for
18655 main() would also need to return 0. */
18657 void
18658 finish_function_body (tree compstmt)
18660 if (compstmt == NULL_TREE)
18661 return;
18663 /* Close the block. */
18664 finish_compound_stmt (compstmt);
18666 if (processing_template_decl)
18667 /* Do nothing now. */;
18668 else if (DECL_CONSTRUCTOR_P (current_function_decl)
18669 || DECL_DESTRUCTOR_P (current_function_decl))
18670 maybe_return_this ();
18673 /* Given a function, returns the BLOCK corresponding to the outermost level
18674 of curly braces, skipping the artificial block created for constructor
18675 initializers. */
18677 tree
18678 outer_curly_brace_block (tree fndecl)
18680 tree block = DECL_INITIAL (fndecl);
18681 if (BLOCK_OUTER_CURLY_BRACE_P (block))
18682 return block;
18683 block = BLOCK_SUBBLOCKS (block);
18684 if (BLOCK_OUTER_CURLY_BRACE_P (block))
18685 return block;
18686 block = BLOCK_SUBBLOCKS (block);
18687 gcc_assert (BLOCK_OUTER_CURLY_BRACE_P (block));
18688 return block;
18691 /* If FNDECL is a class's key method, add the class to the list of
18692 keyed classes that should be emitted. */
18694 static void
18695 record_key_method_defined (tree fndecl)
18697 if (DECL_OBJECT_MEMBER_FUNCTION_P (fndecl)
18698 && DECL_VIRTUAL_P (fndecl)
18699 && !processing_template_decl)
18701 tree fnclass = DECL_CONTEXT (fndecl);
18702 if (fndecl == CLASSTYPE_KEY_METHOD (fnclass))
18704 tree classdecl = TYPE_NAME (fnclass);
18705 /* Classes attached to a named module are already handled. */
18706 if (!DECL_LANG_SPECIFIC (classdecl)
18707 || !DECL_MODULE_ATTACH_P (classdecl))
18708 vec_safe_push (keyed_classes, fnclass);
18713 /* Attempt to add a fix-it hint to RICHLOC suggesting the insertion
18714 of "return *this;" immediately before its location, using FNDECL's
18715 first statement (if any) to give the indentation, if appropriate. */
18717 static void
18718 add_return_star_this_fixit (gcc_rich_location *richloc, tree fndecl)
18720 location_t indent = UNKNOWN_LOCATION;
18721 tree stmts = expr_first (DECL_SAVED_TREE (fndecl));
18722 if (stmts)
18723 indent = EXPR_LOCATION (stmts);
18724 richloc->add_fixit_insert_formatted ("return *this;",
18725 richloc->get_loc (),
18726 indent);
18729 /* Finish up a function declaration and compile that function
18730 all the way to assembler language output. The free the storage
18731 for the function definition. INLINE_P is TRUE if we just
18732 finished processing the body of an in-class inline function
18733 definition. (This processing will have taken place after the
18734 class definition is complete.) */
18736 tree
18737 finish_function (bool inline_p)
18739 tree fndecl = current_function_decl;
18740 tree fntype, ctype = NULL_TREE;
18741 tree resumer = NULL_TREE, destroyer = NULL_TREE;
18743 /* When we get some parse errors, we can end up without a
18744 current_function_decl, so cope. */
18745 if (fndecl == NULL_TREE || fndecl == error_mark_node)
18746 return error_mark_node;
18748 bool do_contracts = (DECL_HAS_CONTRACTS_P (fndecl)
18749 && !processing_template_decl);
18751 if (!DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18752 finish_lambda_scope ();
18754 if (c_dialect_objc ())
18755 objc_finish_function ();
18757 record_key_method_defined (fndecl);
18759 fntype = TREE_TYPE (fndecl);
18761 /* TREE_READONLY (fndecl) = 1;
18762 This caused &foo to be of type ptr-to-const-function
18763 which then got a warning when stored in a ptr-to-function variable. */
18765 gcc_assert (building_stmt_list_p ());
18766 /* The current function is being defined, so its DECL_INITIAL should
18767 be set, and unless there's a multiple definition, it should be
18768 error_mark_node. */
18769 gcc_assert (DECL_INITIAL (fndecl) == error_mark_node);
18771 cp_coroutine_transform *coroutine = nullptr;
18772 if (flag_coroutines
18773 && !processing_template_decl
18774 && DECL_COROUTINE_P (fndecl)
18775 && !DECL_RAMP_FN (fndecl))
18777 gcc_checking_assert (!DECL_CLONED_FUNCTION_P (fndecl)
18778 && !DECL_DEFAULTED_FN (fndecl));
18779 coroutine = new cp_coroutine_transform (fndecl, inline_p);
18780 if (coroutine && coroutine->cp_valid_coroutine ())
18781 coroutine->apply_transforms ();
18783 /* We should handle coroutine IFNs in middle end lowering. */
18784 cfun->coroutine_component = true;
18786 /* Do not try to process the ramp's EH unless outlining succeeded. */
18787 if (coroutine->cp_valid_coroutine () && use_eh_spec_block (fndecl))
18788 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
18789 (TREE_TYPE (fndecl)),
18790 current_eh_spec_block);
18792 /* If outlining succeeded, then add contracts handling if needed. */
18793 if (coroutine->cp_valid_coroutine () && do_contracts)
18794 maybe_apply_function_contracts (fndecl);
18796 else
18797 /* For a cloned function, we've already got all the code we need;
18798 there's no need to add any extra bits. */
18799 if (!DECL_CLONED_FUNCTION_P (fndecl))
18801 /* Make it so that `main' always returns 0 by default. */
18802 if (DECL_MAIN_FREESTANDING_P (current_function_decl)
18803 && !TREE_THIS_VOLATILE (current_function_decl))
18804 finish_return_stmt (integer_zero_node);
18806 if (use_eh_spec_block (current_function_decl))
18807 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
18808 (TREE_TYPE (current_function_decl)),
18809 current_eh_spec_block);
18811 if (do_contracts)
18812 maybe_apply_function_contracts (current_function_decl);
18816 /* If we're saving up tree structure, tie off the function now. */
18817 DECL_SAVED_TREE (fndecl) = pop_stmt_list (DECL_SAVED_TREE (fndecl));
18819 finish_fname_decls ();
18821 /* This must come after expand_function_end because cleanups might
18822 have declarations (from inline functions) that need to go into
18823 this function's blocks. */
18825 /* If the current binding level isn't the outermost binding level
18826 for this function, either there is a bug, or we have experienced
18827 syntax errors and the statement tree is malformed. */
18828 if (current_binding_level->kind != sk_function_parms)
18830 /* Make sure we have already experienced errors. */
18831 gcc_assert (errorcount);
18833 /* Throw away the broken statement tree and extra binding
18834 levels. */
18835 DECL_SAVED_TREE (fndecl) = alloc_stmt_list ();
18837 while (current_binding_level->kind != sk_function_parms)
18839 if (current_binding_level->kind == sk_class)
18840 pop_nested_class ();
18841 else
18842 poplevel (0, 0, 0);
18845 poplevel (1, 0, 1);
18847 /* Statements should always be full-expressions at the outermost set
18848 of curly braces for a function. */
18849 gcc_assert (stmts_are_full_exprs_p ());
18851 /* If there are no return statements in a function with auto return type,
18852 the return type is void. But if the declared type is something like
18853 auto*, this is an error. */
18854 if (!processing_template_decl && FNDECL_USED_AUTO (fndecl)
18855 && TREE_TYPE (fntype) == DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
18857 if (is_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
18858 && !current_function_returns_value
18859 && !current_function_returns_null)
18861 /* We haven't applied return type deduction because we haven't
18862 seen any return statements. Do that now. */
18863 tree node = type_uses_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
18864 do_auto_deduction (DECL_SAVED_AUTO_RETURN_TYPE (fndecl),
18865 void_node, node, tf_warning_or_error,
18866 adc_return_type);
18868 apply_deduced_return_type (fndecl, void_type_node);
18869 fntype = TREE_TYPE (fndecl);
18871 else if (!current_function_returns_value
18872 && !current_function_returns_null)
18874 auto_diagnostic_group d;
18875 error ("no return statements in function returning %qT",
18876 DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
18877 inform (input_location, "only plain %<auto%> return type can be "
18878 "deduced to %<void%>");
18882 /* Remember that we were in class scope. */
18883 if (current_class_name)
18884 ctype = current_class_type;
18886 if (DECL_DELETED_FN (fndecl))
18888 DECL_INITIAL (fndecl) = error_mark_node;
18889 DECL_SAVED_TREE (fndecl) = NULL_TREE;
18890 goto cleanup;
18893 if (flag_openmp)
18894 if (tree attr = lookup_attribute ("omp declare variant base",
18895 DECL_ATTRIBUTES (fndecl)))
18896 omp_declare_variant_finalize (fndecl, attr);
18898 /* Complain if there's just no return statement. */
18899 if ((warn_return_type
18900 || (cxx_dialect >= cxx14
18901 && DECL_DECLARED_CONSTEXPR_P (fndecl)))
18902 && !VOID_TYPE_P (TREE_TYPE (fntype))
18903 && !dependent_type_p (TREE_TYPE (fntype))
18904 && !current_function_returns_value && !current_function_returns_null
18905 /* Don't complain if we abort or throw. */
18906 && !current_function_returns_abnormally
18907 /* Don't complain if there's an infinite loop. */
18908 && !current_function_infinite_loop
18909 /* Don't complain if we are declared noreturn. */
18910 && !TREE_THIS_VOLATILE (fndecl)
18911 && !DECL_NAME (DECL_RESULT (fndecl))
18912 && !warning_suppressed_p (fndecl, OPT_Wreturn_type)
18913 /* Structor return values (if any) are set by the compiler. */
18914 && !DECL_CONSTRUCTOR_P (fndecl)
18915 && !DECL_DESTRUCTOR_P (fndecl)
18916 && targetm.warn_func_return (fndecl))
18918 gcc_rich_location richloc (input_location);
18919 /* Potentially add a "return *this;" fix-it hint for
18920 assignment operators. */
18921 if (IDENTIFIER_ASSIGN_OP_P (DECL_NAME (fndecl)))
18923 tree valtype = TREE_TYPE (DECL_RESULT (fndecl));
18924 if (TREE_CODE (valtype) == REFERENCE_TYPE
18925 && current_class_ref
18926 && same_type_ignoring_top_level_qualifiers_p
18927 (TREE_TYPE (valtype), TREE_TYPE (current_class_ref))
18928 && global_dc->option_enabled_p (OPT_Wreturn_type))
18929 add_return_star_this_fixit (&richloc, fndecl);
18931 if (cxx_dialect >= cxx14
18932 && DECL_DECLARED_CONSTEXPR_P (fndecl))
18933 error_at (&richloc, "no return statement in %<constexpr%> function "
18934 "returning non-void");
18935 else if (warning_at (&richloc, OPT_Wreturn_type,
18936 "no return statement in function returning "
18937 "non-void"))
18938 suppress_warning (fndecl, OPT_Wreturn_type);
18941 /* Lambda closure members are implicitly constexpr if possible. */
18942 if (cxx_dialect >= cxx17
18943 && LAMBDA_TYPE_P (CP_DECL_CONTEXT (fndecl)))
18944 DECL_DECLARED_CONSTEXPR_P (fndecl)
18945 = ((processing_template_decl
18946 || is_valid_constexpr_fn (fndecl, /*complain*/false))
18947 && potential_constant_expression (DECL_SAVED_TREE (fndecl)));
18949 /* Save constexpr function body before it gets munged by
18950 the NRV transformation. */
18951 maybe_save_constexpr_fundef (fndecl);
18953 /* Invoke the pre-genericize plugin before we start munging things. */
18954 if (!processing_template_decl)
18955 invoke_plugin_callbacks (PLUGIN_PRE_GENERICIZE, fndecl);
18957 /* Perform delayed folding before NRV transformation. */
18958 if (!processing_template_decl
18959 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
18960 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18961 cp_fold_function (fndecl);
18963 /* Set up the named return value optimization, if we can. Candidate
18964 variables are selected in check_return_expr. */
18965 if (tree r = current_function_return_value)
18967 if (r != error_mark_node)
18968 finalize_nrv (fndecl, r);
18969 current_function_return_value = NULL_TREE;
18972 /* Must mark the RESULT_DECL as being in this function. */
18973 DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
18975 /* Set the BLOCK_SUPERCONTEXT of the outermost function scope to point
18976 to the FUNCTION_DECL node itself. */
18977 BLOCK_SUPERCONTEXT (DECL_INITIAL (fndecl)) = fndecl;
18979 /* Store the end of the function, so that we get good line number
18980 info for the epilogue. */
18981 cfun->function_end_locus = input_location;
18983 /* Complain about parameters that are only set, but never otherwise used. */
18984 if (warn_unused_but_set_parameter
18985 && !processing_template_decl
18986 && errorcount == unused_but_set_errorcount
18987 && !DECL_CLONED_FUNCTION_P (fndecl))
18989 tree decl;
18991 for (decl = DECL_ARGUMENTS (fndecl);
18992 decl;
18993 decl = DECL_CHAIN (decl))
18994 if (TREE_USED (decl)
18995 && TREE_CODE (decl) == PARM_DECL
18996 && !DECL_READ_P (decl)
18997 && DECL_NAME (decl)
18998 && !DECL_ARTIFICIAL (decl)
18999 && !warning_suppressed_p (decl,OPT_Wunused_but_set_parameter)
19000 && !DECL_IN_SYSTEM_HEADER (decl)
19001 && TREE_TYPE (decl) != error_mark_node
19002 && !TYPE_REF_P (TREE_TYPE (decl))
19003 && (!CLASS_TYPE_P (TREE_TYPE (decl))
19004 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl))))
19005 warning_at (DECL_SOURCE_LOCATION (decl),
19006 OPT_Wunused_but_set_parameter,
19007 "parameter %qD set but not used", decl);
19008 unused_but_set_errorcount = errorcount;
19011 /* Complain about locally defined typedefs that are not used in this
19012 function. */
19013 maybe_warn_unused_local_typedefs ();
19015 /* Possibly warn about unused parameters. */
19016 if (warn_unused_parameter
19017 && !processing_template_decl
19018 && !DECL_CLONED_FUNCTION_P (fndecl))
19019 do_warn_unused_parameter (fndecl);
19021 /* Genericize before inlining. */
19022 if (!processing_template_decl
19023 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
19024 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
19025 cp_genericize (fndecl);
19027 /* If this function can't throw any exceptions, remember that. */
19028 if (!processing_template_decl
19029 && !cp_function_chain->can_throw
19030 && !flag_non_call_exceptions
19031 && !decl_replaceable_p (fndecl,
19032 opt_for_fn (fndecl, flag_semantic_interposition)))
19033 TREE_NOTHROW (fndecl) = 1;
19035 cleanup:
19037 /* We're leaving the context of this function, so zap cfun. It's still in
19038 DECL_STRUCT_FUNCTION, and we'll restore it in tree_rest_of_compilation. */
19039 set_cfun (NULL);
19040 current_function_decl = NULL;
19042 /* If this is an in-class inline definition, we may have to pop the
19043 bindings for the template parameters that we added in
19044 maybe_begin_member_template_processing when start_function was
19045 called. */
19046 if (inline_p)
19047 maybe_end_member_template_processing ();
19049 /* Leave the scope of the class. */
19050 if (ctype)
19051 pop_nested_class ();
19053 --function_depth;
19055 /* Clean up. */
19056 invoke_plugin_callbacks (PLUGIN_FINISH_PARSE_FUNCTION, fndecl);
19058 /* Build outlined functions for coroutines and contracts. */
19060 if (coroutine)
19062 /* Emit the resumer and destroyer functions now, providing that we have
19063 not encountered some fatal error. */
19064 if (coroutine->cp_valid_coroutine ())
19066 coroutine->finish_transforms ();
19067 resumer = coroutine->get_resumer ();
19068 destroyer = coroutine->get_destroyer ();
19069 expand_or_defer_fn (resumer);
19070 expand_or_defer_fn (destroyer);
19072 delete coroutine;
19075 /* If we have used outlined contracts checking functions, build and emit
19076 them here. */
19077 finish_function_contracts (fndecl);
19079 return fndecl;
19082 /* Create the FUNCTION_DECL for a function definition.
19083 DECLSPECS and DECLARATOR are the parts of the declaration;
19084 they describe the return type and the name of the function,
19085 but twisted together in a fashion that parallels the syntax of C.
19087 This function creates a binding context for the function body
19088 as well as setting up the FUNCTION_DECL in current_function_decl.
19090 Returns a FUNCTION_DECL on success.
19092 If the DECLARATOR is not suitable for a function (it defines a datum
19093 instead), we return 0, which tells yyparse to report a parse error.
19095 May return void_type_node indicating that this method is actually
19096 a friend. See grokfield for more details.
19098 Came here with a `.pushlevel' .
19100 DO NOT MAKE ANY CHANGES TO THIS CODE WITHOUT MAKING CORRESPONDING
19101 CHANGES TO CODE IN `grokfield'. */
19103 tree
19104 grokmethod (cp_decl_specifier_seq *declspecs,
19105 const cp_declarator *declarator, tree attrlist)
19107 tree fndecl = grokdeclarator (declarator, declspecs, MEMFUNCDEF, 0,
19108 &attrlist);
19110 if (fndecl == error_mark_node)
19111 return error_mark_node;
19113 if (attrlist)
19114 cplus_decl_attributes (&fndecl, attrlist, 0);
19116 /* Pass friends other than inline friend functions back. */
19117 if (fndecl == void_type_node)
19118 return fndecl;
19120 if (DECL_IN_AGGR_P (fndecl))
19122 if (DECL_CLASS_SCOPE_P (fndecl))
19123 error ("%qD is already defined in class %qT", fndecl,
19124 DECL_CONTEXT (fndecl));
19125 return error_mark_node;
19128 check_template_shadow (fndecl);
19130 /* p1779 ABI-Isolation makes inline not a default for in-class
19131 definitions attached to a named module. If the user explicitly
19132 made it inline, grokdeclarator will already have done the right
19133 things. */
19134 if ((!named_module_attach_p ()
19135 || flag_module_implicit_inline
19136 /* Lambda's operator function remains inline. */
19137 || LAMBDA_TYPE_P (DECL_CONTEXT (fndecl)))
19138 /* If the user explicitly asked for this to be inline, we don't
19139 need to do more, but more importantly we want to warn if we
19140 can't inline it. */
19141 && !DECL_DECLARED_INLINE_P (fndecl))
19143 if (TREE_PUBLIC (fndecl))
19144 DECL_COMDAT (fndecl) = 1;
19145 DECL_DECLARED_INLINE_P (fndecl) = 1;
19146 /* It's ok if we can't inline this. */
19147 DECL_NO_INLINE_WARNING_P (fndecl) = 1;
19150 /* We process method specializations in finish_struct_1. */
19151 if (processing_template_decl && !DECL_TEMPLATE_SPECIALIZATION (fndecl))
19153 /* Avoid calling decl_spec_seq... until we have to. */
19154 bool friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
19155 fndecl = push_template_decl (fndecl, friendp);
19156 if (fndecl == error_mark_node)
19157 return fndecl;
19160 if (DECL_CHAIN (fndecl) && !decl_spec_seq_has_spec_p (declspecs, ds_friend))
19162 fndecl = copy_node (fndecl);
19163 TREE_CHAIN (fndecl) = NULL_TREE;
19166 cp_finish_decl (fndecl, NULL_TREE, false, NULL_TREE, 0);
19168 DECL_IN_AGGR_P (fndecl) = 1;
19169 return fndecl;
19173 /* VAR is a VAR_DECL. If its type is incomplete, remember VAR so that
19174 we can lay it out later, when and if its type becomes complete.
19176 Also handle constexpr variables where the initializer involves
19177 an unlowered PTRMEM_CST because the class isn't complete yet. */
19179 void
19180 maybe_register_incomplete_var (tree var)
19182 gcc_assert (VAR_P (var));
19184 /* Keep track of variables with incomplete types. */
19185 if (!processing_template_decl && TREE_TYPE (var) != error_mark_node
19186 && DECL_EXTERNAL (var))
19188 tree inner_type = TREE_TYPE (var);
19190 while (TREE_CODE (inner_type) == ARRAY_TYPE)
19191 inner_type = TREE_TYPE (inner_type);
19192 inner_type = TYPE_MAIN_VARIANT (inner_type);
19194 if ((!COMPLETE_TYPE_P (inner_type) && CLASS_TYPE_P (inner_type))
19195 /* RTTI TD entries are created while defining the type_info. */
19196 || (TYPE_LANG_SPECIFIC (inner_type)
19197 && TYPE_BEING_DEFINED (inner_type)))
19199 incomplete_var iv = {var, inner_type};
19200 vec_safe_push (incomplete_vars, iv);
19202 else if (!(DECL_LANG_SPECIFIC (var) && DECL_TEMPLATE_INFO (var))
19203 && DECL_CLASS_SCOPE_P (var)
19204 && TYPE_BEING_DEFINED (DECL_CONTEXT (var))
19205 && decl_constant_var_p (var)
19206 && (TYPE_PTRMEM_P (inner_type) || CLASS_TYPE_P (inner_type)))
19208 /* When the outermost open class is complete we can resolve any
19209 pointers-to-members. */
19210 tree context = outermost_open_class ();
19211 incomplete_var iv = {var, context};
19212 vec_safe_push (incomplete_vars, iv);
19217 /* Called when a class type (given by TYPE) is defined. If there are
19218 any existing VAR_DECLs whose type has been completed by this
19219 declaration, update them now. */
19221 void
19222 complete_vars (tree type)
19224 unsigned ix;
19225 incomplete_var *iv;
19227 for (ix = 0; vec_safe_iterate (incomplete_vars, ix, &iv); )
19229 if (same_type_p (type, iv->incomplete_type))
19231 tree var = iv->decl;
19232 tree type = TREE_TYPE (var);
19234 if (type != error_mark_node
19235 && (TYPE_MAIN_VARIANT (strip_array_types (type))
19236 == iv->incomplete_type))
19238 /* Complete the type of the variable. */
19239 complete_type (type);
19240 cp_apply_type_quals_to_decl (cp_type_quals (type), var);
19241 if (COMPLETE_TYPE_P (type))
19242 layout_var_decl (var);
19245 /* Remove this entry from the list. */
19246 incomplete_vars->unordered_remove (ix);
19248 else
19249 ix++;
19253 /* If DECL is of a type which needs a cleanup, build and return an
19254 expression to perform that cleanup here. Return NULL_TREE if no
19255 cleanup need be done. DECL can also be a _REF when called from
19256 split_nonconstant_init_1. */
19258 tree
19259 cxx_maybe_build_cleanup (tree decl, tsubst_flags_t complain)
19261 tree type;
19262 tree attr;
19263 tree cleanup;
19265 /* Assume no cleanup is required. */
19266 cleanup = NULL_TREE;
19268 if (error_operand_p (decl))
19269 return cleanup;
19271 /* Handle "__attribute__((cleanup))". We run the cleanup function
19272 before the destructor since the destructor is what actually
19273 terminates the lifetime of the object. */
19274 if (DECL_P (decl))
19275 attr = lookup_attribute ("cleanup", DECL_ATTRIBUTES (decl));
19276 else
19277 attr = NULL_TREE;
19278 if (attr)
19280 tree id;
19281 tree fn;
19282 tree arg;
19284 /* Get the name specified by the user for the cleanup function. */
19285 id = TREE_VALUE (TREE_VALUE (attr));
19286 /* Look up the name to find the cleanup function to call. It is
19287 important to use lookup_name here because that is what is
19288 used in c-common.cc:handle_cleanup_attribute when performing
19289 initial checks on the attribute. Note that those checks
19290 include ensuring that the function found is not an overloaded
19291 function, or an object with an overloaded call operator,
19292 etc.; we can rely on the fact that the function found is an
19293 ordinary FUNCTION_DECL. */
19294 fn = lookup_name (id);
19295 arg = build_address (decl);
19296 if (!mark_used (decl, complain) && !(complain & tf_error))
19297 return error_mark_node;
19298 cleanup = cp_build_function_call_nary (fn, complain, arg, NULL_TREE);
19299 if (cleanup == error_mark_node)
19300 return error_mark_node;
19302 /* Handle ordinary C++ destructors. */
19303 type = TREE_TYPE (decl);
19304 if (type_build_dtor_call (type))
19306 int flags = LOOKUP_NORMAL|LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR;
19307 tree addr;
19308 tree call;
19310 if (TREE_CODE (type) == ARRAY_TYPE)
19311 addr = decl;
19312 else
19313 addr = build_address (decl);
19315 call = build_delete (input_location, TREE_TYPE (addr), addr,
19316 sfk_complete_destructor, flags, 0, complain);
19317 if (call == error_mark_node)
19318 cleanup = error_mark_node;
19319 else if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
19320 /* Discard the call. */;
19321 else if (decl_maybe_constant_destruction (decl, type)
19322 && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
19323 cxx_constant_dtor (call, decl);
19324 else if (cleanup)
19325 cleanup = cp_build_compound_expr (cleanup, call, complain);
19326 else
19327 cleanup = call;
19330 /* build_delete sets the location of the destructor call to the
19331 current location, even though the destructor is going to be
19332 called later, at the end of the current scope. This can lead to
19333 a "jumpy" behavior for users of debuggers when they step around
19334 the end of the block. So let's unset the location of the
19335 destructor call instead. */
19336 protected_set_expr_location (cleanup, UNKNOWN_LOCATION);
19337 if (cleanup && CONVERT_EXPR_P (cleanup))
19338 protected_set_expr_location (TREE_OPERAND (cleanup, 0), UNKNOWN_LOCATION);
19340 if (cleanup
19341 && DECL_P (decl)
19342 && !lookup_attribute ("warn_unused", TYPE_ATTRIBUTES (TREE_TYPE (decl)))
19343 /* Treat objects with destructors as used; the destructor may do
19344 something substantive. */
19345 && !mark_used (decl, complain) && !(complain & tf_error))
19346 return error_mark_node;
19348 if (cleanup && cfun && !processing_template_decl
19349 && !expr_noexcept_p (cleanup, tf_none))
19350 cp_function_chain->throwing_cleanup = true;
19352 return cleanup;
19356 /* Return the FUNCTION_TYPE that corresponds to MEMFNTYPE, which can be a
19357 FUNCTION_DECL, METHOD_TYPE, FUNCTION_TYPE, pointer or reference to
19358 METHOD_TYPE or FUNCTION_TYPE, or pointer to member function. */
19360 tree
19361 static_fn_type (tree memfntype)
19363 tree fntype;
19364 tree args;
19366 if (TYPE_PTRMEMFUNC_P (memfntype))
19367 memfntype = TYPE_PTRMEMFUNC_FN_TYPE (memfntype);
19368 if (INDIRECT_TYPE_P (memfntype)
19369 || TREE_CODE (memfntype) == FUNCTION_DECL)
19370 memfntype = TREE_TYPE (memfntype);
19371 if (TREE_CODE (memfntype) == FUNCTION_TYPE)
19372 return memfntype;
19373 gcc_assert (TREE_CODE (memfntype) == METHOD_TYPE);
19374 args = TYPE_ARG_TYPES (memfntype);
19375 fntype = build_function_type (TREE_TYPE (memfntype), TREE_CHAIN (args));
19376 fntype = apply_memfn_quals (fntype, type_memfn_quals (memfntype));
19377 fntype = (cp_build_type_attribute_variant
19378 (fntype, TYPE_ATTRIBUTES (memfntype)));
19379 fntype = cxx_copy_lang_qualifiers (fntype, memfntype);
19380 return fntype;
19383 /* DECL was originally constructed as a non-static member function,
19384 but turned out to be static. Update it accordingly. */
19386 void
19387 revert_static_member_fn (tree decl)
19389 tree stype = static_fn_type (decl);
19390 cp_cv_quals quals = type_memfn_quals (stype);
19391 cp_ref_qualifier rqual = type_memfn_rqual (stype);
19393 if (quals != TYPE_UNQUALIFIED || rqual != REF_QUAL_NONE)
19394 stype = apply_memfn_quals (stype, TYPE_UNQUALIFIED, REF_QUAL_NONE);
19396 TREE_TYPE (decl) = stype;
19398 if (DECL_ARGUMENTS (decl))
19399 DECL_ARGUMENTS (decl) = DECL_CHAIN (DECL_ARGUMENTS (decl));
19400 DECL_STATIC_FUNCTION_P (decl) = 1;
19403 /* Return which tree structure is used by T, or TS_CP_GENERIC if T is
19404 one of the language-independent trees. */
19406 enum cp_tree_node_structure_enum
19407 cp_tree_node_structure (union lang_tree_node * t)
19409 switch (TREE_CODE (&t->generic))
19411 case ARGUMENT_PACK_SELECT: return TS_CP_ARGUMENT_PACK_SELECT;
19412 case BASELINK: return TS_CP_BASELINK;
19413 case CONSTRAINT_INFO: return TS_CP_CONSTRAINT_INFO;
19414 case DEFERRED_NOEXCEPT: return TS_CP_DEFERRED_NOEXCEPT;
19415 case DEFERRED_PARSE: return TS_CP_DEFERRED_PARSE;
19416 case IDENTIFIER_NODE: return TS_CP_IDENTIFIER;
19417 case LAMBDA_EXPR: return TS_CP_LAMBDA_EXPR;
19418 case BINDING_VECTOR: return TS_CP_BINDING_VECTOR;
19419 case OVERLOAD: return TS_CP_OVERLOAD;
19420 case PTRMEM_CST: return TS_CP_PTRMEM;
19421 case STATIC_ASSERT: return TS_CP_STATIC_ASSERT;
19422 case TEMPLATE_DECL: return TS_CP_TEMPLATE_DECL;
19423 case TEMPLATE_INFO: return TS_CP_TEMPLATE_INFO;
19424 case TEMPLATE_PARM_INDEX: return TS_CP_TPI;
19425 case TRAIT_EXPR: return TS_CP_TRAIT_EXPR;
19426 case USERDEF_LITERAL: return TS_CP_USERDEF_LITERAL;
19427 default: return TS_CP_GENERIC;
19431 bool
19432 cp_missing_noreturn_ok_p (tree decl)
19434 /* A missing noreturn is ok for the `main' function. */
19435 return DECL_MAIN_P (decl);
19438 /* Return the decl used to identify the COMDAT group into which DECL should
19439 be placed. */
19441 tree
19442 cxx_comdat_group (tree decl)
19444 /* Virtual tables, construction virtual tables, and virtual table
19445 tables all go in a single COMDAT group, named after the primary
19446 virtual table. */
19447 if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
19448 decl = CLASSTYPE_VTABLES (DECL_CONTEXT (decl));
19449 /* For all other DECLs, the COMDAT group is the mangled name of the
19450 declaration itself. */
19451 else
19453 while (DECL_THUNK_P (decl))
19455 /* If TARGET_USE_LOCAL_THUNK_ALIAS_P, use_thunk puts the thunk
19456 into the same section as the target function. In that case
19457 we must return target's name. */
19458 tree target = THUNK_TARGET (decl);
19459 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (target)
19460 && DECL_SECTION_NAME (target) != NULL
19461 && DECL_ONE_ONLY (target))
19462 decl = target;
19463 else
19464 break;
19466 /* If a ctor/dtor has already set the comdat group by
19467 maybe_clone_body, don't override it. */
19468 if (SUPPORTS_ONE_ONLY
19469 && TREE_CODE (decl) == FUNCTION_DECL
19470 && DECL_CLONED_FUNCTION_P (decl))
19471 if (tree comdat = DECL_COMDAT_GROUP (decl))
19472 return comdat;
19475 return decl;
19478 /* Returns the return type for FN as written by the user, which may include
19479 a placeholder for a deduced return type. */
19481 tree
19482 fndecl_declared_return_type (tree fn)
19484 fn = STRIP_TEMPLATE (fn);
19485 if (FNDECL_USED_AUTO (fn))
19486 return DECL_SAVED_AUTO_RETURN_TYPE (fn);
19488 return TREE_TYPE (TREE_TYPE (fn));
19491 /* Returns true iff DECL is a variable or function declared with an auto type
19492 that has not yet been deduced to a real type. */
19494 bool
19495 undeduced_auto_decl (tree decl)
19497 if (cxx_dialect < cxx11)
19498 return false;
19499 STRIP_ANY_LOCATION_WRAPPER (decl);
19500 return ((VAR_OR_FUNCTION_DECL_P (decl)
19501 || TREE_CODE (decl) == TEMPLATE_DECL)
19502 && type_uses_auto (TREE_TYPE (decl)));
19505 /* Complain if DECL has an undeduced return type. */
19507 bool
19508 require_deduced_type (tree decl, tsubst_flags_t complain)
19510 if (undeduced_auto_decl (decl))
19512 if (TREE_CODE (decl) == FUNCTION_DECL
19513 && fndecl_built_in_p (decl, BUILT_IN_FRONTEND)
19514 && DECL_FE_FUNCTION_CODE (decl) == CP_BUILT_IN_SOURCE_LOCATION)
19516 /* Set the return type of __builtin_source_location. */
19517 tree type = get_source_location_impl_type ();
19518 if (type == error_mark_node)
19520 inform (input_location, "using %qs", "__builtin_source_location");
19521 return false;
19523 type = cp_build_qualified_type (type, TYPE_QUAL_CONST);
19524 type = build_pointer_type (type);
19525 apply_deduced_return_type (decl, type);
19526 return true;
19529 if (warning_suppressed_p (decl) && seen_error ())
19530 /* We probably already complained about deduction failure. */;
19531 else if (complain & tf_error)
19532 error ("use of %qD before deduction of %<auto%>", decl);
19533 note_failed_type_completion_for_satisfaction (decl);
19534 return false;
19536 return true;
19539 /* Create a representation of the explicit-specifier with
19540 constant-expression of EXPR. COMPLAIN is as for tsubst. */
19542 tree
19543 build_explicit_specifier (tree expr, tsubst_flags_t complain)
19545 if (check_for_bare_parameter_packs (expr))
19546 return error_mark_node;
19548 if (instantiation_dependent_expression_p (expr))
19549 /* Wait for instantiation, tsubst_function_decl will handle it. */
19550 return expr;
19552 expr = build_converted_constant_bool_expr (expr, complain);
19553 expr = instantiate_non_dependent_expr (expr, complain);
19554 expr = cxx_constant_value (expr, complain);
19555 return expr;
19558 #include "gt-cp-decl.h"