c++: Revert deferring emission of inline variables [PR114013]
[official-gcc.git] / gcc / cp / decl.cc
blobd19d09adde43b713b6c4149f0c3c4ed901f9d3d1
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 */
64 /* Possible cases of bad specifiers type used by bad_specifiers. */
65 enum bad_spec_place {
66 BSP_VAR, /* variable */
67 BSP_PARM, /* parameter */
68 BSP_TYPE, /* type */
69 BSP_FIELD /* field */
72 static const char *redeclaration_error_message (tree, tree);
74 static bool decl_jump_unsafe (tree);
75 static void require_complete_types_for_parms (tree);
76 static tree grok_reference_init (tree, tree, tree, int);
77 static tree grokvardecl (tree, tree, tree, const cp_decl_specifier_seq *,
78 int, int, int, bool, int, tree, location_t);
79 static void check_static_variable_definition (tree, tree);
80 static void record_unknown_type (tree, const char *);
81 static int member_function_or_else (tree, tree, enum overload_flags);
82 static tree local_variable_p_walkfn (tree *, int *, void *);
83 static const char *tag_name (enum tag_types);
84 static tree lookup_and_check_tag (enum tag_types, tree, TAG_how, bool);
85 static void maybe_deduce_size_from_array_init (tree, tree);
86 static void layout_var_decl (tree);
87 static tree check_initializer (tree, tree, int, vec<tree, va_gc> **);
88 static void make_rtl_for_nonlocal_decl (tree, tree, const char *);
89 static void copy_type_enum (tree , tree);
90 static void check_function_type (tree, tree);
91 static void begin_destructor_body (void);
92 static void record_key_method_defined (tree);
93 static tree create_array_type_for_decl (tree, tree, tree, location_t);
94 static tree get_atexit_node (void);
95 static tree get_dso_handle_node (void);
96 static tree start_cleanup_fn (void);
97 static void end_cleanup_fn (void);
98 static tree cp_make_fname_decl (location_t, tree, int);
99 static void initialize_predefined_identifiers (void);
100 static tree check_special_function_return_type
101 (special_function_kind, tree, tree, int, const location_t*);
102 static tree push_cp_library_fn (enum tree_code, tree, int);
103 static tree build_cp_library_fn (tree, enum tree_code, tree, int);
104 static void store_parm_decls (tree);
105 static void initialize_local_var (tree, tree);
106 static void expand_static_init (tree, tree);
107 static location_t smallest_type_location (const cp_decl_specifier_seq*);
108 static bool identify_goto (tree, location_t, const location_t *,
109 diagnostic_t, bool);
111 /* The following symbols are subsumed in the cp_global_trees array, and
112 listed here individually for documentation purposes.
114 C++ extensions
115 tree wchar_decl_node;
117 tree vtable_entry_type;
118 tree delta_type_node;
119 tree __t_desc_type_node;
121 tree class_type_node;
122 tree unknown_type_node;
124 Array type `vtable_entry_type[]'
126 tree vtbl_type_node;
127 tree vtbl_ptr_type_node;
129 Namespaces,
131 tree std_node;
132 tree abi_node;
134 A FUNCTION_DECL which can call `abort'. Not necessarily the
135 one that the user will declare, but sufficient to be called
136 by routines that want to abort the program.
138 tree abort_fndecl;
140 Used by RTTI
141 tree type_info_type_node, tinfo_decl_id, tinfo_decl_type;
142 tree tinfo_var_id; */
144 tree cp_global_trees[CPTI_MAX];
146 /* A list of objects which have constructors or destructors
147 which reside in namespace scope. The decl is stored in
148 the TREE_VALUE slot and the initializer is stored
149 in the TREE_PURPOSE slot. */
150 tree static_aggregates;
152 /* Like static_aggregates, but for thread_local variables. */
153 tree tls_aggregates;
155 /* A hash-map mapping from variable decls to the dynamic initializer for
156 the decl. This is currently only used by OpenMP. */
157 decl_tree_map *dynamic_initializers;
159 /* -- end of C++ */
161 /* A node for the integer constant 2. */
163 tree integer_two_node;
165 /* vector of static decls. */
166 vec<tree, va_gc> *static_decls;
168 /* vector of keyed classes. */
169 vec<tree, va_gc> *keyed_classes;
171 /* Used only for jumps to as-yet undefined labels, since jumps to
172 defined labels can have their validity checked immediately. */
174 struct GTY((chain_next ("%h.next"))) named_label_use_entry {
175 struct named_label_use_entry *next;
176 /* The binding level to which this entry is *currently* attached.
177 This is initially the binding level in which the goto appeared,
178 but is modified as scopes are closed. */
179 cp_binding_level *binding_level;
180 /* The head of the names list that was current when the goto appeared,
181 or the inner scope popped. These are the decls that will *not* be
182 skipped when jumping to the label. */
183 tree names_in_scope;
184 /* If the use is a possible destination of a computed goto, a vec of decls
185 that aren't destroyed, filled in by poplevel_named_label_1. */
186 vec<tree,va_gc> *computed_goto;
187 /* The location of the goto, for error reporting. */
188 location_t o_goto_locus;
189 /* True if an OpenMP structured block scope has been closed since
190 the goto appeared. This means that the branch from the label will
191 illegally exit an OpenMP scope. */
192 bool in_omp_scope;
195 /* A list of all LABEL_DECLs in the function that have names. Here so
196 we can clear out their names' definitions at the end of the
197 function, and so we can check the validity of jumps to these labels. */
199 struct GTY((for_user)) named_label_entry {
201 tree name; /* Name of decl. */
203 tree label_decl; /* LABEL_DECL, unless deleted local label. */
205 named_label_entry *outer; /* Outer shadowed chain. */
207 /* The binding level to which the label is *currently* attached.
208 This is initially set to the binding level in which the label
209 is defined, but is modified as scopes are closed. */
210 cp_binding_level *binding_level;
212 /* The head of the names list that was current when the label was
213 defined, or the inner scope popped. These are the decls that will
214 be skipped when jumping to the label. */
215 tree names_in_scope;
217 /* A vector of all decls from all binding levels that would be
218 crossed by a backward branch to the label. */
219 vec<tree, va_gc> *bad_decls;
221 /* A list of uses of the label, before the label is defined. */
222 named_label_use_entry *uses;
224 /* True if we've seen &&label. Appalently we can't use TREE_ADDRESSABLE for
225 this, it has a more specific meaning for LABEL_DECL. */
226 bool addressed;
228 /* The following bits are set after the label is defined, and are
229 updated as scopes are popped. They indicate that a jump to the
230 label will illegally enter a scope of the given flavor. */
231 bool in_try_scope;
232 bool in_catch_scope;
233 bool in_omp_scope;
234 bool in_transaction_scope;
235 bool in_constexpr_if;
236 bool in_consteval_if;
237 bool in_stmt_expr;
240 #define named_labels cp_function_chain->x_named_labels
242 /* The number of function bodies which we are currently processing.
243 (Zero if we are at namespace scope, one inside the body of a
244 function, two inside the body of a function in a local class, etc.) */
245 int function_depth;
247 /* Whether the exception-specifier is part of a function type (i.e. C++17). */
248 bool flag_noexcept_type;
250 /* States indicating how grokdeclarator() should handle declspecs marked
251 with __attribute__((deprecated)). An object declared as
252 __attribute__((deprecated)) suppresses warnings of uses of other
253 deprecated items. */
254 enum deprecated_states deprecated_state = DEPRECATED_NORMAL;
257 /* A list of VAR_DECLs whose type was incomplete at the time the
258 variable was declared. */
260 struct GTY(()) incomplete_var {
261 tree decl;
262 tree incomplete_type;
266 static GTY(()) vec<incomplete_var, va_gc> *incomplete_vars;
268 /* Returns the kind of template specialization we are currently
269 processing, given that it's declaration contained N_CLASS_SCOPES
270 explicit scope qualifications. */
272 tmpl_spec_kind
273 current_tmpl_spec_kind (int n_class_scopes)
275 int n_template_parm_scopes = 0;
276 int seen_specialization_p = 0;
277 int innermost_specialization_p = 0;
278 cp_binding_level *b;
280 /* Scan through the template parameter scopes. */
281 for (b = current_binding_level;
282 b->kind == sk_template_parms;
283 b = b->level_chain)
285 /* If we see a specialization scope inside a parameter scope,
286 then something is wrong. That corresponds to a declaration
287 like:
289 template <class T> template <> ...
291 which is always invalid since [temp.expl.spec] forbids the
292 specialization of a class member template if the enclosing
293 class templates are not explicitly specialized as well. */
294 if (b->explicit_spec_p)
296 if (n_template_parm_scopes == 0)
297 innermost_specialization_p = 1;
298 else
299 seen_specialization_p = 1;
301 else if (seen_specialization_p == 1)
302 return tsk_invalid_member_spec;
304 ++n_template_parm_scopes;
307 /* Handle explicit instantiations. */
308 if (processing_explicit_instantiation)
310 if (n_template_parm_scopes != 0)
311 /* We've seen a template parameter list during an explicit
312 instantiation. For example:
314 template <class T> template void f(int);
316 This is erroneous. */
317 return tsk_invalid_expl_inst;
318 else
319 return tsk_expl_inst;
322 if (n_template_parm_scopes < n_class_scopes)
323 /* We've not seen enough template headers to match all the
324 specialized classes present. For example:
326 template <class T> void R<T>::S<T>::f(int);
328 This is invalid; there needs to be one set of template
329 parameters for each class. */
330 return tsk_insufficient_parms;
331 else if (n_template_parm_scopes == n_class_scopes)
332 /* We're processing a non-template declaration (even though it may
333 be a member of a template class.) For example:
335 template <class T> void S<T>::f(int);
337 The `class T' matches the `S<T>', leaving no template headers
338 corresponding to the `f'. */
339 return tsk_none;
340 else if (n_template_parm_scopes > n_class_scopes + 1)
341 /* We've got too many template headers. For example:
343 template <> template <class T> void f (T);
345 There need to be more enclosing classes. */
346 return tsk_excessive_parms;
347 else
348 /* This must be a template. It's of the form:
350 template <class T> template <class U> void S<T>::f(U);
352 This is a specialization if the innermost level was a
353 specialization; otherwise it's just a definition of the
354 template. */
355 return innermost_specialization_p ? tsk_expl_spec : tsk_template;
358 /* Exit the current scope. */
360 void
361 finish_scope (void)
363 poplevel (0, 0, 0);
366 /* When a label goes out of scope, check to see if that label was used
367 in a valid manner, and issue any appropriate warnings or errors. */
369 static void
370 check_label_used (tree label)
372 if (!processing_template_decl)
374 if (DECL_INITIAL (label) == NULL_TREE)
376 location_t location;
378 error ("label %q+D used but not defined", label);
379 location = input_location;
380 /* FIXME want (LOCATION_FILE (input_location), (line)0) */
381 /* Avoid crashing later. */
382 define_label (location, DECL_NAME (label));
384 else
385 warn_for_unused_label (label);
389 /* Helper function to sort named label entries in a vector by DECL_UID. */
391 static int
392 sort_labels (const void *a, const void *b)
394 tree label1 = *(tree const *) a;
395 tree label2 = *(tree const *) b;
397 /* DECL_UIDs can never be equal. */
398 return DECL_UID (label1) > DECL_UID (label2) ? -1 : +1;
401 /* At the end of a function, all labels declared within the function
402 go out of scope. BLOCK is the top-level block for the
403 function. */
405 static void
406 pop_labels (tree block)
408 if (!named_labels)
409 return;
411 /* We need to add the labels to the block chain, so debug
412 information is emitted. But, we want the order to be stable so
413 need to sort them first. Otherwise the debug output could be
414 randomly ordered. I guess it's mostly stable, unless the hash
415 table implementation changes. */
416 auto_vec<tree, 32> labels (named_labels->elements ());
417 hash_table<named_label_hash>::iterator end (named_labels->end ());
418 for (hash_table<named_label_hash>::iterator iter
419 (named_labels->begin ()); iter != end; ++iter)
421 named_label_entry *ent = *iter;
423 gcc_checking_assert (!ent->outer);
424 if (ent->label_decl)
425 labels.quick_push (ent->label_decl);
426 ggc_free (ent);
428 named_labels = NULL;
429 labels.qsort (sort_labels);
431 while (labels.length ())
433 tree label = labels.pop ();
435 DECL_CHAIN (label) = BLOCK_VARS (block);
436 BLOCK_VARS (block) = label;
438 check_label_used (label);
442 /* At the end of a block with local labels, restore the outer definition. */
444 static void
445 pop_local_label (tree id, tree label)
447 check_label_used (label);
448 named_label_entry **slot = named_labels->find_slot_with_hash
449 (id, IDENTIFIER_HASH_VALUE (id), NO_INSERT);
450 named_label_entry *ent = *slot;
452 if (ent->outer)
453 ent = ent->outer;
454 else
456 ent = ggc_cleared_alloc<named_label_entry> ();
457 ent->name = id;
459 *slot = ent;
462 /* The following two routines are used to interface to Objective-C++.
463 The binding level is purposely treated as an opaque type. */
465 void *
466 objc_get_current_scope (void)
468 return current_binding_level;
471 /* The following routine is used by the NeXT-style SJLJ exceptions;
472 variables get marked 'volatile' so as to not be clobbered by
473 _setjmp()/_longjmp() calls. All variables in the current scope,
474 as well as parent scopes up to (but not including) ENCLOSING_BLK
475 shall be thusly marked. */
477 void
478 objc_mark_locals_volatile (void *enclosing_blk)
480 cp_binding_level *scope;
482 for (scope = current_binding_level;
483 scope && scope != enclosing_blk;
484 scope = scope->level_chain)
486 tree decl;
488 for (decl = scope->names; decl; decl = TREE_CHAIN (decl))
489 objc_volatilize_decl (decl);
491 /* Do not climb up past the current function. */
492 if (scope->kind == sk_function_parms)
493 break;
497 /* True if B is the level for the condition of a constexpr if. */
499 static bool
500 level_for_constexpr_if (cp_binding_level *b)
502 return (b->kind == sk_cond && b->this_entity
503 && TREE_CODE (b->this_entity) == IF_STMT
504 && IF_STMT_CONSTEXPR_P (b->this_entity));
507 /* True if B is the level for the condition of a consteval if. */
509 static bool
510 level_for_consteval_if (cp_binding_level *b)
512 return (b->kind == sk_cond && b->this_entity
513 && TREE_CODE (b->this_entity) == IF_STMT
514 && IF_STMT_CONSTEVAL_P (b->this_entity));
517 /* Update data for defined and undefined labels when leaving a scope. */
520 poplevel_named_label_1 (named_label_entry **slot, cp_binding_level *bl)
522 named_label_entry *ent = *slot;
523 cp_binding_level *obl = bl->level_chain;
525 if (ent->binding_level == bl)
527 tree decl;
529 /* ENT->NAMES_IN_SCOPE may contain a mixture of DECLs and
530 TREE_LISTs representing OVERLOADs, so be careful. */
531 for (decl = ent->names_in_scope; decl; decl = (DECL_P (decl)
532 ? DECL_CHAIN (decl)
533 : TREE_CHAIN (decl)))
534 if (decl_jump_unsafe (decl))
535 vec_safe_push (ent->bad_decls, decl);
537 ent->binding_level = obl;
538 ent->names_in_scope = obl->names;
539 switch (bl->kind)
541 case sk_try:
542 ent->in_try_scope = true;
543 break;
544 case sk_catch:
545 ent->in_catch_scope = true;
546 break;
547 case sk_omp:
548 ent->in_omp_scope = true;
549 break;
550 case sk_transaction:
551 ent->in_transaction_scope = true;
552 break;
553 case sk_stmt_expr:
554 ent->in_stmt_expr = true;
555 break;
556 case sk_block:
557 if (level_for_constexpr_if (bl->level_chain))
558 ent->in_constexpr_if = true;
559 else if (level_for_consteval_if (bl->level_chain))
560 ent->in_consteval_if = true;
561 break;
562 default:
563 break;
566 else if (ent->uses)
568 struct named_label_use_entry *use;
570 for (use = ent->uses; use ; use = use->next)
571 if (use->binding_level == bl)
573 if (auto &cg = use->computed_goto)
575 if (bl->kind == sk_catch)
576 vec_safe_push (cg, get_identifier ("catch"));
577 for (tree d = use->names_in_scope; d; d = DECL_CHAIN (d))
578 if (TREE_CODE (d) == VAR_DECL && !TREE_STATIC (d)
579 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (d)))
580 vec_safe_push (cg, d);
583 use->binding_level = obl;
584 use->names_in_scope = obl->names;
585 if (bl->kind == sk_omp)
586 use->in_omp_scope = true;
590 return 1;
593 /* Saved errorcount to avoid -Wunused-but-set-{parameter,variable} warnings
594 when errors were reported, except for -Werror-unused-but-set-*. */
595 static int unused_but_set_errorcount;
597 /* Exit a binding level.
598 Pop the level off, and restore the state of the identifier-decl mappings
599 that were in effect when this level was entered.
601 If KEEP == 1, this level had explicit declarations, so
602 and create a "block" (a BLOCK node) for the level
603 to record its declarations and subblocks for symbol table output.
605 If FUNCTIONBODY is nonzero, this level is the body of a function,
606 so create a block as if KEEP were set and also clear out all
607 label names.
609 If REVERSE is nonzero, reverse the order of decls before putting
610 them into the BLOCK. */
612 tree
613 poplevel (int keep, int reverse, int functionbody)
615 tree link;
616 /* The chain of decls was accumulated in reverse order.
617 Put it into forward order, just for cleanliness. */
618 tree decls;
619 tree subblocks;
620 tree block;
621 tree decl;
622 scope_kind kind;
624 auto_cond_timevar tv (TV_NAME_LOOKUP);
625 restart:
627 block = NULL_TREE;
629 gcc_assert (current_binding_level->kind != sk_class
630 && current_binding_level->kind != sk_namespace);
632 if (current_binding_level->kind == sk_cleanup)
633 functionbody = 0;
634 subblocks = functionbody >= 0 ? current_binding_level->blocks : 0;
636 gcc_assert (!vec_safe_length (current_binding_level->class_shadowed));
638 /* We used to use KEEP == 2 to indicate that the new block should go
639 at the beginning of the list of blocks at this binding level,
640 rather than the end. This hack is no longer used. */
641 gcc_assert (keep == 0 || keep == 1);
643 if (current_binding_level->keep)
644 keep = 1;
646 /* Any uses of undefined labels, and any defined labels, now operate
647 under constraints of next binding contour. */
648 if (cfun && !functionbody && named_labels)
649 named_labels->traverse<cp_binding_level *, poplevel_named_label_1>
650 (current_binding_level);
652 /* Get the decls in the order they were written.
653 Usually current_binding_level->names is in reverse order.
654 But parameter decls were previously put in forward order. */
656 decls = current_binding_level->names;
657 if (reverse)
659 decls = nreverse (decls);
660 current_binding_level->names = decls;
663 /* If there were any declarations or structure tags in that level,
664 or if this level is a function body,
665 create a BLOCK to record them for the life of this function. */
666 block = NULL_TREE;
667 /* Avoid function body block if possible. */
668 if (functionbody && subblocks && BLOCK_CHAIN (subblocks) == NULL_TREE)
669 keep = 0;
670 else if (keep == 1 || functionbody)
671 block = make_node (BLOCK);
672 if (block != NULL_TREE)
674 BLOCK_VARS (block) = decls;
675 BLOCK_SUBBLOCKS (block) = subblocks;
678 /* In each subblock, record that this is its superior. */
679 if (keep >= 0)
680 for (link = subblocks; link; link = BLOCK_CHAIN (link))
681 BLOCK_SUPERCONTEXT (link) = block;
683 /* Before we remove the declarations first check for unused variables. */
684 if ((warn_unused_variable || warn_unused_but_set_variable)
685 && current_binding_level->kind != sk_template_parms
686 && !processing_template_decl)
687 for (tree d = get_local_decls (); d; d = TREE_CHAIN (d))
689 /* There are cases where D itself is a TREE_LIST. See in
690 push_local_binding where the list of decls returned by
691 getdecls is built. */
692 decl = TREE_CODE (d) == TREE_LIST ? TREE_VALUE (d) : d;
694 tree type = TREE_TYPE (decl);
695 if (VAR_P (decl)
696 && (! TREE_USED (decl) || !DECL_READ_P (decl))
697 && ! DECL_IN_SYSTEM_HEADER (decl)
698 /* For structured bindings, consider only real variables, not
699 subobjects. */
700 && (DECL_DECOMPOSITION_P (decl) ? !DECL_DECOMP_BASE (decl)
701 : (DECL_NAME (decl) && !DECL_ARTIFICIAL (decl)))
702 /* Don't warn about name-independent declarations. */
703 && !name_independent_decl_p (decl)
704 && type != error_mark_node
705 && (!CLASS_TYPE_P (type)
706 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
707 || lookup_attribute ("warn_unused",
708 TYPE_ATTRIBUTES (TREE_TYPE (decl)))))
710 if (! TREE_USED (decl))
712 if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
713 warning_at (DECL_SOURCE_LOCATION (decl),
714 OPT_Wunused_variable,
715 "unused structured binding declaration");
716 else
717 warning_at (DECL_SOURCE_LOCATION (decl),
718 OPT_Wunused_variable, "unused variable %qD", decl);
719 suppress_warning (decl, OPT_Wunused_variable);
721 else if (DECL_CONTEXT (decl) == current_function_decl
722 // For -Wunused-but-set-variable leave references alone.
723 && !TYPE_REF_P (TREE_TYPE (decl))
724 && errorcount == unused_but_set_errorcount)
726 if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
727 warning_at (DECL_SOURCE_LOCATION (decl),
728 OPT_Wunused_but_set_variable, "structured "
729 "binding declaration set but not used");
730 else
731 warning_at (DECL_SOURCE_LOCATION (decl),
732 OPT_Wunused_but_set_variable,
733 "variable %qD set but not used", decl);
734 unused_but_set_errorcount = errorcount;
739 /* Remove declarations for all the DECLs in this level. */
740 for (link = decls; link; link = TREE_CHAIN (link))
742 tree name;
743 if (TREE_CODE (link) == TREE_LIST)
745 decl = TREE_VALUE (link);
746 name = TREE_PURPOSE (link);
747 gcc_checking_assert (name);
749 else
751 decl = link;
752 name = DECL_NAME (decl);
755 /* Remove the binding. */
756 if (TREE_CODE (decl) == LABEL_DECL)
757 pop_local_label (name, decl);
758 else
759 pop_local_binding (name, decl);
762 /* Restore the IDENTIFIER_TYPE_VALUEs. */
763 for (link = current_binding_level->type_shadowed;
764 link; link = TREE_CHAIN (link))
765 SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (link), TREE_VALUE (link));
767 /* There may be OVERLOADs (wrapped in TREE_LISTs) on the BLOCK_VARs
768 list if a `using' declaration put them there. The debugging
769 back ends won't understand OVERLOAD, so we remove them here.
770 Because the BLOCK_VARS are (temporarily) shared with
771 CURRENT_BINDING_LEVEL->NAMES we must do this fixup after we have
772 popped all the bindings. Also remove undeduced 'auto' decls,
773 which LTO doesn't understand, and can't have been used by anything. */
774 if (block)
776 tree* d;
778 for (d = &BLOCK_VARS (block); *d; )
780 if (TREE_CODE (*d) == TREE_LIST
781 || (!processing_template_decl
782 && undeduced_auto_decl (*d)))
783 *d = TREE_CHAIN (*d);
784 else
785 d = &DECL_CHAIN (*d);
789 /* If the level being exited is the top level of a function,
790 check over all the labels. */
791 if (functionbody)
793 if (block)
795 /* Since this is the top level block of a function, the vars are
796 the function's parameters. Don't leave them in the BLOCK
797 because they are found in the FUNCTION_DECL instead. */
798 BLOCK_VARS (block) = 0;
799 pop_labels (block);
801 else
802 pop_labels (subblocks);
805 kind = current_binding_level->kind;
806 if (kind == sk_cleanup)
808 tree stmt;
810 /* If this is a temporary binding created for a cleanup, then we'll
811 have pushed a statement list level. Pop that, create a new
812 BIND_EXPR for the block, and insert it into the stream. */
813 stmt = pop_stmt_list (current_binding_level->statement_list);
814 stmt = c_build_bind_expr (input_location, block, stmt);
815 add_stmt (stmt);
818 leave_scope ();
819 if (functionbody)
821 /* The current function is being defined, so its DECL_INITIAL
822 should be error_mark_node. */
823 gcc_assert (DECL_INITIAL (current_function_decl) == error_mark_node);
824 DECL_INITIAL (current_function_decl) = block ? block : subblocks;
825 if (subblocks)
827 if (FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
829 if (BLOCK_SUBBLOCKS (subblocks))
830 BLOCK_OUTER_CURLY_BRACE_P (BLOCK_SUBBLOCKS (subblocks)) = 1;
832 else
833 BLOCK_OUTER_CURLY_BRACE_P (subblocks) = 1;
836 else if (block)
837 current_binding_level->blocks
838 = block_chainon (current_binding_level->blocks, block);
840 /* If we did not make a block for the level just exited,
841 any blocks made for inner levels
842 (since they cannot be recorded as subblocks in that level)
843 must be carried forward so they will later become subblocks
844 of something else. */
845 else if (subblocks)
846 current_binding_level->blocks
847 = block_chainon (current_binding_level->blocks, subblocks);
849 /* Each and every BLOCK node created here in `poplevel' is important
850 (e.g. for proper debugging information) so if we created one
851 earlier, mark it as "used". */
852 if (block)
853 TREE_USED (block) = 1;
855 /* All temporary bindings created for cleanups are popped silently. */
856 if (kind == sk_cleanup)
857 goto restart;
859 return block;
862 /* Call wrapup_globals_declarations for the globals in NAMESPACE. */
863 /* Diagnose odr-used extern inline variables without definitions
864 in the current TU. */
867 wrapup_namespace_globals ()
869 if (vec<tree, va_gc> *statics = static_decls)
871 for (tree decl : *statics)
873 if (warn_unused_function
874 && TREE_CODE (decl) == FUNCTION_DECL
875 && DECL_INITIAL (decl) == 0
876 && DECL_EXTERNAL (decl)
877 && !TREE_PUBLIC (decl)
878 && !DECL_ARTIFICIAL (decl)
879 && !DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
880 && !warning_suppressed_p (decl, OPT_Wunused_function))
881 warning_at (DECL_SOURCE_LOCATION (decl),
882 OPT_Wunused_function,
883 "%qF declared %<static%> but never defined", decl);
885 if (VAR_P (decl)
886 && DECL_EXTERNAL (decl)
887 && DECL_INLINE_VAR_P (decl)
888 && DECL_ODR_USED (decl))
889 error_at (DECL_SOURCE_LOCATION (decl),
890 "odr-used inline variable %qD is not defined", decl);
893 /* Clear out the list, so we don't rescan next time. */
894 static_decls = NULL;
896 /* Write out any globals that need to be output. */
897 return wrapup_global_declarations (statics->address (),
898 statics->length ());
900 return 0;
903 /* In C++, you don't have to write `struct S' to refer to `S'; you
904 can just use `S'. We accomplish this by creating a TYPE_DECL as
905 if the user had written `typedef struct S S'. Create and return
906 the TYPE_DECL for TYPE. */
908 tree
909 create_implicit_typedef (tree name, tree type)
911 tree decl;
913 decl = build_decl (input_location, TYPE_DECL, name, type);
914 DECL_ARTIFICIAL (decl) = 1;
915 /* There are other implicit type declarations, like the one *within*
916 a class that allows you to write `S::S'. We must distinguish
917 amongst these. */
918 SET_DECL_IMPLICIT_TYPEDEF_P (decl);
919 TYPE_NAME (type) = decl;
920 TYPE_STUB_DECL (type) = decl;
922 return decl;
925 /* Function-scope local entities that need discriminators. Each entry
926 is a {decl,name} pair. VAR_DECLs for anon unions get their name
927 smashed, so we cannot rely on DECL_NAME. */
929 static GTY((deletable)) vec<tree, va_gc> *local_entities;
931 /* Determine the mangling discriminator of local DECL. There are
932 generally very few of these in any particular function. */
934 void
935 determine_local_discriminator (tree decl, tree name)
937 auto_cond_timevar tv (TV_NAME_LOOKUP);
938 retrofit_lang_decl (decl);
939 tree ctx = DECL_CONTEXT (decl);
940 size_t nelts = vec_safe_length (local_entities);
941 if (name == NULL_TREE)
942 name = (TREE_CODE (decl) == TYPE_DECL
943 && TYPE_UNNAMED_P (TREE_TYPE (decl))
944 ? NULL_TREE : DECL_NAME (decl));
945 for (size_t i = 0; i < nelts; i += 2)
947 tree *pair = &(*local_entities)[i];
948 tree d = pair[0];
949 tree n = pair[1];
950 gcc_checking_assert (d != decl);
951 if (name == n
952 && TREE_CODE (decl) == TREE_CODE (d)
953 && ctx == DECL_CONTEXT (d))
955 tree disc = integer_one_node;
956 if (DECL_DISCRIMINATOR (d))
957 disc = build_int_cst (TREE_TYPE (disc),
958 TREE_INT_CST_LOW (DECL_DISCRIMINATOR (d)) + 1);
959 DECL_DISCRIMINATOR (decl) = disc;
960 /* Replace the saved decl. */
961 pair[0] = decl;
962 decl = NULL_TREE;
963 break;
967 if (decl)
969 vec_safe_reserve (local_entities, 2);
970 local_entities->quick_push (decl);
971 local_entities->quick_push (name);
976 /* True if DECL is a constrained hidden friend as per [temp.friend]/9:
978 A non-template friend declaration with a requires-clause shall be a
979 definition. A friend function template with a constraint that depends on a
980 template parameter from an enclosing template shall be a definition. Such a
981 constrained friend function or function template declaration does not
982 declare the same function or function template as a declaration in any other
983 scope.
985 The ABI calls this a "member-like constrained friend" and mangles it like a
986 member function to avoid collisions. */
988 bool
989 member_like_constrained_friend_p (tree decl)
991 return (TREE_CODE (decl) == FUNCTION_DECL
992 && DECL_UNIQUE_FRIEND_P (decl)
993 && DECL_FRIEND_CONTEXT (decl)
994 && get_constraints (decl)
995 && (!DECL_TEMPLATE_INFO (decl)
996 || !PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl))
997 || (uses_outer_template_parms_in_constraints
998 (most_general_template (decl)))));
1001 /* Returns true if functions FN1 and FN2 have equivalent trailing
1002 requires clauses. */
1004 static bool
1005 function_requirements_equivalent_p (tree newfn, tree oldfn)
1007 /* In the concepts TS, the combined constraints are compared. */
1008 if (cxx_dialect < cxx20)
1010 tree ci1 = get_constraints (oldfn);
1011 tree ci2 = get_constraints (newfn);
1012 tree req1 = ci1 ? CI_ASSOCIATED_CONSTRAINTS (ci1) : NULL_TREE;
1013 tree req2 = ci2 ? CI_ASSOCIATED_CONSTRAINTS (ci2) : NULL_TREE;
1014 return cp_tree_equal (req1, req2);
1017 /* [temp.friend]/9 "Such a constrained friend function does not declare the
1018 same function as a declaration in any other scope." So no need to
1019 actually compare the requirements. */
1020 if (member_like_constrained_friend_p (newfn)
1021 || member_like_constrained_friend_p (oldfn))
1022 return false;
1024 /* Compare only trailing requirements. */
1025 tree reqs1 = get_trailing_function_requirements (newfn);
1026 tree reqs2 = get_trailing_function_requirements (oldfn);
1027 if ((reqs1 != NULL_TREE) != (reqs2 != NULL_TREE))
1028 return false;
1030 /* Substitution is needed when friends are involved. */
1031 reqs1 = maybe_substitute_reqs_for (reqs1, newfn);
1032 reqs2 = maybe_substitute_reqs_for (reqs2, oldfn);
1034 return cp_tree_equal (reqs1, reqs2);
1037 /* Two functions of the same name correspond [basic.scope.scope] if
1039 + both declare functions with the same non-object-parameter-type-list,
1040 equivalent ([temp.over.link]) trailing requires-clauses (if any, except as
1041 specified in [temp.friend]), and, if both are non-static members, they have
1042 corresponding object parameters, or
1044 + both declare function templates with equivalent
1045 non-object-parameter-type-lists, return types (if any), template-heads, and
1046 trailing requires-clauses (if any), and, if both are non-static members,
1047 they have corresponding object parameters.
1049 This is a subset of decls_match: it identifies declarations that cannot be
1050 overloaded with one another. This function does not consider DECL_NAME. */
1052 bool
1053 fns_correspond (tree newdecl, tree olddecl)
1055 if (TREE_CODE (newdecl) != TREE_CODE (olddecl))
1056 return false;
1058 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1060 if (!template_heads_equivalent_p (newdecl, olddecl))
1061 return 0;
1062 newdecl = DECL_TEMPLATE_RESULT (newdecl);
1063 olddecl = DECL_TEMPLATE_RESULT (olddecl);
1066 tree f1 = TREE_TYPE (newdecl);
1067 tree f2 = TREE_TYPE (olddecl);
1069 int rq1 = type_memfn_rqual (f1);
1070 int rq2 = type_memfn_rqual (f2);
1072 /* If only one is a non-static member function, ignore ref-quals. */
1073 if (TREE_CODE (f1) != TREE_CODE (f2))
1074 rq1 = rq2;
1075 /* Two non-static member functions have corresponding object parameters if:
1076 + exactly one is an implicit object member function with no ref-qualifier
1077 and the types of their object parameters ([dcl.fct]), after removing
1078 top-level references, are the same, or
1079 + their object parameters have the same type. */
1080 /* ??? We treat member functions of different classes as corresponding even
1081 though that means the object parameters have different types. */
1082 else if ((rq1 == REF_QUAL_NONE) != (rq2 == REF_QUAL_NONE))
1083 rq1 = rq2;
1085 bool types_match = rq1 == rq2;
1087 if (types_match)
1089 tree p1 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1090 tree p2 = FUNCTION_FIRST_USER_PARMTYPE (olddecl);
1091 types_match = compparms (p1, p2);
1094 /* Two function declarations match if either has a requires-clause
1095 then both have a requires-clause and their constraints-expressions
1096 are equivalent. */
1097 if (types_match && flag_concepts)
1098 types_match = function_requirements_equivalent_p (newdecl, olddecl);
1100 return types_match;
1103 /* Subroutine of duplicate_decls: return truthvalue of whether
1104 or not types of these decls match.
1106 For C++, we must compare the parameter list so that `int' can match
1107 `int&' in a parameter position, but `int&' is not confused with
1108 `const int&'. */
1111 decls_match (tree newdecl, tree olddecl, bool record_versions /* = true */)
1113 int types_match;
1115 if (newdecl == olddecl)
1116 return 1;
1118 if (TREE_CODE (newdecl) != TREE_CODE (olddecl))
1119 /* If the two DECLs are not even the same kind of thing, we're not
1120 interested in their types. */
1121 return 0;
1123 gcc_assert (DECL_P (newdecl));
1125 if (TREE_CODE (newdecl) == FUNCTION_DECL)
1127 /* Specializations of different templates are different functions
1128 even if they have the same type. */
1129 tree t1 = (DECL_USE_TEMPLATE (newdecl)
1130 ? DECL_TI_TEMPLATE (newdecl)
1131 : NULL_TREE);
1132 tree t2 = (DECL_USE_TEMPLATE (olddecl)
1133 ? DECL_TI_TEMPLATE (olddecl)
1134 : NULL_TREE);
1135 if (t1 != t2)
1136 return 0;
1138 if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1139 && ! (DECL_EXTERN_C_P (newdecl)
1140 && DECL_EXTERN_C_P (olddecl)))
1141 return 0;
1143 /* A new declaration doesn't match a built-in one unless it
1144 is also extern "C". */
1145 if (DECL_IS_UNDECLARED_BUILTIN (olddecl)
1146 && DECL_EXTERN_C_P (olddecl) && !DECL_EXTERN_C_P (newdecl))
1147 return 0;
1149 tree f1 = TREE_TYPE (newdecl);
1150 tree f2 = TREE_TYPE (olddecl);
1151 if (TREE_CODE (f1) != TREE_CODE (f2))
1152 return 0;
1154 /* A declaration with deduced return type should use its pre-deduction
1155 type for declaration matching. */
1156 tree r2 = fndecl_declared_return_type (olddecl);
1157 tree r1 = fndecl_declared_return_type (newdecl);
1159 tree p1 = TYPE_ARG_TYPES (f1);
1160 tree p2 = TYPE_ARG_TYPES (f2);
1162 if (same_type_p (r1, r2))
1164 if (!prototype_p (f2) && DECL_EXTERN_C_P (olddecl)
1165 && fndecl_built_in_p (olddecl))
1167 types_match = self_promoting_args_p (p1);
1168 if (p1 == void_list_node)
1169 TREE_TYPE (newdecl) = TREE_TYPE (olddecl);
1171 else
1172 types_match =
1173 compparms (p1, p2)
1174 && type_memfn_rqual (f1) == type_memfn_rqual (f2)
1175 && (TYPE_ATTRIBUTES (TREE_TYPE (newdecl)) == NULL_TREE
1176 || comp_type_attributes (TREE_TYPE (newdecl),
1177 TREE_TYPE (olddecl)) != 0);
1179 else
1180 types_match = 0;
1182 /* Two function declarations match if either has a requires-clause
1183 then both have a requires-clause and their constraints-expressions
1184 are equivalent. */
1185 if (types_match && flag_concepts)
1186 types_match = function_requirements_equivalent_p (newdecl, olddecl);
1188 /* The decls dont match if they correspond to two different versions
1189 of the same function. Disallow extern "C" functions to be
1190 versions for now. */
1191 if (types_match
1192 && !DECL_EXTERN_C_P (newdecl)
1193 && !DECL_EXTERN_C_P (olddecl)
1194 && targetm.target_option.function_versions (newdecl, olddecl))
1196 if (record_versions)
1197 maybe_version_functions (newdecl, olddecl,
1198 (!DECL_FUNCTION_VERSIONED (newdecl)
1199 || !DECL_FUNCTION_VERSIONED (olddecl)));
1200 return 0;
1203 else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1205 if (!template_heads_equivalent_p (newdecl, olddecl))
1206 return 0;
1208 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1209 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1211 if (TREE_CODE (newres) != TREE_CODE (oldres))
1212 return 0;
1214 /* Two template types match if they are the same. Otherwise, compare
1215 the underlying declarations. */
1216 if (TREE_CODE (newres) == TYPE_DECL)
1217 types_match = same_type_p (TREE_TYPE (newres), TREE_TYPE (oldres));
1218 else
1219 types_match = decls_match (newres, oldres);
1221 else
1223 /* Need to check scope for variable declaration (VAR_DECL).
1224 For typedef (TYPE_DECL), scope is ignored. */
1225 if (VAR_P (newdecl)
1226 && CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1227 /* [dcl.link]
1228 Two declarations for an object with C language linkage
1229 with the same name (ignoring the namespace that qualify
1230 it) that appear in different namespace scopes refer to
1231 the same object. */
1232 && !(DECL_EXTERN_C_P (olddecl) && DECL_EXTERN_C_P (newdecl)))
1233 return 0;
1235 if (TREE_TYPE (newdecl) == error_mark_node)
1236 types_match = TREE_TYPE (olddecl) == error_mark_node;
1237 else if (TREE_TYPE (olddecl) == NULL_TREE)
1238 types_match = TREE_TYPE (newdecl) == NULL_TREE;
1239 else if (TREE_TYPE (newdecl) == NULL_TREE)
1240 types_match = 0;
1241 else
1242 types_match = comptypes (TREE_TYPE (newdecl),
1243 TREE_TYPE (olddecl),
1244 COMPARE_REDECLARATION);
1247 return types_match;
1250 /* Mark DECL as versioned if it isn't already. */
1252 static void
1253 maybe_mark_function_versioned (tree decl)
1255 if (!DECL_FUNCTION_VERSIONED (decl))
1257 DECL_FUNCTION_VERSIONED (decl) = 1;
1258 /* If DECL_ASSEMBLER_NAME has already been set, re-mangle
1259 to include the version marker. */
1260 if (DECL_ASSEMBLER_NAME_SET_P (decl))
1261 mangle_decl (decl);
1265 /* NEWDECL and OLDDECL have identical signatures. If they are
1266 different versions adjust them and return true.
1267 If RECORD is set to true, record function versions. */
1269 bool
1270 maybe_version_functions (tree newdecl, tree olddecl, bool record)
1272 if (!targetm.target_option.function_versions (newdecl, olddecl))
1273 return false;
1275 maybe_mark_function_versioned (olddecl);
1276 if (DECL_LOCAL_DECL_P (olddecl))
1278 olddecl = DECL_LOCAL_DECL_ALIAS (olddecl);
1279 maybe_mark_function_versioned (olddecl);
1282 maybe_mark_function_versioned (newdecl);
1283 if (DECL_LOCAL_DECL_P (newdecl))
1285 /* Unfortunately, we can get here before pushdecl naturally calls
1286 push_local_extern_decl_alias, so we need to call it directly. */
1287 if (!DECL_LOCAL_DECL_ALIAS (newdecl))
1288 push_local_extern_decl_alias (newdecl);
1289 newdecl = DECL_LOCAL_DECL_ALIAS (newdecl);
1290 maybe_mark_function_versioned (newdecl);
1293 if (record)
1294 cgraph_node::record_function_versions (olddecl, newdecl);
1296 return true;
1299 /* If NEWDECL is `static' and an `extern' was seen previously,
1300 warn about it. OLDDECL is the previous declaration.
1302 Note that this does not apply to the C++ case of declaring
1303 a variable `extern const' and then later `const'.
1305 Don't complain about built-in functions, since they are beyond
1306 the user's control. */
1308 void
1309 warn_extern_redeclared_static (tree newdecl, tree olddecl)
1311 if (TREE_CODE (newdecl) == TYPE_DECL
1312 || TREE_CODE (newdecl) == TEMPLATE_DECL
1313 || TREE_CODE (newdecl) == CONST_DECL
1314 || TREE_CODE (newdecl) == NAMESPACE_DECL)
1315 return;
1317 /* Don't get confused by static member functions; that's a different
1318 use of `static'. */
1319 if (TREE_CODE (newdecl) == FUNCTION_DECL
1320 && DECL_STATIC_FUNCTION_P (newdecl))
1321 return;
1323 /* If the old declaration was `static', or the new one isn't, then
1324 everything is OK. */
1325 if (DECL_THIS_STATIC (olddecl) || !DECL_THIS_STATIC (newdecl))
1326 return;
1328 /* It's OK to declare a builtin function as `static'. */
1329 if (TREE_CODE (olddecl) == FUNCTION_DECL
1330 && DECL_ARTIFICIAL (olddecl))
1331 return;
1333 auto_diagnostic_group d;
1334 if (permerror (DECL_SOURCE_LOCATION (newdecl),
1335 "%qD was declared %<extern%> and later %<static%>", newdecl))
1336 inform (DECL_SOURCE_LOCATION (olddecl),
1337 "previous declaration of %qD", olddecl);
1340 /* NEW_DECL is a redeclaration of OLD_DECL; both are functions or
1341 function templates. If their exception specifications do not
1342 match, issue a diagnostic. */
1344 static void
1345 check_redeclaration_exception_specification (tree new_decl,
1346 tree old_decl)
1348 tree new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1349 tree old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1351 /* Two default specs are equivalent, don't force evaluation. */
1352 if (UNEVALUATED_NOEXCEPT_SPEC_P (new_exceptions)
1353 && UNEVALUATED_NOEXCEPT_SPEC_P (old_exceptions))
1354 return;
1356 if (!type_dependent_expression_p (old_decl))
1358 maybe_instantiate_noexcept (new_decl);
1359 maybe_instantiate_noexcept (old_decl);
1361 new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1362 old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1364 /* [except.spec]
1366 If any declaration of a function has an exception-specification,
1367 all declarations, including the definition and an explicit
1368 specialization, of that function shall have an
1369 exception-specification with the same set of type-ids. */
1370 if (!DECL_IS_UNDECLARED_BUILTIN (old_decl)
1371 && !DECL_IS_UNDECLARED_BUILTIN (new_decl)
1372 && !comp_except_specs (new_exceptions, old_exceptions, ce_normal))
1374 const char *const msg
1375 = G_("declaration of %qF has a different exception specifier");
1376 bool complained = true;
1377 location_t new_loc = DECL_SOURCE_LOCATION (new_decl);
1378 auto_diagnostic_group d;
1379 if (DECL_IN_SYSTEM_HEADER (old_decl))
1380 complained = pedwarn (new_loc, OPT_Wsystem_headers, msg, new_decl);
1381 else if (!flag_exceptions)
1382 /* We used to silently permit mismatched eh specs with
1383 -fno-exceptions, so make them a pedwarn now. */
1384 complained = pedwarn (new_loc, OPT_Wpedantic, msg, new_decl);
1385 else
1386 error_at (new_loc, msg, new_decl);
1387 if (complained)
1388 inform (DECL_SOURCE_LOCATION (old_decl),
1389 "from previous declaration %qF", old_decl);
1393 /* Return true if OLD_DECL and NEW_DECL agree on constexprness.
1394 Otherwise issue diagnostics. */
1396 static bool
1397 validate_constexpr_redeclaration (tree old_decl, tree new_decl)
1399 old_decl = STRIP_TEMPLATE (old_decl);
1400 new_decl = STRIP_TEMPLATE (new_decl);
1401 if (!VAR_OR_FUNCTION_DECL_P (old_decl)
1402 || !VAR_OR_FUNCTION_DECL_P (new_decl))
1403 return true;
1404 if (DECL_DECLARED_CONSTEXPR_P (old_decl)
1405 == DECL_DECLARED_CONSTEXPR_P (new_decl))
1407 if (TREE_CODE (old_decl) != FUNCTION_DECL)
1408 return true;
1409 if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1410 == DECL_IMMEDIATE_FUNCTION_P (new_decl))
1411 return true;
1413 if (TREE_CODE (old_decl) == FUNCTION_DECL)
1415 /* With -fimplicit-constexpr, ignore changes in the constexpr
1416 keyword. */
1417 if (flag_implicit_constexpr
1418 && (DECL_IMMEDIATE_FUNCTION_P (new_decl)
1419 == DECL_IMMEDIATE_FUNCTION_P (old_decl)))
1420 return true;
1421 if (fndecl_built_in_p (old_decl))
1423 /* Hide a built-in declaration. */
1424 DECL_DECLARED_CONSTEXPR_P (old_decl)
1425 = DECL_DECLARED_CONSTEXPR_P (new_decl);
1426 if (DECL_IMMEDIATE_FUNCTION_P (new_decl))
1427 SET_DECL_IMMEDIATE_FUNCTION_P (old_decl);
1428 return true;
1430 /* 7.1.5 [dcl.constexpr]
1431 Note: An explicit specialization can differ from the template
1432 declaration with respect to the constexpr specifier. */
1433 if (! DECL_TEMPLATE_SPECIALIZATION (old_decl)
1434 && DECL_TEMPLATE_SPECIALIZATION (new_decl))
1435 return true;
1437 const char *kind = "constexpr";
1438 if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1439 || DECL_IMMEDIATE_FUNCTION_P (new_decl))
1440 kind = "consteval";
1441 error_at (DECL_SOURCE_LOCATION (new_decl),
1442 "redeclaration %qD differs in %qs "
1443 "from previous declaration", new_decl,
1444 kind);
1445 inform (DECL_SOURCE_LOCATION (old_decl),
1446 "previous declaration %qD", old_decl);
1447 return false;
1449 return true;
1452 // If OLDDECL and NEWDECL are concept declarations with the same type
1453 // (i.e., and template parameters), but different requirements,
1454 // emit diagnostics and return true. Otherwise, return false.
1455 static inline bool
1456 check_concept_refinement (tree olddecl, tree newdecl)
1458 if (!DECL_DECLARED_CONCEPT_P (olddecl) || !DECL_DECLARED_CONCEPT_P (newdecl))
1459 return false;
1461 tree d1 = DECL_TEMPLATE_RESULT (olddecl);
1462 tree d2 = DECL_TEMPLATE_RESULT (newdecl);
1463 if (TREE_CODE (d1) != TREE_CODE (d2))
1464 return false;
1466 tree t1 = TREE_TYPE (d1);
1467 tree t2 = TREE_TYPE (d2);
1468 if (TREE_CODE (d1) == FUNCTION_DECL)
1470 if (compparms (TYPE_ARG_TYPES (t1), TYPE_ARG_TYPES (t2))
1471 && comp_template_parms (DECL_TEMPLATE_PARMS (olddecl),
1472 DECL_TEMPLATE_PARMS (newdecl))
1473 && !equivalently_constrained (olddecl, newdecl))
1475 error ("cannot specialize concept %q#D", olddecl);
1476 return true;
1479 return false;
1482 /* DECL is a redeclaration of a function or function template. If
1483 it does have default arguments issue a diagnostic. Note: this
1484 function is used to enforce the requirements in C++11 8.3.6 about
1485 no default arguments in redeclarations. */
1487 static void
1488 check_redeclaration_no_default_args (tree decl)
1490 gcc_assert (DECL_DECLARES_FUNCTION_P (decl));
1492 for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
1493 t && t != void_list_node; t = TREE_CHAIN (t))
1494 if (TREE_PURPOSE (t))
1496 permerror (DECL_SOURCE_LOCATION (decl),
1497 "redeclaration of %q#D may not have default "
1498 "arguments", decl);
1499 return;
1503 /* NEWDECL is a redeclaration of a function or function template OLDDECL,
1504 in any case represented as FUNCTION_DECLs (the DECL_TEMPLATE_RESULTs of
1505 the TEMPLATE_DECLs in case of function templates). This function is used
1506 to enforce the final part of C++17 11.3.6/4, about a single declaration:
1507 "If a friend declaration specifies a default argument expression, that
1508 declaration shall be a definition and shall be the only declaration of
1509 the function or function template in the translation unit." */
1511 static void
1512 check_no_redeclaration_friend_default_args (tree olddecl, tree newdecl)
1514 if (!DECL_UNIQUE_FRIEND_P (olddecl) && !DECL_UNIQUE_FRIEND_P (newdecl))
1515 return;
1517 for (tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl),
1518 t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1519 t1 && t1 != void_list_node;
1520 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1521 if ((DECL_UNIQUE_FRIEND_P (olddecl) && TREE_PURPOSE (t1))
1522 || (DECL_UNIQUE_FRIEND_P (newdecl) && TREE_PURPOSE (t2)))
1524 auto_diagnostic_group d;
1525 if (permerror (DECL_SOURCE_LOCATION (newdecl),
1526 "friend declaration of %q#D specifies default "
1527 "arguments and isn%'t the only declaration", newdecl))
1528 inform (DECL_SOURCE_LOCATION (olddecl),
1529 "previous declaration of %q#D", olddecl);
1530 return;
1534 /* Merge tree bits that correspond to attributes noreturn, nothrow,
1535 const, malloc, and pure from NEWDECL with those of OLDDECL. */
1537 static void
1538 merge_attribute_bits (tree newdecl, tree olddecl)
1540 TREE_THIS_VOLATILE (newdecl) |= TREE_THIS_VOLATILE (olddecl);
1541 TREE_THIS_VOLATILE (olddecl) |= TREE_THIS_VOLATILE (newdecl);
1542 TREE_NOTHROW (newdecl) |= TREE_NOTHROW (olddecl);
1543 TREE_NOTHROW (olddecl) |= TREE_NOTHROW (newdecl);
1544 TREE_READONLY (newdecl) |= TREE_READONLY (olddecl);
1545 TREE_READONLY (olddecl) |= TREE_READONLY (newdecl);
1546 DECL_IS_MALLOC (newdecl) |= DECL_IS_MALLOC (olddecl);
1547 DECL_IS_MALLOC (olddecl) |= DECL_IS_MALLOC (newdecl);
1548 DECL_PURE_P (newdecl) |= DECL_PURE_P (olddecl);
1549 DECL_PURE_P (olddecl) |= DECL_PURE_P (newdecl);
1550 DECL_UNINLINABLE (newdecl) |= DECL_UNINLINABLE (olddecl);
1551 DECL_UNINLINABLE (olddecl) |= DECL_UNINLINABLE (newdecl);
1552 TREE_DEPRECATED (newdecl) |= TREE_DEPRECATED (olddecl);
1553 TREE_DEPRECATED (olddecl) |= TREE_DEPRECATED (newdecl);
1554 TREE_UNAVAILABLE (newdecl) |= TREE_UNAVAILABLE (olddecl);
1555 TREE_UNAVAILABLE (olddecl) |= TREE_UNAVAILABLE (newdecl);
1558 #define GNU_INLINE_P(fn) (DECL_DECLARED_INLINE_P (fn) \
1559 && lookup_attribute ("gnu_inline", \
1560 DECL_ATTRIBUTES (fn)))
1562 /* A subroutine of duplicate_decls. Emits a diagnostic when newdecl
1563 ambiguates olddecl. Returns true if an error occurs. */
1565 static bool
1566 duplicate_function_template_decls (tree newdecl, tree olddecl)
1568 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1569 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1570 /* Function template declarations can be differentiated by parameter
1571 and return type. */
1572 if (compparms (TYPE_ARG_TYPES (TREE_TYPE (oldres)),
1573 TYPE_ARG_TYPES (TREE_TYPE (newres)))
1574 && same_type_p (TREE_TYPE (TREE_TYPE (newdecl)),
1575 TREE_TYPE (TREE_TYPE (olddecl))))
1577 /* ... and also by their template-heads and requires-clauses. */
1578 if (template_heads_equivalent_p (newdecl, olddecl)
1579 && function_requirements_equivalent_p (newres, oldres))
1581 error ("ambiguating new declaration %q+#D", newdecl);
1582 inform (DECL_SOURCE_LOCATION (olddecl),
1583 "old declaration %q#D", olddecl);
1584 return true;
1587 /* FIXME: The types are the same but the are differences
1588 in either the template heads or function requirements.
1589 We should be able to diagnose a set of common errors
1590 stemming from these declarations. For example:
1592 template<typename T> requires C void f(...);
1593 template<typename T> void f(...) requires C;
1595 These are functionally equivalent but not equivalent. */
1598 return false;
1601 /* OLD_PARMS is the innermost set of template parameters for some template
1602 declaration, and NEW_PARMS is the corresponding set of template parameters
1603 for a redeclaration of that template. Merge the default arguments within
1604 these two sets of parameters. CLASS_P is true iff the template in
1605 question is a class template. */
1607 bool
1608 merge_default_template_args (tree new_parms, tree old_parms, bool class_p)
1610 gcc_checking_assert (TREE_VEC_LENGTH (new_parms)
1611 == TREE_VEC_LENGTH (old_parms));
1612 for (int i = 0; i < TREE_VEC_LENGTH (new_parms); i++)
1614 tree new_parm = TREE_VALUE (TREE_VEC_ELT (new_parms, i));
1615 tree old_parm = TREE_VALUE (TREE_VEC_ELT (old_parms, i));
1616 tree& new_default = TREE_PURPOSE (TREE_VEC_ELT (new_parms, i));
1617 tree& old_default = TREE_PURPOSE (TREE_VEC_ELT (old_parms, i));
1618 if (error_operand_p (new_parm) || error_operand_p (old_parm))
1619 return false;
1620 if (new_default != NULL_TREE && old_default != NULL_TREE)
1622 auto_diagnostic_group d;
1623 error ("redefinition of default argument for %q+#D", new_parm);
1624 inform (DECL_SOURCE_LOCATION (old_parm),
1625 "original definition appeared here");
1626 return false;
1628 else if (new_default != NULL_TREE)
1629 /* Update the previous template parameters (which are the ones
1630 that will really count) with the new default value. */
1631 old_default = new_default;
1632 else if (class_p && old_default != NULL_TREE)
1633 /* Update the new parameters, too; they'll be used as the
1634 parameters for any members. */
1635 new_default = old_default;
1637 return true;
1640 /* If NEWDECL is a redeclaration of OLDDECL, merge the declarations.
1641 If the redeclaration is invalid, a diagnostic is issued, and the
1642 error_mark_node is returned. Otherwise, OLDDECL is returned.
1644 If NEWDECL is not a redeclaration of OLDDECL, NULL_TREE is
1645 returned.
1647 HIDING is true if the new decl is being hidden. WAS_HIDDEN is true
1648 if the old decl was hidden.
1650 Hidden decls can be anticipated builtins, injected friends, or
1651 (coming soon) injected from a local-extern decl. */
1653 tree
1654 duplicate_decls (tree newdecl, tree olddecl, bool hiding, bool was_hidden)
1656 unsigned olddecl_uid = DECL_UID (olddecl);
1657 int types_match = 0;
1658 int new_defines_function = 0;
1659 tree new_template_info;
1660 location_t olddecl_loc = DECL_SOURCE_LOCATION (olddecl);
1661 location_t newdecl_loc = DECL_SOURCE_LOCATION (newdecl);
1663 if (newdecl == olddecl)
1664 return olddecl;
1666 types_match = decls_match (newdecl, olddecl);
1668 /* If either the type of the new decl or the type of the old decl is an
1669 error_mark_node, then that implies that we have already issued an
1670 error (earlier) for some bogus type specification, and in that case,
1671 it is rather pointless to harass the user with yet more error message
1672 about the same declaration, so just pretend the types match here. */
1673 if (TREE_TYPE (newdecl) == error_mark_node
1674 || TREE_TYPE (olddecl) == error_mark_node)
1675 return error_mark_node;
1677 /* Check for redeclaration and other discrepancies. */
1678 if (TREE_CODE (olddecl) == FUNCTION_DECL
1679 && DECL_IS_UNDECLARED_BUILTIN (olddecl))
1681 if (TREE_CODE (newdecl) != FUNCTION_DECL)
1683 /* Avoid warnings redeclaring built-ins which have not been
1684 explicitly declared. */
1685 if (was_hidden)
1687 if (TREE_PUBLIC (newdecl)
1688 && CP_DECL_CONTEXT (newdecl) == global_namespace)
1689 warning_at (newdecl_loc,
1690 OPT_Wbuiltin_declaration_mismatch,
1691 "built-in function %qD declared as non-function",
1692 newdecl);
1693 return NULL_TREE;
1696 /* If you declare a built-in or predefined function name as static,
1697 the old definition is overridden, but optionally warn this was a
1698 bad choice of name. */
1699 if (! TREE_PUBLIC (newdecl))
1701 warning_at (newdecl_loc,
1702 OPT_Wshadow,
1703 fndecl_built_in_p (olddecl)
1704 ? G_("shadowing built-in function %q#D")
1705 : G_("shadowing library function %q#D"), olddecl);
1706 /* Discard the old built-in function. */
1707 return NULL_TREE;
1709 /* If the built-in is not ansi, then programs can override
1710 it even globally without an error. */
1711 else if (! fndecl_built_in_p (olddecl))
1712 warning_at (newdecl_loc, 0,
1713 "library function %q#D redeclared as non-function %q#D",
1714 olddecl, newdecl);
1715 else
1716 error_at (newdecl_loc,
1717 "declaration of %q#D conflicts with built-in "
1718 "declaration %q#D", newdecl, olddecl);
1719 return NULL_TREE;
1721 else if (!types_match)
1723 /* Avoid warnings redeclaring built-ins which have not been
1724 explicitly declared. */
1725 if (was_hidden)
1727 tree t1, t2;
1729 /* A new declaration doesn't match a built-in one unless it
1730 is also extern "C". */
1731 gcc_assert (DECL_IS_UNDECLARED_BUILTIN (olddecl));
1732 gcc_assert (DECL_EXTERN_C_P (olddecl));
1733 if (!DECL_EXTERN_C_P (newdecl))
1734 return NULL_TREE;
1736 for (t1 = TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1737 t2 = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1738 t1 || t2;
1739 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1741 if (!t1 || !t2)
1742 break;
1743 /* FILE, tm types are not known at the time
1744 we create the builtins. */
1745 for (unsigned i = 0;
1746 i < sizeof (builtin_structptr_types)
1747 / sizeof (builtin_structptr_type);
1748 ++i)
1749 if (TREE_VALUE (t2) == builtin_structptr_types[i].node)
1751 tree t = TREE_VALUE (t1);
1753 if (TYPE_PTR_P (t)
1754 && TYPE_IDENTIFIER (TREE_TYPE (t))
1755 == get_identifier (builtin_structptr_types[i].str)
1756 && compparms (TREE_CHAIN (t1), TREE_CHAIN (t2)))
1758 tree oldargs = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1760 TYPE_ARG_TYPES (TREE_TYPE (olddecl))
1761 = TYPE_ARG_TYPES (TREE_TYPE (newdecl));
1762 types_match = decls_match (newdecl, olddecl);
1763 if (types_match)
1764 return duplicate_decls (newdecl, olddecl,
1765 hiding, was_hidden);
1766 TYPE_ARG_TYPES (TREE_TYPE (olddecl)) = oldargs;
1768 goto next_arg;
1771 if (! same_type_p (TREE_VALUE (t1), TREE_VALUE (t2)))
1772 break;
1773 next_arg:;
1776 warning_at (newdecl_loc,
1777 OPT_Wbuiltin_declaration_mismatch,
1778 "declaration of %q#D conflicts with built-in "
1779 "declaration %q#D", newdecl, olddecl);
1781 else if ((DECL_EXTERN_C_P (newdecl)
1782 && DECL_EXTERN_C_P (olddecl))
1783 || compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1784 TYPE_ARG_TYPES (TREE_TYPE (olddecl))))
1786 /* Don't really override olddecl for __* prefixed builtins
1787 except for __[^b]*_chk, the compiler might be using those
1788 explicitly. */
1789 if (fndecl_built_in_p (olddecl))
1791 tree id = DECL_NAME (olddecl);
1792 const char *name = IDENTIFIER_POINTER (id);
1793 size_t len;
1795 if (name[0] == '_'
1796 && name[1] == '_'
1797 && (startswith (name + 2, "builtin_")
1798 || (len = strlen (name)) <= strlen ("___chk")
1799 || memcmp (name + len - strlen ("_chk"),
1800 "_chk", strlen ("_chk") + 1) != 0))
1802 if (DECL_INITIAL (newdecl))
1804 error_at (newdecl_loc,
1805 "definition of %q#D ambiguates built-in "
1806 "declaration %q#D", newdecl, olddecl);
1807 return error_mark_node;
1809 auto_diagnostic_group d;
1810 if (permerror (newdecl_loc,
1811 "new declaration %q#D ambiguates built-in"
1812 " declaration %q#D", newdecl, olddecl)
1813 && flag_permissive)
1814 inform (newdecl_loc,
1815 "ignoring the %q#D declaration", newdecl);
1816 return flag_permissive ? olddecl : error_mark_node;
1820 /* A near match; override the builtin. */
1822 if (TREE_PUBLIC (newdecl))
1823 warning_at (newdecl_loc,
1824 OPT_Wbuiltin_declaration_mismatch,
1825 "new declaration %q#D ambiguates built-in "
1826 "declaration %q#D", newdecl, olddecl);
1827 else
1828 warning (OPT_Wshadow,
1829 fndecl_built_in_p (olddecl)
1830 ? G_("shadowing built-in function %q#D")
1831 : G_("shadowing library function %q#D"), olddecl);
1833 else
1834 /* Discard the old built-in function. */
1835 return NULL_TREE;
1837 /* Replace the old RTL to avoid problems with inlining. */
1838 COPY_DECL_RTL (newdecl, olddecl);
1840 else
1842 /* Even if the types match, prefer the new declarations type
1843 for built-ins which have not been explicitly declared,
1844 for exception lists, etc... */
1845 tree type = TREE_TYPE (newdecl);
1846 tree attribs = (*targetm.merge_type_attributes)
1847 (TREE_TYPE (olddecl), type);
1849 type = cp_build_type_attribute_variant (type, attribs);
1850 TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = type;
1853 /* If a function is explicitly declared "throw ()", propagate that to
1854 the corresponding builtin. */
1855 if (DECL_BUILT_IN_CLASS (olddecl) == BUILT_IN_NORMAL
1856 && was_hidden
1857 && TREE_NOTHROW (newdecl)
1858 && !TREE_NOTHROW (olddecl))
1860 enum built_in_function fncode = DECL_FUNCTION_CODE (olddecl);
1861 tree tmpdecl = builtin_decl_explicit (fncode);
1862 if (tmpdecl && tmpdecl != olddecl && types_match)
1863 TREE_NOTHROW (tmpdecl) = 1;
1866 /* Whether or not the builtin can throw exceptions has no
1867 bearing on this declarator. */
1868 TREE_NOTHROW (olddecl) = 0;
1870 if (DECL_THIS_STATIC (newdecl) && !DECL_THIS_STATIC (olddecl))
1872 /* If a builtin function is redeclared as `static', merge
1873 the declarations, but make the original one static. */
1874 DECL_THIS_STATIC (olddecl) = 1;
1875 TREE_PUBLIC (olddecl) = 0;
1877 /* Make the old declaration consistent with the new one so
1878 that all remnants of the builtin-ness of this function
1879 will be banished. */
1880 SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
1881 COPY_DECL_RTL (newdecl, olddecl);
1884 else if (TREE_CODE (olddecl) != TREE_CODE (newdecl))
1886 /* C++ Standard, 3.3, clause 4:
1887 "[Note: a namespace name or a class template name must be unique
1888 in its declarative region (7.3.2, clause 14). ]" */
1889 if (TREE_CODE (olddecl) == NAMESPACE_DECL
1890 || TREE_CODE (newdecl) == NAMESPACE_DECL)
1891 /* Namespace conflicts with not namespace. */;
1892 else if (DECL_TYPE_TEMPLATE_P (olddecl)
1893 || DECL_TYPE_TEMPLATE_P (newdecl))
1894 /* Class template conflicts. */;
1895 else if ((TREE_CODE (olddecl) == TEMPLATE_DECL
1896 && DECL_TEMPLATE_RESULT (olddecl)
1897 && TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)) == VAR_DECL)
1898 || (TREE_CODE (newdecl) == TEMPLATE_DECL
1899 && DECL_TEMPLATE_RESULT (newdecl)
1900 && TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == VAR_DECL))
1901 /* Variable template conflicts. */;
1902 else if (concept_definition_p (olddecl)
1903 || concept_definition_p (newdecl))
1904 /* Concept conflicts. */;
1905 else if ((TREE_CODE (newdecl) == FUNCTION_DECL
1906 && DECL_FUNCTION_TEMPLATE_P (olddecl))
1907 || (TREE_CODE (olddecl) == FUNCTION_DECL
1908 && DECL_FUNCTION_TEMPLATE_P (newdecl)))
1910 /* One is a function and the other is a template
1911 function. */
1912 if (!UDLIT_OPER_P (DECL_NAME (newdecl)))
1913 return NULL_TREE;
1915 /* There can only be one! */
1916 if (TREE_CODE (newdecl) == TEMPLATE_DECL
1917 && check_raw_literal_operator (olddecl))
1918 error_at (newdecl_loc,
1919 "literal operator %q#D conflicts with"
1920 " raw literal operator", newdecl);
1921 else if (check_raw_literal_operator (newdecl))
1922 error_at (newdecl_loc,
1923 "raw literal operator %q#D conflicts with"
1924 " literal operator template", newdecl);
1925 else
1926 return NULL_TREE;
1928 inform (olddecl_loc, "previous declaration %q#D", olddecl);
1929 return error_mark_node;
1931 else if ((VAR_P (olddecl) && DECL_DECOMPOSITION_P (olddecl))
1932 || (VAR_P (newdecl) && DECL_DECOMPOSITION_P (newdecl)))
1933 /* A structured binding must be unique in its declarative region. */;
1934 else if (DECL_IMPLICIT_TYPEDEF_P (olddecl)
1935 || DECL_IMPLICIT_TYPEDEF_P (newdecl))
1936 /* One is an implicit typedef, that's ok. */
1937 return NULL_TREE;
1939 error ("%q#D redeclared as different kind of entity", newdecl);
1940 inform (olddecl_loc, "previous declaration %q#D", olddecl);
1942 return error_mark_node;
1944 else if (!types_match)
1946 if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl))
1947 /* These are certainly not duplicate declarations; they're
1948 from different scopes. */
1949 return NULL_TREE;
1951 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1953 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1954 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1956 /* The name of a class template may not be declared to refer to
1957 any other template, class, function, object, namespace, value,
1958 or type in the same scope. */
1959 if (TREE_CODE (oldres) == TYPE_DECL
1960 || TREE_CODE (newres) == TYPE_DECL)
1962 error_at (newdecl_loc,
1963 "conflicting declaration of template %q#D", newdecl);
1964 inform (olddecl_loc,
1965 "previous declaration %q#D", olddecl);
1966 return error_mark_node;
1969 else if (TREE_CODE (oldres) == FUNCTION_DECL
1970 && TREE_CODE (newres) == FUNCTION_DECL)
1972 if (duplicate_function_template_decls (newdecl, olddecl))
1973 return error_mark_node;
1974 return NULL_TREE;
1976 else if (check_concept_refinement (olddecl, newdecl))
1977 return error_mark_node;
1978 return NULL_TREE;
1980 if (TREE_CODE (newdecl) == FUNCTION_DECL)
1982 if (DECL_EXTERN_C_P (newdecl) && DECL_EXTERN_C_P (olddecl))
1984 error_at (newdecl_loc,
1985 "conflicting declaration of C function %q#D",
1986 newdecl);
1987 inform (olddecl_loc,
1988 "previous declaration %q#D", olddecl);
1989 return error_mark_node;
1991 /* For function versions, params and types match, but they
1992 are not ambiguous. */
1993 else if ((!DECL_FUNCTION_VERSIONED (newdecl)
1994 && !DECL_FUNCTION_VERSIONED (olddecl))
1995 /* Let constrained hidden friends coexist for now, we'll
1996 check satisfaction later. */
1997 && !member_like_constrained_friend_p (newdecl)
1998 && !member_like_constrained_friend_p (olddecl)
1999 // The functions have the same parameter types.
2000 && compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
2001 TYPE_ARG_TYPES (TREE_TYPE (olddecl)))
2002 // And the same constraints.
2003 && equivalently_constrained (newdecl, olddecl))
2005 error_at (newdecl_loc,
2006 "ambiguating new declaration of %q#D", newdecl);
2007 inform (olddecl_loc,
2008 "old declaration %q#D", olddecl);
2009 return error_mark_node;
2011 else
2012 return NULL_TREE;
2014 else
2016 error_at (newdecl_loc, "conflicting declaration %q#D", newdecl);
2017 inform (olddecl_loc,
2018 "previous declaration as %q#D", olddecl);
2019 return error_mark_node;
2022 else if (TREE_CODE (newdecl) == FUNCTION_DECL
2023 && DECL_OMP_DECLARE_REDUCTION_P (newdecl))
2025 /* OMP UDRs are never duplicates. */
2026 gcc_assert (DECL_OMP_DECLARE_REDUCTION_P (olddecl));
2027 error_at (newdecl_loc,
2028 "redeclaration of %<pragma omp declare reduction%>");
2029 inform (olddecl_loc,
2030 "previous %<pragma omp declare reduction%> declaration");
2031 return error_mark_node;
2033 else if (TREE_CODE (newdecl) == FUNCTION_DECL
2034 && ((DECL_TEMPLATE_SPECIALIZATION (olddecl)
2035 && (!DECL_TEMPLATE_INFO (newdecl)
2036 || (DECL_TI_TEMPLATE (newdecl)
2037 != DECL_TI_TEMPLATE (olddecl))))
2038 || (DECL_TEMPLATE_SPECIALIZATION (newdecl)
2039 && (!DECL_TEMPLATE_INFO (olddecl)
2040 || (DECL_TI_TEMPLATE (olddecl)
2041 != DECL_TI_TEMPLATE (newdecl))))))
2042 /* It's OK to have a template specialization and a non-template
2043 with the same type, or to have specializations of two
2044 different templates with the same type. Note that if one is a
2045 specialization, and the other is an instantiation of the same
2046 template, that we do not exit at this point. That situation
2047 can occur if we instantiate a template class, and then
2048 specialize one of its methods. This situation is valid, but
2049 the declarations must be merged in the usual way. */
2050 return NULL_TREE;
2051 else if (TREE_CODE (newdecl) == FUNCTION_DECL
2052 && ((DECL_TEMPLATE_INSTANTIATION (olddecl)
2053 && !DECL_USE_TEMPLATE (newdecl))
2054 || (DECL_TEMPLATE_INSTANTIATION (newdecl)
2055 && !DECL_USE_TEMPLATE (olddecl))))
2056 /* One of the declarations is a template instantiation, and the
2057 other is not a template at all. That's OK. */
2058 return NULL_TREE;
2059 else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
2061 /* In [namespace.alias] we have:
2063 In a declarative region, a namespace-alias-definition can be
2064 used to redefine a namespace-alias declared in that declarative
2065 region to refer only to the namespace to which it already
2066 refers.
2068 Therefore, if we encounter a second alias directive for the same
2069 alias, we can just ignore the second directive. */
2070 if (DECL_NAMESPACE_ALIAS (newdecl)
2071 && (DECL_NAMESPACE_ALIAS (newdecl)
2072 == DECL_NAMESPACE_ALIAS (olddecl)))
2073 return olddecl;
2075 /* Leave it to update_binding to merge or report error. */
2076 return NULL_TREE;
2078 else
2080 const char *errmsg = redeclaration_error_message (newdecl, olddecl);
2081 if (errmsg)
2083 auto_diagnostic_group d;
2084 error_at (newdecl_loc, errmsg, newdecl);
2085 if (DECL_NAME (olddecl) != NULL_TREE)
2086 inform (olddecl_loc,
2087 (DECL_INITIAL (olddecl) && namespace_bindings_p ())
2088 ? G_("%q#D previously defined here")
2089 : G_("%q#D previously declared here"), olddecl);
2090 if (cxx_dialect >= cxx26
2091 && DECL_NAME (newdecl)
2092 && id_equal (DECL_NAME (newdecl), "_")
2093 && !name_independent_decl_p (newdecl))
2095 if (TREE_CODE (newdecl) == PARM_DECL)
2096 inform (newdecl_loc,
2097 "parameter declaration is not name-independent");
2098 else if (DECL_DECOMPOSITION_P (newdecl))
2100 if (at_namespace_scope_p ())
2101 inform (newdecl_loc,
2102 "structured binding at namespace scope is not "
2103 "name-independent");
2104 else if (TREE_STATIC (newdecl))
2105 inform (newdecl_loc,
2106 "static structured binding is not "
2107 "name-independent");
2108 else if (DECL_EXTERNAL (newdecl))
2109 inform (newdecl_loc,
2110 "extern structured binding is not "
2111 "name-independent");
2113 else if (at_class_scope_p ()
2114 && VAR_P (newdecl)
2115 && TREE_STATIC (newdecl))
2116 inform (newdecl_loc,
2117 "static data member is not name-independent");
2118 else if (VAR_P (newdecl) && at_namespace_scope_p ())
2119 inform (newdecl_loc,
2120 "variable at namespace scope is not name-independent");
2121 else if (VAR_P (newdecl) && TREE_STATIC (newdecl))
2122 inform (newdecl_loc,
2123 "static variable is not name-independent");
2124 else if (VAR_P (newdecl) && DECL_EXTERNAL (newdecl))
2125 inform (newdecl_loc,
2126 "extern variable is not name-independent");
2128 return error_mark_node;
2130 else if (TREE_CODE (olddecl) == FUNCTION_DECL
2131 && DECL_INITIAL (olddecl) != NULL_TREE
2132 && !prototype_p (TREE_TYPE (olddecl))
2133 && prototype_p (TREE_TYPE (newdecl)))
2135 /* Prototype decl follows defn w/o prototype. */
2136 auto_diagnostic_group d;
2137 if (warning_at (newdecl_loc, 0,
2138 "prototype specified for %q#D", newdecl))
2139 inform (olddecl_loc,
2140 "previous non-prototype definition here");
2142 else if (VAR_OR_FUNCTION_DECL_P (olddecl)
2143 && DECL_LANGUAGE (newdecl) != DECL_LANGUAGE (olddecl))
2145 /* [dcl.link]
2146 If two declarations of the same function or object
2147 specify different linkage-specifications ..., the program
2148 is ill-formed.... Except for functions with C++ linkage,
2149 a function declaration without a linkage specification
2150 shall not precede the first linkage specification for
2151 that function. A function can be declared without a
2152 linkage specification after an explicit linkage
2153 specification has been seen; the linkage explicitly
2154 specified in the earlier declaration is not affected by
2155 such a function declaration.
2157 DR 563 raises the question why the restrictions on
2158 functions should not also apply to objects. Older
2159 versions of G++ silently ignore the linkage-specification
2160 for this example:
2162 namespace N {
2163 extern int i;
2164 extern "C" int i;
2167 which is clearly wrong. Therefore, we now treat objects
2168 like functions. */
2169 if (current_lang_depth () == 0)
2171 /* There is no explicit linkage-specification, so we use
2172 the linkage from the previous declaration. */
2173 retrofit_lang_decl (newdecl);
2174 SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
2176 else
2178 auto_diagnostic_group d;
2179 error_at (newdecl_loc,
2180 "conflicting declaration of %q#D with %qL linkage",
2181 newdecl, DECL_LANGUAGE (newdecl));
2182 inform (olddecl_loc,
2183 "previous declaration with %qL linkage",
2184 DECL_LANGUAGE (olddecl));
2188 if (DECL_LANG_SPECIFIC (olddecl) && DECL_USE_TEMPLATE (olddecl))
2190 else if (TREE_CODE (olddecl) == FUNCTION_DECL)
2192 /* Note: free functions, as TEMPLATE_DECLs, are handled below. */
2193 if (DECL_FUNCTION_MEMBER_P (olddecl)
2194 && (/* grokfndecl passes member function templates too
2195 as FUNCTION_DECLs. */
2196 DECL_TEMPLATE_INFO (olddecl)
2197 /* C++11 8.3.6/6.
2198 Default arguments for a member function of a class
2199 template shall be specified on the initial declaration
2200 of the member function within the class template. */
2201 || CLASSTYPE_TEMPLATE_INFO (CP_DECL_CONTEXT (olddecl))))
2203 check_redeclaration_no_default_args (newdecl);
2205 if (DECL_TEMPLATE_INFO (olddecl)
2206 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (olddecl)))
2208 tree new_parms = DECL_TEMPLATE_INFO (newdecl)
2209 ? DECL_INNERMOST_TEMPLATE_PARMS (DECL_TI_TEMPLATE (newdecl))
2210 : INNERMOST_TEMPLATE_PARMS (current_template_parms);
2211 tree old_parms
2212 = DECL_INNERMOST_TEMPLATE_PARMS (DECL_TI_TEMPLATE (olddecl));
2213 merge_default_template_args (new_parms, old_parms,
2214 /*class_p=*/false);
2217 else
2219 tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl);
2220 tree t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
2221 int i = 1;
2223 for (; t1 && t1 != void_list_node;
2224 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2), i++)
2225 if (TREE_PURPOSE (t1) && TREE_PURPOSE (t2))
2227 if (simple_cst_equal (TREE_PURPOSE (t1),
2228 TREE_PURPOSE (t2)) == 1)
2230 auto_diagnostic_group d;
2231 if (permerror (newdecl_loc,
2232 "default argument given for parameter "
2233 "%d of %q#D", i, newdecl))
2234 inform (olddecl_loc,
2235 "previous specification in %q#D here",
2236 olddecl);
2238 else
2240 auto_diagnostic_group d;
2241 error_at (newdecl_loc,
2242 "default argument given for parameter %d "
2243 "of %q#D", i, newdecl);
2244 inform (olddecl_loc,
2245 "previous specification in %q#D here",
2246 olddecl);
2250 /* C++17 11.3.6/4: "If a friend declaration specifies a default
2251 argument expression, that declaration... shall be the only
2252 declaration of the function or function template in the
2253 translation unit." */
2254 check_no_redeclaration_friend_default_args (olddecl, newdecl);
2259 /* Do not merge an implicit typedef with an explicit one. In:
2261 class A;
2263 typedef class A A __attribute__ ((foo));
2265 the attribute should apply only to the typedef. */
2266 if (TREE_CODE (olddecl) == TYPE_DECL
2267 && (DECL_IMPLICIT_TYPEDEF_P (olddecl)
2268 || DECL_IMPLICIT_TYPEDEF_P (newdecl)))
2269 return NULL_TREE;
2271 if (DECL_TEMPLATE_PARM_P (olddecl) != DECL_TEMPLATE_PARM_P (newdecl))
2272 return NULL_TREE;
2274 if (!validate_constexpr_redeclaration (olddecl, newdecl))
2275 return error_mark_node;
2277 if (modules_p ()
2278 && TREE_CODE (CP_DECL_CONTEXT (olddecl)) == NAMESPACE_DECL
2279 && TREE_CODE (olddecl) != NAMESPACE_DECL
2280 && !hiding)
2282 if (!module_may_redeclare (olddecl))
2284 if (DECL_ARTIFICIAL (olddecl))
2285 error ("declaration %qD conflicts with builtin", newdecl);
2286 else
2288 error ("declaration %qD conflicts with import", newdecl);
2289 inform (olddecl_loc, "import declared %q#D here", olddecl);
2292 return error_mark_node;
2295 tree not_tmpl = STRIP_TEMPLATE (olddecl);
2296 if (DECL_LANG_SPECIFIC (not_tmpl)
2297 && DECL_MODULE_ATTACH_P (not_tmpl)
2298 /* Typedefs are not entities and so are OK to be redeclared
2299 as exported: see [module.interface]/p6. */
2300 && TREE_CODE (olddecl) != TYPE_DECL)
2302 if (DECL_MODULE_EXPORT_P (STRIP_TEMPLATE (newdecl))
2303 && !DECL_MODULE_EXPORT_P (not_tmpl))
2305 auto_diagnostic_group d;
2306 error ("conflicting exporting for declaration %qD", newdecl);
2307 inform (olddecl_loc,
2308 "previously declared here without exporting");
2311 else if (DECL_MODULE_EXPORT_P (newdecl))
2312 DECL_MODULE_EXPORT_P (not_tmpl) = true;
2315 /* We have committed to returning OLDDECL at this point. */
2317 /* If new decl is `static' and an `extern' was seen previously,
2318 warn about it. */
2319 warn_extern_redeclared_static (newdecl, olddecl);
2321 /* True to merge attributes between the declarations, false to
2322 set OLDDECL's attributes to those of NEWDECL (for template
2323 explicit specializations that specify their own attributes
2324 independent of those specified for the primary template). */
2325 const bool merge_attr = (TREE_CODE (newdecl) != FUNCTION_DECL
2326 || !DECL_TEMPLATE_SPECIALIZATION (newdecl)
2327 || DECL_TEMPLATE_SPECIALIZATION (olddecl));
2329 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2331 if (merge_attr)
2333 if (diagnose_mismatched_attributes (olddecl, newdecl))
2334 inform (olddecl_loc, DECL_INITIAL (olddecl)
2335 ? G_("previous definition of %qD here")
2336 : G_("previous declaration of %qD here"), olddecl);
2338 /* [dcl.attr.noreturn]: The first declaration of a function shall
2339 specify the noreturn attribute if any declaration of that function
2340 specifies the noreturn attribute. */
2341 tree a;
2342 if (TREE_THIS_VOLATILE (newdecl)
2343 && !TREE_THIS_VOLATILE (olddecl)
2344 /* This applies to [[noreturn]] only, not its GNU variants. */
2345 && (a = lookup_attribute ("noreturn", DECL_ATTRIBUTES (newdecl)))
2346 && cxx11_attribute_p (a)
2347 && get_attribute_namespace (a) == NULL_TREE)
2349 error_at (newdecl_loc, "function %qD declared %<[[noreturn]]%> "
2350 "but its first declaration was not", newdecl);
2351 inform (olddecl_loc, "previous declaration of %qD", olddecl);
2355 /* Now that functions must hold information normally held
2356 by field decls, there is extra work to do so that
2357 declaration information does not get destroyed during
2358 definition. */
2359 if (DECL_VINDEX (olddecl))
2360 DECL_VINDEX (newdecl) = DECL_VINDEX (olddecl);
2361 if (DECL_CONTEXT (olddecl))
2362 DECL_CONTEXT (newdecl) = DECL_CONTEXT (olddecl);
2363 DECL_STATIC_CONSTRUCTOR (newdecl) |= DECL_STATIC_CONSTRUCTOR (olddecl);
2364 DECL_STATIC_DESTRUCTOR (newdecl) |= DECL_STATIC_DESTRUCTOR (olddecl);
2365 DECL_PURE_VIRTUAL_P (newdecl) |= DECL_PURE_VIRTUAL_P (olddecl);
2366 DECL_VIRTUAL_P (newdecl) |= DECL_VIRTUAL_P (olddecl);
2367 DECL_INVALID_OVERRIDER_P (newdecl) |= DECL_INVALID_OVERRIDER_P (olddecl);
2368 DECL_FINAL_P (newdecl) |= DECL_FINAL_P (olddecl);
2369 DECL_OVERRIDE_P (newdecl) |= DECL_OVERRIDE_P (olddecl);
2370 DECL_THIS_STATIC (newdecl) |= DECL_THIS_STATIC (olddecl);
2371 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (newdecl)
2372 |= DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (olddecl);
2373 if (DECL_OVERLOADED_OPERATOR_P (olddecl))
2374 DECL_OVERLOADED_OPERATOR_CODE_RAW (newdecl)
2375 = DECL_OVERLOADED_OPERATOR_CODE_RAW (olddecl);
2376 new_defines_function = DECL_INITIAL (newdecl) != NULL_TREE;
2378 duplicate_contracts (newdecl, olddecl);
2380 /* Optionally warn about more than one declaration for the same
2381 name, but don't warn about a function declaration followed by a
2382 definition. */
2383 if (warn_redundant_decls && ! DECL_ARTIFICIAL (olddecl)
2384 && !(new_defines_function && DECL_INITIAL (olddecl) == NULL_TREE)
2385 /* Don't warn about extern decl followed by definition. */
2386 && !(DECL_EXTERNAL (olddecl) && ! DECL_EXTERNAL (newdecl))
2387 /* Don't warn if at least one is/was hidden. */
2388 && !(hiding || was_hidden)
2389 /* Don't warn about declaration followed by specialization. */
2390 && (! DECL_TEMPLATE_SPECIALIZATION (newdecl)
2391 || DECL_TEMPLATE_SPECIALIZATION (olddecl)))
2393 auto_diagnostic_group d;
2394 if (warning_at (newdecl_loc,
2395 OPT_Wredundant_decls,
2396 "redundant redeclaration of %qD in same scope",
2397 newdecl))
2398 inform (olddecl_loc,
2399 "previous declaration of %qD", olddecl);
2402 /* [dcl.fct.def.delete] A deleted definition of a function shall be the
2403 first declaration of the function or, for an explicit specialization
2404 of a function template, the first declaration of that
2405 specialization. */
2406 if (!(DECL_TEMPLATE_INSTANTIATION (olddecl)
2407 && DECL_TEMPLATE_SPECIALIZATION (newdecl)))
2409 if (DECL_DELETED_FN (newdecl))
2411 auto_diagnostic_group d;
2412 if (pedwarn (newdecl_loc, 0, "deleted definition of %qD "
2413 "is not first declaration", newdecl))
2414 inform (olddecl_loc,
2415 "previous declaration of %qD", olddecl);
2417 DECL_DELETED_FN (newdecl) |= DECL_DELETED_FN (olddecl);
2421 /* Deal with C++: must preserve virtual function table size. */
2422 if (TREE_CODE (olddecl) == TYPE_DECL)
2424 tree newtype = TREE_TYPE (newdecl);
2425 tree oldtype = TREE_TYPE (olddecl);
2427 if (newtype != error_mark_node && oldtype != error_mark_node
2428 && TYPE_LANG_SPECIFIC (newtype) && TYPE_LANG_SPECIFIC (oldtype))
2429 CLASSTYPE_FRIEND_CLASSES (newtype)
2430 = CLASSTYPE_FRIEND_CLASSES (oldtype);
2432 DECL_ORIGINAL_TYPE (newdecl) = DECL_ORIGINAL_TYPE (olddecl);
2435 /* Copy all the DECL_... slots specified in the new decl except for
2436 any that we copy here from the old type. */
2437 if (merge_attr)
2438 DECL_ATTRIBUTES (newdecl)
2439 = (*targetm.merge_decl_attributes) (olddecl, newdecl);
2440 else
2441 DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
2443 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
2445 tree old_result = DECL_TEMPLATE_RESULT (olddecl);
2446 tree new_result = DECL_TEMPLATE_RESULT (newdecl);
2447 TREE_TYPE (olddecl) = TREE_TYPE (old_result);
2449 /* The new decl should not already have gathered any
2450 specializations. */
2451 gcc_assert (!DECL_TEMPLATE_SPECIALIZATIONS (newdecl));
2453 /* Make sure the contracts are equivalent. */
2454 duplicate_contracts (newdecl, olddecl);
2456 /* Remove contracts from old_result so they aren't appended to
2457 old_result by the merge function. */
2458 remove_contract_attributes (old_result);
2460 DECL_ATTRIBUTES (old_result)
2461 = (*targetm.merge_decl_attributes) (old_result, new_result);
2463 if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2465 if (DECL_SOURCE_LOCATION (newdecl)
2466 != DECL_SOURCE_LOCATION (olddecl))
2468 /* Per C++11 8.3.6/4, default arguments cannot be added in
2469 later declarations of a function template. */
2470 check_redeclaration_no_default_args (newdecl);
2471 /* C++17 11.3.6/4: "If a friend declaration specifies a default
2472 argument expression, that declaration... shall be the only
2473 declaration of the function or function template in the
2474 translation unit." */
2475 check_no_redeclaration_friend_default_args
2476 (old_result, new_result);
2478 tree new_parms = DECL_INNERMOST_TEMPLATE_PARMS (newdecl);
2479 tree old_parms = DECL_INNERMOST_TEMPLATE_PARMS (olddecl);
2480 merge_default_template_args (new_parms, old_parms,
2481 /*class_p=*/false);
2483 if (!DECL_UNIQUE_FRIEND_P (new_result))
2484 DECL_UNIQUE_FRIEND_P (old_result) = false;
2486 check_default_args (newdecl);
2488 if (GNU_INLINE_P (old_result) != GNU_INLINE_P (new_result)
2489 && DECL_INITIAL (new_result))
2491 if (DECL_INITIAL (old_result))
2492 DECL_UNINLINABLE (old_result) = 1;
2493 else
2494 DECL_UNINLINABLE (old_result) = DECL_UNINLINABLE (new_result);
2495 DECL_EXTERNAL (old_result) = DECL_EXTERNAL (new_result);
2496 DECL_NOT_REALLY_EXTERN (old_result)
2497 = DECL_NOT_REALLY_EXTERN (new_result);
2498 DECL_INTERFACE_KNOWN (old_result)
2499 = DECL_INTERFACE_KNOWN (new_result);
2500 DECL_DECLARED_INLINE_P (old_result)
2501 = DECL_DECLARED_INLINE_P (new_result);
2502 DECL_DISREGARD_INLINE_LIMITS (old_result)
2503 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2505 else
2507 DECL_DECLARED_INLINE_P (old_result)
2508 |= DECL_DECLARED_INLINE_P (new_result);
2509 DECL_DISREGARD_INLINE_LIMITS (old_result)
2510 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2511 check_redeclaration_exception_specification (newdecl, olddecl);
2513 merge_attribute_bits (new_result, old_result);
2517 /* If the new declaration is a definition, update the file and
2518 line information on the declaration, and also make
2519 the old declaration the same definition. */
2520 if (DECL_INITIAL (new_result) != NULL_TREE)
2522 DECL_SOURCE_LOCATION (olddecl)
2523 = DECL_SOURCE_LOCATION (old_result)
2524 = DECL_SOURCE_LOCATION (newdecl);
2525 DECL_INITIAL (old_result) = DECL_INITIAL (new_result);
2526 if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2528 DECL_ARGUMENTS (old_result) = DECL_ARGUMENTS (new_result);
2529 for (tree p = DECL_ARGUMENTS (old_result); p; p = DECL_CHAIN (p))
2530 DECL_CONTEXT (p) = old_result;
2532 if (tree fc = DECL_FRIEND_CONTEXT (new_result))
2533 SET_DECL_FRIEND_CONTEXT (old_result, fc);
2537 return olddecl;
2540 if (types_match)
2542 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2543 check_redeclaration_exception_specification (newdecl, olddecl);
2545 /* Automatically handles default parameters. */
2546 tree oldtype = TREE_TYPE (olddecl);
2547 tree newtype;
2549 /* For typedefs use the old type, as the new type's DECL_NAME points
2550 at newdecl, which will be ggc_freed. */
2551 if (TREE_CODE (newdecl) == TYPE_DECL)
2553 /* But NEWTYPE might have an attribute, honor that. */
2554 tree tem = TREE_TYPE (newdecl);
2555 newtype = oldtype;
2557 if (TYPE_USER_ALIGN (tem))
2559 if (TYPE_ALIGN (tem) > TYPE_ALIGN (newtype))
2560 SET_TYPE_ALIGN (newtype, TYPE_ALIGN (tem));
2561 TYPE_USER_ALIGN (newtype) = true;
2564 /* And remove the new type from the variants list. */
2565 if (TYPE_NAME (TREE_TYPE (newdecl)) == newdecl)
2567 tree remove = TREE_TYPE (newdecl);
2568 if (TYPE_MAIN_VARIANT (remove) == remove)
2570 gcc_assert (TYPE_NEXT_VARIANT (remove) == NULL_TREE);
2571 /* If remove is the main variant, no need to remove that
2572 from the list. One of the DECL_ORIGINAL_TYPE
2573 variants, e.g. created for aligned attribute, might still
2574 refer to the newdecl TYPE_DECL though, so remove that one
2575 in that case. */
2576 if (tree orig = DECL_ORIGINAL_TYPE (newdecl))
2577 if (orig != remove)
2578 for (tree t = TYPE_MAIN_VARIANT (orig); t;
2579 t = TYPE_MAIN_VARIANT (t))
2580 if (TYPE_NAME (TYPE_NEXT_VARIANT (t)) == newdecl)
2582 TYPE_NEXT_VARIANT (t)
2583 = TYPE_NEXT_VARIANT (TYPE_NEXT_VARIANT (t));
2584 break;
2587 else
2588 for (tree t = TYPE_MAIN_VARIANT (remove); ;
2589 t = TYPE_NEXT_VARIANT (t))
2590 if (TYPE_NEXT_VARIANT (t) == remove)
2592 TYPE_NEXT_VARIANT (t) = TYPE_NEXT_VARIANT (remove);
2593 break;
2597 else if (merge_attr)
2598 newtype = merge_types (TREE_TYPE (newdecl), TREE_TYPE (olddecl));
2599 else
2600 newtype = TREE_TYPE (newdecl);
2602 if (VAR_P (newdecl))
2604 DECL_THIS_EXTERN (newdecl) |= DECL_THIS_EXTERN (olddecl);
2605 /* For already initialized vars, TREE_READONLY could have been
2606 cleared in cp_finish_decl, because the var needs runtime
2607 initialization or destruction. Make sure not to set
2608 TREE_READONLY on it again. */
2609 if (DECL_INITIALIZED_P (olddecl)
2610 && !DECL_EXTERNAL (olddecl)
2611 && !TREE_READONLY (olddecl))
2612 TREE_READONLY (newdecl) = 0;
2613 DECL_INITIALIZED_P (newdecl) |= DECL_INITIALIZED_P (olddecl);
2614 DECL_NONTRIVIALLY_INITIALIZED_P (newdecl)
2615 |= DECL_NONTRIVIALLY_INITIALIZED_P (olddecl);
2616 if (DECL_DEPENDENT_INIT_P (olddecl))
2617 SET_DECL_DEPENDENT_INIT_P (newdecl, true);
2618 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (newdecl)
2619 |= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (olddecl);
2620 DECL_DECLARED_CONSTEXPR_P (newdecl)
2621 |= DECL_DECLARED_CONSTEXPR_P (olddecl);
2622 DECL_DECLARED_CONSTINIT_P (newdecl)
2623 |= DECL_DECLARED_CONSTINIT_P (olddecl);
2625 /* Merge the threadprivate attribute from OLDDECL into NEWDECL. */
2626 if (DECL_LANG_SPECIFIC (olddecl)
2627 && CP_DECL_THREADPRIVATE_P (olddecl))
2629 /* Allocate a LANG_SPECIFIC structure for NEWDECL, if needed. */
2630 retrofit_lang_decl (newdecl);
2631 CP_DECL_THREADPRIVATE_P (newdecl) = 1;
2635 /* An explicit specialization of a function template or of a member
2636 function of a class template can be declared transaction_safe
2637 independently of whether the corresponding template entity is declared
2638 transaction_safe. */
2639 if (flag_tm && TREE_CODE (newdecl) == FUNCTION_DECL
2640 && DECL_TEMPLATE_INSTANTIATION (olddecl)
2641 && DECL_TEMPLATE_SPECIALIZATION (newdecl)
2642 && tx_safe_fn_type_p (newtype)
2643 && !tx_safe_fn_type_p (TREE_TYPE (newdecl)))
2644 newtype = tx_unsafe_fn_variant (newtype);
2646 TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = newtype;
2648 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2649 check_default_args (newdecl);
2651 /* Lay the type out, unless already done. */
2652 if (! same_type_p (newtype, oldtype)
2653 && TREE_TYPE (newdecl) != error_mark_node
2654 && !(processing_template_decl && uses_template_parms (newdecl)))
2655 layout_type (TREE_TYPE (newdecl));
2657 if ((VAR_P (newdecl)
2658 || TREE_CODE (newdecl) == PARM_DECL
2659 || TREE_CODE (newdecl) == RESULT_DECL
2660 || TREE_CODE (newdecl) == FIELD_DECL
2661 || TREE_CODE (newdecl) == TYPE_DECL)
2662 && !(processing_template_decl && uses_template_parms (newdecl)))
2663 layout_decl (newdecl, 0);
2665 /* Merge deprecatedness. */
2666 if (TREE_DEPRECATED (newdecl))
2667 TREE_DEPRECATED (olddecl) = 1;
2669 /* Merge unavailability. */
2670 if (TREE_UNAVAILABLE (newdecl))
2671 TREE_UNAVAILABLE (olddecl) = 1;
2673 /* Preserve function specific target and optimization options */
2674 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2676 if (DECL_FUNCTION_SPECIFIC_TARGET (olddecl)
2677 && !DECL_FUNCTION_SPECIFIC_TARGET (newdecl))
2678 DECL_FUNCTION_SPECIFIC_TARGET (newdecl)
2679 = DECL_FUNCTION_SPECIFIC_TARGET (olddecl);
2681 if (DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl)
2682 && !DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl))
2683 DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl)
2684 = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl);
2686 if (!DECL_UNIQUE_FRIEND_P (olddecl))
2687 DECL_UNIQUE_FRIEND_P (newdecl) = false;
2689 else
2691 /* Merge the const type qualifier. */
2692 if (TREE_READONLY (newdecl))
2693 TREE_READONLY (olddecl) = 1;
2694 /* Merge the volatile type qualifier. */
2695 if (TREE_THIS_VOLATILE (newdecl))
2696 TREE_THIS_VOLATILE (olddecl) = 1;
2699 /* Merge the initialization information. */
2700 if (DECL_INITIAL (newdecl) == NULL_TREE
2701 && DECL_INITIAL (olddecl) != NULL_TREE)
2703 DECL_INITIAL (newdecl) = DECL_INITIAL (olddecl);
2704 DECL_SOURCE_LOCATION (newdecl) = DECL_SOURCE_LOCATION (olddecl);
2705 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2707 DECL_SAVED_TREE (newdecl) = DECL_SAVED_TREE (olddecl);
2708 DECL_STRUCT_FUNCTION (newdecl) = DECL_STRUCT_FUNCTION (olddecl);
2712 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2714 DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (newdecl)
2715 |= DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (olddecl);
2716 DECL_NO_LIMIT_STACK (newdecl) |= DECL_NO_LIMIT_STACK (olddecl);
2717 if (DECL_IS_OPERATOR_NEW_P (olddecl))
2718 DECL_SET_IS_OPERATOR_NEW (newdecl, true);
2719 DECL_LOOPING_CONST_OR_PURE_P (newdecl)
2720 |= DECL_LOOPING_CONST_OR_PURE_P (olddecl);
2721 DECL_IS_REPLACEABLE_OPERATOR (newdecl)
2722 |= DECL_IS_REPLACEABLE_OPERATOR (olddecl);
2724 if (merge_attr)
2725 merge_attribute_bits (newdecl, olddecl);
2726 else
2728 /* Merge the noreturn bit. */
2729 TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2730 TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2731 TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2732 DECL_IS_MALLOC (olddecl) = DECL_IS_MALLOC (newdecl);
2733 DECL_PURE_P (olddecl) = DECL_PURE_P (newdecl);
2735 /* Keep the old RTL. */
2736 COPY_DECL_RTL (olddecl, newdecl);
2738 else if (VAR_P (newdecl)
2739 && (DECL_SIZE (olddecl) || !DECL_SIZE (newdecl)))
2741 /* Keep the old RTL. We cannot keep the old RTL if the old
2742 declaration was for an incomplete object and the new
2743 declaration is not since many attributes of the RTL will
2744 change. */
2745 COPY_DECL_RTL (olddecl, newdecl);
2748 /* If cannot merge, then use the new type and qualifiers,
2749 and don't preserve the old rtl. */
2750 else
2752 /* Clean out any memory we had of the old declaration. */
2753 tree oldstatic = value_member (olddecl, static_aggregates);
2754 if (oldstatic)
2755 TREE_VALUE (oldstatic) = error_mark_node;
2757 TREE_TYPE (olddecl) = TREE_TYPE (newdecl);
2758 TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2759 TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2760 TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2761 TREE_SIDE_EFFECTS (olddecl) = TREE_SIDE_EFFECTS (newdecl);
2764 /* Merge the storage class information. */
2765 merge_weak (newdecl, olddecl);
2767 DECL_DEFER_OUTPUT (newdecl) |= DECL_DEFER_OUTPUT (olddecl);
2768 TREE_PUBLIC (newdecl) = TREE_PUBLIC (olddecl);
2769 TREE_STATIC (olddecl) = TREE_STATIC (newdecl) |= TREE_STATIC (olddecl);
2770 if (! DECL_EXTERNAL (olddecl))
2771 DECL_EXTERNAL (newdecl) = 0;
2772 if (! DECL_COMDAT (olddecl))
2773 DECL_COMDAT (newdecl) = 0;
2775 if (VAR_OR_FUNCTION_DECL_P (newdecl) && DECL_LOCAL_DECL_P (newdecl))
2777 if (!DECL_LOCAL_DECL_P (olddecl))
2778 /* This can happen if olddecl was brought in from the
2779 enclosing namespace via a using-decl. The new decl is
2780 then not a block-scope extern at all. */
2781 DECL_LOCAL_DECL_P (newdecl) = false;
2782 else
2784 retrofit_lang_decl (newdecl);
2785 tree alias = DECL_LOCAL_DECL_ALIAS (newdecl)
2786 = DECL_LOCAL_DECL_ALIAS (olddecl);
2787 DECL_ATTRIBUTES (alias)
2788 = (*targetm.merge_decl_attributes) (alias, newdecl);
2789 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2790 merge_attribute_bits (newdecl, alias);
2794 new_template_info = NULL_TREE;
2795 if (DECL_LANG_SPECIFIC (newdecl) && DECL_LANG_SPECIFIC (olddecl))
2797 bool new_redefines_gnu_inline = false;
2799 if (new_defines_function
2800 && ((DECL_INTERFACE_KNOWN (olddecl)
2801 && TREE_CODE (olddecl) == FUNCTION_DECL)
2802 || (TREE_CODE (olddecl) == TEMPLATE_DECL
2803 && (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl))
2804 == FUNCTION_DECL))))
2805 new_redefines_gnu_inline = GNU_INLINE_P (STRIP_TEMPLATE (olddecl));
2807 if (!new_redefines_gnu_inline)
2809 DECL_INTERFACE_KNOWN (newdecl) |= DECL_INTERFACE_KNOWN (olddecl);
2810 DECL_NOT_REALLY_EXTERN (newdecl) |= DECL_NOT_REALLY_EXTERN (olddecl);
2811 DECL_COMDAT (newdecl) |= DECL_COMDAT (olddecl);
2814 if (TREE_CODE (newdecl) != TYPE_DECL)
2816 DECL_TEMPLATE_INSTANTIATED (newdecl)
2817 |= DECL_TEMPLATE_INSTANTIATED (olddecl);
2818 DECL_ODR_USED (newdecl) |= DECL_ODR_USED (olddecl);
2820 /* If the OLDDECL is an instantiation and/or specialization,
2821 then the NEWDECL must be too. But, it may not yet be marked
2822 as such if the caller has created NEWDECL, but has not yet
2823 figured out that it is a redeclaration. */
2824 if (!DECL_USE_TEMPLATE (newdecl))
2825 DECL_USE_TEMPLATE (newdecl) = DECL_USE_TEMPLATE (olddecl);
2827 if (!DECL_TEMPLATE_SPECIALIZATION (newdecl))
2828 DECL_INITIALIZED_IN_CLASS_P (newdecl)
2829 |= DECL_INITIALIZED_IN_CLASS_P (olddecl);
2832 /* Don't really know how much of the language-specific
2833 values we should copy from old to new. */
2834 DECL_IN_AGGR_P (newdecl) = DECL_IN_AGGR_P (olddecl);
2836 if (LANG_DECL_HAS_MIN (newdecl))
2838 DECL_ACCESS (newdecl) = DECL_ACCESS (olddecl);
2839 if (DECL_TEMPLATE_INFO (newdecl))
2841 new_template_info = DECL_TEMPLATE_INFO (newdecl);
2842 if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2843 && DECL_TEMPLATE_SPECIALIZATION (newdecl))
2844 /* Remember the presence of explicit specialization args. */
2845 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (olddecl))
2846 = TINFO_USED_TEMPLATE_ID (new_template_info);
2849 /* We don't want to copy template info from a non-templated friend
2850 (PR105761), but these shouldn't have DECL_TEMPLATE_INFO now. */
2851 gcc_checking_assert (!DECL_TEMPLATE_INFO (olddecl)
2852 || !non_templated_friend_p (olddecl));
2853 DECL_TEMPLATE_INFO (newdecl) = DECL_TEMPLATE_INFO (olddecl);
2856 if (DECL_DECLARES_FUNCTION_P (newdecl))
2858 /* Only functions have these fields. */
2859 DECL_NONCONVERTING_P (newdecl) = DECL_NONCONVERTING_P (olddecl);
2860 DECL_BEFRIENDING_CLASSES (newdecl)
2861 = chainon (DECL_BEFRIENDING_CLASSES (newdecl),
2862 DECL_BEFRIENDING_CLASSES (olddecl));
2863 /* DECL_THUNKS is only valid for virtual functions,
2864 otherwise it is a DECL_FRIEND_CONTEXT. */
2865 if (DECL_VIRTUAL_P (newdecl))
2866 SET_DECL_THUNKS (newdecl, DECL_THUNKS (olddecl));
2867 else if (tree fc = DECL_FRIEND_CONTEXT (newdecl))
2868 SET_DECL_FRIEND_CONTEXT (olddecl, fc);
2870 else if (VAR_P (newdecl))
2872 /* Only variables have this field. */
2873 if (VAR_HAD_UNKNOWN_BOUND (olddecl))
2874 SET_VAR_HAD_UNKNOWN_BOUND (newdecl);
2878 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2880 tree parm;
2882 /* Merge parameter attributes. */
2883 tree oldarg, newarg;
2884 for (oldarg = DECL_ARGUMENTS(olddecl), newarg = DECL_ARGUMENTS(newdecl);
2885 oldarg && newarg;
2886 oldarg = DECL_CHAIN(oldarg), newarg = DECL_CHAIN(newarg))
2888 DECL_ATTRIBUTES (newarg)
2889 = (*targetm.merge_decl_attributes) (oldarg, newarg);
2890 DECL_ATTRIBUTES (oldarg) = DECL_ATTRIBUTES (newarg);
2893 if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2894 && !DECL_TEMPLATE_INSTANTIATION (newdecl))
2896 /* If newdecl is not a specialization, then it is not a
2897 template-related function at all. And that means that we
2898 should have exited above, returning 0. */
2899 gcc_assert (DECL_TEMPLATE_SPECIALIZATION (newdecl));
2901 if (DECL_ODR_USED (olddecl))
2902 /* From [temp.expl.spec]:
2904 If a template, a member template or the member of a class
2905 template is explicitly specialized then that
2906 specialization shall be declared before the first use of
2907 that specialization that would cause an implicit
2908 instantiation to take place, in every translation unit in
2909 which such a use occurs. */
2910 error ("explicit specialization of %qD after first use",
2911 olddecl);
2913 SET_DECL_TEMPLATE_SPECIALIZATION (olddecl);
2914 DECL_COMDAT (newdecl) = (TREE_PUBLIC (newdecl)
2915 && DECL_DECLARED_INLINE_P (newdecl));
2917 /* Don't propagate visibility from the template to the
2918 specialization here. We'll do that in determine_visibility if
2919 appropriate. */
2920 DECL_VISIBILITY_SPECIFIED (olddecl) = 0;
2922 /* [temp.expl.spec/14] We don't inline explicit specialization
2923 just because the primary template says so. */
2924 gcc_assert (!merge_attr);
2926 DECL_DECLARED_INLINE_P (olddecl)
2927 = DECL_DECLARED_INLINE_P (newdecl);
2929 DECL_DISREGARD_INLINE_LIMITS (olddecl)
2930 = DECL_DISREGARD_INLINE_LIMITS (newdecl);
2932 DECL_UNINLINABLE (olddecl) = DECL_UNINLINABLE (newdecl);
2934 else if (new_defines_function && DECL_INITIAL (olddecl))
2936 /* Never inline re-defined extern inline functions.
2937 FIXME: this could be better handled by keeping both
2938 function as separate declarations. */
2939 DECL_UNINLINABLE (newdecl) = 1;
2941 else
2943 if (DECL_PENDING_INLINE_P (olddecl))
2945 DECL_PENDING_INLINE_P (newdecl) = 1;
2946 DECL_PENDING_INLINE_INFO (newdecl)
2947 = DECL_PENDING_INLINE_INFO (olddecl);
2949 else if (DECL_PENDING_INLINE_P (newdecl))
2951 else if (DECL_SAVED_AUTO_RETURN_TYPE (newdecl) == NULL)
2952 DECL_SAVED_AUTO_RETURN_TYPE (newdecl)
2953 = DECL_SAVED_AUTO_RETURN_TYPE (olddecl);
2955 DECL_DECLARED_INLINE_P (newdecl) |= DECL_DECLARED_INLINE_P (olddecl);
2957 DECL_UNINLINABLE (newdecl) = DECL_UNINLINABLE (olddecl)
2958 = (DECL_UNINLINABLE (newdecl) || DECL_UNINLINABLE (olddecl));
2960 DECL_DISREGARD_INLINE_LIMITS (newdecl)
2961 = DECL_DISREGARD_INLINE_LIMITS (olddecl)
2962 = (DECL_DISREGARD_INLINE_LIMITS (newdecl)
2963 || DECL_DISREGARD_INLINE_LIMITS (olddecl));
2966 /* Preserve abstractness on cloned [cd]tors. */
2967 DECL_ABSTRACT_P (newdecl) = DECL_ABSTRACT_P (olddecl);
2969 /* Update newdecl's parms to point at olddecl. */
2970 for (parm = DECL_ARGUMENTS (newdecl); parm;
2971 parm = DECL_CHAIN (parm))
2972 DECL_CONTEXT (parm) = olddecl;
2974 if (! types_match)
2976 SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
2977 COPY_DECL_ASSEMBLER_NAME (newdecl, olddecl);
2978 COPY_DECL_RTL (newdecl, olddecl);
2980 if (! types_match || new_defines_function)
2982 /* These are the final DECL_ARGUMENTS that will be used within the
2983 body; update any references to old DECL_ARGUMENTS in the
2984 contracts, if present. */
2985 if (tree contracts = DECL_CONTRACTS (newdecl))
2986 remap_contracts (olddecl, newdecl, contracts, true);
2988 /* These need to be copied so that the names are available.
2989 Note that if the types do match, we'll preserve inline
2990 info and other bits, but if not, we won't. */
2991 DECL_ARGUMENTS (olddecl) = DECL_ARGUMENTS (newdecl);
2992 DECL_RESULT (olddecl) = DECL_RESULT (newdecl);
2994 /* In some cases, duplicate_contracts will remove contracts from
2995 OLDDECL, to avoid duplications. Sometimes, the contracts end up
2996 shared. If we removed them, re-add them. */
2997 if (!DECL_CONTRACTS (olddecl))
2998 copy_contract_attributes (olddecl, newdecl);
3000 /* If redeclaring a builtin function, it stays built in
3001 if newdecl is a gnu_inline definition, or if newdecl is just
3002 a declaration. */
3003 if (fndecl_built_in_p (olddecl)
3004 && (new_defines_function ? GNU_INLINE_P (newdecl) : types_match))
3006 copy_decl_built_in_function (newdecl, olddecl);
3007 /* If we're keeping the built-in definition, keep the rtl,
3008 regardless of declaration matches. */
3009 COPY_DECL_RTL (olddecl, newdecl);
3010 if (DECL_BUILT_IN_CLASS (newdecl) == BUILT_IN_NORMAL)
3012 enum built_in_function fncode = DECL_FUNCTION_CODE (newdecl);
3013 if (builtin_decl_explicit_p (fncode))
3015 /* A compatible prototype of these builtin functions
3016 is seen, assume the runtime implements it with
3017 the expected semantics. */
3018 switch (fncode)
3020 case BUILT_IN_STPCPY:
3021 set_builtin_decl_implicit_p (fncode, true);
3022 break;
3023 default:
3024 set_builtin_decl_declared_p (fncode, true);
3025 break;
3029 copy_attributes_to_builtin (newdecl);
3032 if (new_defines_function)
3033 /* If defining a function declared with other language
3034 linkage, use the previously declared language linkage. */
3035 SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
3036 else if (types_match)
3038 DECL_RESULT (newdecl) = DECL_RESULT (olddecl);
3039 /* Don't clear out the arguments if we're just redeclaring a
3040 function. */
3041 if (DECL_ARGUMENTS (olddecl))
3043 /* If we removed contracts from previous definition, re-attach
3044 them. Otherwise, rewrite the contracts so they match the
3045 parameters of the new declaration. */
3046 if (DECL_INITIAL (olddecl)
3047 && DECL_CONTRACTS (newdecl)
3048 && !DECL_CONTRACTS (olddecl))
3049 copy_contract_attributes (olddecl, newdecl);
3050 else
3052 /* Temporarily undo the re-contexting of parameters so we can
3053 actually remap parameters. The inliner won't replace
3054 parameters if we don't do this. */
3055 tree args = DECL_ARGUMENTS (newdecl);
3056 for (tree p = args; p; p = DECL_CHAIN (p))
3057 DECL_CONTEXT (p) = newdecl;
3059 /* Save new argument names for use in contracts parsing,
3060 unless we've already started parsing the body of olddecl
3061 (particular issues arise when newdecl is from a prior
3062 friend decl with no argument names, see
3063 modules/contracts-tpl-friend-1). */
3064 if (tree contracts = DECL_CONTRACTS (olddecl))
3065 remap_contracts (newdecl, olddecl, contracts, true);
3067 /* And reverse this operation again. */
3068 for (tree p = args; p; p = DECL_CHAIN (p))
3069 DECL_CONTEXT (p) = olddecl;
3072 DECL_ARGUMENTS (newdecl) = DECL_ARGUMENTS (olddecl);
3076 else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
3077 NAMESPACE_LEVEL (newdecl) = NAMESPACE_LEVEL (olddecl);
3079 /* Now preserve various other info from the definition. */
3080 TREE_ADDRESSABLE (newdecl) = TREE_ADDRESSABLE (olddecl);
3081 TREE_ASM_WRITTEN (newdecl) = TREE_ASM_WRITTEN (olddecl);
3082 DECL_COMMON (newdecl) = DECL_COMMON (olddecl);
3083 COPY_DECL_ASSEMBLER_NAME (olddecl, newdecl);
3085 /* Warn about conflicting visibility specifications. */
3086 if (DECL_VISIBILITY_SPECIFIED (olddecl)
3087 && DECL_VISIBILITY_SPECIFIED (newdecl)
3088 && DECL_VISIBILITY (newdecl) != DECL_VISIBILITY (olddecl))
3090 auto_diagnostic_group d;
3091 if (warning_at (newdecl_loc, OPT_Wattributes,
3092 "%qD: visibility attribute ignored because it "
3093 "conflicts with previous declaration", newdecl))
3094 inform (olddecl_loc,
3095 "previous declaration of %qD", olddecl);
3097 /* Choose the declaration which specified visibility. */
3098 if (DECL_VISIBILITY_SPECIFIED (olddecl))
3100 DECL_VISIBILITY (newdecl) = DECL_VISIBILITY (olddecl);
3101 DECL_VISIBILITY_SPECIFIED (newdecl) = 1;
3103 /* Init priority used to be merged from newdecl to olddecl by the memcpy,
3104 so keep this behavior. */
3105 if (VAR_P (newdecl) && DECL_HAS_INIT_PRIORITY_P (newdecl))
3107 SET_DECL_INIT_PRIORITY (olddecl, DECL_INIT_PRIORITY (newdecl));
3108 DECL_HAS_INIT_PRIORITY_P (olddecl) = 1;
3110 /* Likewise for DECL_ALIGN, DECL_USER_ALIGN and DECL_PACKED. */
3111 if (DECL_ALIGN (olddecl) > DECL_ALIGN (newdecl))
3113 SET_DECL_ALIGN (newdecl, DECL_ALIGN (olddecl));
3114 DECL_USER_ALIGN (newdecl) |= DECL_USER_ALIGN (olddecl);
3116 else if (DECL_ALIGN (olddecl) == DECL_ALIGN (newdecl)
3117 && DECL_USER_ALIGN (olddecl) != DECL_USER_ALIGN (newdecl))
3118 DECL_USER_ALIGN (newdecl) = 1;
3120 DECL_USER_ALIGN (olddecl) = DECL_USER_ALIGN (newdecl);
3121 if (DECL_WARN_IF_NOT_ALIGN (olddecl)
3122 > DECL_WARN_IF_NOT_ALIGN (newdecl))
3123 SET_DECL_WARN_IF_NOT_ALIGN (newdecl,
3124 DECL_WARN_IF_NOT_ALIGN (olddecl));
3125 if (TREE_CODE (newdecl) == FIELD_DECL)
3126 DECL_PACKED (olddecl) = DECL_PACKED (newdecl);
3128 /* The DECL_LANG_SPECIFIC information in OLDDECL will be replaced
3129 with that from NEWDECL below. */
3130 if (DECL_LANG_SPECIFIC (olddecl))
3132 gcc_checking_assert (DECL_LANG_SPECIFIC (olddecl)
3133 != DECL_LANG_SPECIFIC (newdecl));
3134 ggc_free (DECL_LANG_SPECIFIC (olddecl));
3137 /* Merge the USED information. */
3138 if (TREE_USED (olddecl))
3139 TREE_USED (newdecl) = 1;
3140 else if (TREE_USED (newdecl))
3141 TREE_USED (olddecl) = 1;
3143 if (VAR_P (newdecl))
3145 if (DECL_READ_P (olddecl))
3146 DECL_READ_P (newdecl) = 1;
3147 else if (DECL_READ_P (newdecl))
3148 DECL_READ_P (olddecl) = 1;
3151 if (DECL_PRESERVE_P (olddecl))
3152 DECL_PRESERVE_P (newdecl) = 1;
3153 else if (DECL_PRESERVE_P (newdecl))
3154 DECL_PRESERVE_P (olddecl) = 1;
3156 /* Merge the DECL_FUNCTION_VERSIONED information. newdecl will be copied
3157 to olddecl and deleted. */
3158 if (TREE_CODE (newdecl) == FUNCTION_DECL
3159 && DECL_FUNCTION_VERSIONED (olddecl))
3161 /* Set the flag for newdecl so that it gets copied to olddecl. */
3162 DECL_FUNCTION_VERSIONED (newdecl) = 1;
3163 /* newdecl will be purged after copying to olddecl and is no longer
3164 a version. */
3165 cgraph_node::delete_function_version_by_decl (newdecl);
3168 if (TREE_CODE (newdecl) == FUNCTION_DECL)
3170 int function_size;
3171 struct symtab_node *snode = symtab_node::get (olddecl);
3173 function_size = sizeof (struct tree_decl_common);
3175 memcpy ((char *) olddecl + sizeof (struct tree_common),
3176 (char *) newdecl + sizeof (struct tree_common),
3177 function_size - sizeof (struct tree_common));
3179 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3180 (char *) newdecl + sizeof (struct tree_decl_common),
3181 sizeof (struct tree_function_decl) - sizeof (struct tree_decl_common));
3183 /* Preserve symtab node mapping. */
3184 olddecl->decl_with_vis.symtab_node = snode;
3186 if (new_template_info)
3187 /* If newdecl is a template instantiation, it is possible that
3188 the following sequence of events has occurred:
3190 o A friend function was declared in a class template. The
3191 class template was instantiated.
3193 o The instantiation of the friend declaration was
3194 recorded on the instantiation list, and is newdecl.
3196 o Later, however, instantiate_class_template called pushdecl
3197 on the newdecl to perform name injection. But, pushdecl in
3198 turn called duplicate_decls when it discovered that another
3199 declaration of a global function with the same name already
3200 existed.
3202 o Here, in duplicate_decls, we decided to clobber newdecl.
3204 If we're going to do that, we'd better make sure that
3205 olddecl, and not newdecl, is on the list of
3206 instantiations so that if we try to do the instantiation
3207 again we won't get the clobbered declaration. */
3208 reregister_specialization (newdecl,
3209 new_template_info,
3210 olddecl);
3212 else
3214 size_t size = tree_code_size (TREE_CODE (newdecl));
3216 memcpy ((char *) olddecl + sizeof (struct tree_common),
3217 (char *) newdecl + sizeof (struct tree_common),
3218 sizeof (struct tree_decl_common) - sizeof (struct tree_common));
3220 switch (TREE_CODE (newdecl))
3222 case LABEL_DECL:
3223 case VAR_DECL:
3224 case RESULT_DECL:
3225 case PARM_DECL:
3226 case FIELD_DECL:
3227 case TYPE_DECL:
3228 case CONST_DECL:
3230 struct symtab_node *snode = NULL;
3232 if (VAR_P (newdecl)
3233 && (TREE_STATIC (olddecl) || TREE_PUBLIC (olddecl)
3234 || DECL_EXTERNAL (olddecl)))
3235 snode = symtab_node::get (olddecl);
3236 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3237 (char *) newdecl + sizeof (struct tree_decl_common),
3238 size - sizeof (struct tree_decl_common)
3239 + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
3240 if (VAR_P (newdecl))
3241 olddecl->decl_with_vis.symtab_node = snode;
3243 break;
3244 default:
3245 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3246 (char *) newdecl + sizeof (struct tree_decl_common),
3247 sizeof (struct tree_decl_non_common) - sizeof (struct tree_decl_common)
3248 + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
3249 break;
3253 if (VAR_OR_FUNCTION_DECL_P (newdecl))
3255 if (DECL_EXTERNAL (olddecl)
3256 || TREE_PUBLIC (olddecl)
3257 || TREE_STATIC (olddecl))
3259 /* Merge the section attribute.
3260 We want to issue an error if the sections conflict but that must be
3261 done later in decl_attributes since we are called before attributes
3262 are assigned. */
3263 if (DECL_SECTION_NAME (newdecl) != NULL)
3264 set_decl_section_name (olddecl, newdecl);
3266 if (DECL_ONE_ONLY (newdecl))
3268 struct symtab_node *oldsym, *newsym;
3269 if (TREE_CODE (olddecl) == FUNCTION_DECL)
3270 oldsym = cgraph_node::get_create (olddecl);
3271 else
3272 oldsym = varpool_node::get_create (olddecl);
3273 newsym = symtab_node::get (newdecl);
3274 oldsym->set_comdat_group (newsym->get_comdat_group ());
3278 if (VAR_P (newdecl)
3279 && CP_DECL_THREAD_LOCAL_P (newdecl))
3281 CP_DECL_THREAD_LOCAL_P (olddecl) = true;
3282 if (!processing_template_decl)
3283 set_decl_tls_model (olddecl, DECL_TLS_MODEL (newdecl));
3287 DECL_UID (olddecl) = olddecl_uid;
3289 /* NEWDECL contains the merged attribute lists.
3290 Update OLDDECL to be the same. */
3291 DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
3293 /* If OLDDECL had its DECL_RTL instantiated, re-invoke make_decl_rtl
3294 so that encode_section_info has a chance to look at the new decl
3295 flags and attributes. */
3296 if (DECL_RTL_SET_P (olddecl)
3297 && (TREE_CODE (olddecl) == FUNCTION_DECL
3298 || (VAR_P (olddecl)
3299 && TREE_STATIC (olddecl))))
3300 make_decl_rtl (olddecl);
3302 /* The NEWDECL will no longer be needed. Because every out-of-class
3303 declaration of a member results in a call to duplicate_decls,
3304 freeing these nodes represents in a significant savings.
3306 Before releasing the node, be sore to remove function from symbol
3307 table that might have been inserted there to record comdat group.
3308 Be sure to however do not free DECL_STRUCT_FUNCTION because this
3309 structure is shared in between newdecl and oldecl. */
3310 if (TREE_CODE (newdecl) == FUNCTION_DECL)
3311 DECL_STRUCT_FUNCTION (newdecl) = NULL;
3312 if (VAR_OR_FUNCTION_DECL_P (newdecl))
3314 struct symtab_node *snode = symtab_node::get (newdecl);
3315 if (snode)
3316 snode->remove ();
3319 if (TREE_CODE (olddecl) == FUNCTION_DECL)
3321 tree clone;
3322 FOR_EACH_CLONE (clone, olddecl)
3324 DECL_ATTRIBUTES (clone) = DECL_ATTRIBUTES (olddecl);
3325 DECL_PRESERVE_P (clone) |= DECL_PRESERVE_P (olddecl);
3329 /* Remove the associated constraints for newdecl, if any, before
3330 reclaiming memory. */
3331 if (flag_concepts)
3332 remove_constraints (newdecl);
3334 ggc_free (newdecl);
3336 return olddecl;
3339 /* Return zero if the declaration NEWDECL is valid
3340 when the declaration OLDDECL (assumed to be for the same name)
3341 has already been seen.
3342 Otherwise return an error message format string with a %s
3343 where the identifier should go. */
3345 static const char *
3346 redeclaration_error_message (tree newdecl, tree olddecl)
3348 if (TREE_CODE (newdecl) == TYPE_DECL)
3350 /* Because C++ can put things into name space for free,
3351 constructs like "typedef struct foo { ... } foo"
3352 would look like an erroneous redeclaration. */
3353 if (same_type_p (TREE_TYPE (newdecl), TREE_TYPE (olddecl)))
3354 return NULL;
3355 else
3356 return G_("redefinition of %q#D");
3358 else if (TREE_CODE (newdecl) == FUNCTION_DECL)
3360 /* If this is a pure function, its olddecl will actually be
3361 the original initialization to `0' (which we force to call
3362 abort()). Don't complain about redefinition in this case. */
3363 if (DECL_LANG_SPECIFIC (olddecl) && DECL_PURE_VIRTUAL_P (olddecl)
3364 && DECL_INITIAL (olddecl) == NULL_TREE)
3365 return NULL;
3367 /* If both functions come from different namespaces, this is not
3368 a redeclaration - this is a conflict with a used function. */
3369 if (DECL_NAMESPACE_SCOPE_P (olddecl)
3370 && DECL_CONTEXT (olddecl) != DECL_CONTEXT (newdecl)
3371 && ! decls_match (olddecl, newdecl))
3372 return G_("%qD conflicts with used function");
3374 /* We'll complain about linkage mismatches in
3375 warn_extern_redeclared_static. */
3377 /* Defining the same name twice is no good. */
3378 if (decl_defined_p (olddecl)
3379 && decl_defined_p (newdecl))
3381 if (DECL_NAME (olddecl) == NULL_TREE)
3382 return G_("%q#D not declared in class");
3383 else if (!GNU_INLINE_P (olddecl)
3384 || GNU_INLINE_P (newdecl))
3385 return G_("redefinition of %q#D");
3388 if (DECL_DECLARED_INLINE_P (olddecl) && DECL_DECLARED_INLINE_P (newdecl))
3390 bool olda = GNU_INLINE_P (olddecl);
3391 bool newa = GNU_INLINE_P (newdecl);
3393 if (olda != newa)
3395 if (newa)
3396 return G_("%q+D redeclared inline with "
3397 "%<gnu_inline%> attribute");
3398 else
3399 return G_("%q+D redeclared inline without "
3400 "%<gnu_inline%> attribute");
3404 /* [class.compare.default]: A definition of a comparison operator as
3405 defaulted that appears in a class shall be the first declaration of
3406 that function. */
3407 special_function_kind sfk = special_function_p (olddecl);
3408 if (sfk == sfk_comparison && DECL_DEFAULTED_FN (newdecl))
3409 return G_("comparison operator %q+D defaulted after "
3410 "its first declaration");
3412 check_abi_tag_redeclaration
3413 (olddecl, lookup_attribute ("abi_tag", DECL_ATTRIBUTES (olddecl)),
3414 lookup_attribute ("abi_tag", DECL_ATTRIBUTES (newdecl)));
3416 return NULL;
3418 else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
3420 tree nt, ot;
3422 if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == CONCEPT_DECL)
3423 return G_("redefinition of %q#D");
3425 if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) != FUNCTION_DECL)
3426 return redeclaration_error_message (DECL_TEMPLATE_RESULT (newdecl),
3427 DECL_TEMPLATE_RESULT (olddecl));
3429 if (DECL_TEMPLATE_RESULT (newdecl) == DECL_TEMPLATE_RESULT (olddecl))
3430 return NULL;
3432 nt = DECL_TEMPLATE_RESULT (newdecl);
3433 if (DECL_TEMPLATE_INFO (nt))
3434 nt = DECL_TEMPLATE_RESULT (template_for_substitution (nt));
3435 ot = DECL_TEMPLATE_RESULT (olddecl);
3436 if (DECL_TEMPLATE_INFO (ot))
3437 ot = DECL_TEMPLATE_RESULT (template_for_substitution (ot));
3438 if (DECL_INITIAL (nt) && DECL_INITIAL (ot)
3439 && (!GNU_INLINE_P (ot) || GNU_INLINE_P (nt)))
3440 return G_("redefinition of %q#D");
3442 if (DECL_DECLARED_INLINE_P (ot) && DECL_DECLARED_INLINE_P (nt))
3444 bool olda = GNU_INLINE_P (ot);
3445 bool newa = GNU_INLINE_P (nt);
3447 if (olda != newa)
3449 if (newa)
3450 return G_("%q+D redeclared inline with "
3451 "%<gnu_inline%> attribute");
3452 else
3453 return G_("%q+D redeclared inline without "
3454 "%<gnu_inline%> attribute");
3458 /* Core issue #226 (C++11):
3460 If a friend function template declaration specifies a
3461 default template-argument, that declaration shall be a
3462 definition and shall be the only declaration of the
3463 function template in the translation unit. */
3464 if ((cxx_dialect != cxx98)
3465 && TREE_CODE (ot) == FUNCTION_DECL && DECL_UNIQUE_FRIEND_P (ot)
3466 && !check_default_tmpl_args (nt, DECL_TEMPLATE_PARMS (newdecl),
3467 /*is_primary=*/true,
3468 /*is_partial=*/false,
3469 /*is_friend_decl=*/2))
3470 return G_("redeclaration of friend %q#D "
3471 "may not have default template arguments");
3473 return NULL;
3475 else if (VAR_P (newdecl)
3476 && (CP_DECL_THREAD_LOCAL_P (newdecl)
3477 != CP_DECL_THREAD_LOCAL_P (olddecl))
3478 && (! DECL_LANG_SPECIFIC (olddecl)
3479 || ! CP_DECL_THREADPRIVATE_P (olddecl)
3480 || CP_DECL_THREAD_LOCAL_P (newdecl)))
3482 /* Only variables can be thread-local, and all declarations must
3483 agree on this property. */
3484 if (CP_DECL_THREAD_LOCAL_P (newdecl))
3485 return G_("thread-local declaration of %q#D follows "
3486 "non-thread-local declaration");
3487 else
3488 return G_("non-thread-local declaration of %q#D follows "
3489 "thread-local declaration");
3491 else if (toplevel_bindings_p () || DECL_NAMESPACE_SCOPE_P (newdecl))
3493 /* The objects have been declared at namespace scope. If either
3494 is a member of an anonymous union, then this is an invalid
3495 redeclaration. For example:
3497 int i;
3498 union { int i; };
3500 is invalid. */
3501 if ((VAR_P (newdecl) && DECL_ANON_UNION_VAR_P (newdecl))
3502 || (VAR_P (olddecl) && DECL_ANON_UNION_VAR_P (olddecl)))
3503 return G_("redeclaration of %q#D");
3504 /* If at least one declaration is a reference, there is no
3505 conflict. For example:
3507 int i = 3;
3508 extern int i;
3510 is valid. */
3511 if (DECL_EXTERNAL (newdecl) || DECL_EXTERNAL (olddecl))
3512 return NULL;
3514 /* Static data member declared outside a class definition
3515 if the variable is defined within the class with constexpr
3516 specifier is declaration rather than definition (and
3517 deprecated). */
3518 if (cxx_dialect >= cxx17
3519 && VAR_P (olddecl)
3520 && DECL_CLASS_SCOPE_P (olddecl)
3521 && DECL_DECLARED_CONSTEXPR_P (olddecl)
3522 && !DECL_INITIAL (newdecl))
3524 DECL_EXTERNAL (newdecl) = 1;
3525 /* For now, only warn with explicit -Wdeprecated. */
3526 if (OPTION_SET_P (warn_deprecated))
3528 auto_diagnostic_group d;
3529 if (warning_at (DECL_SOURCE_LOCATION (newdecl), OPT_Wdeprecated,
3530 "redundant redeclaration of %<constexpr%> "
3531 "static data member %qD", newdecl))
3532 inform (DECL_SOURCE_LOCATION (olddecl),
3533 "previous declaration of %qD", olddecl);
3535 return NULL;
3538 /* Reject two definitions. */
3539 return G_("redefinition of %q#D");
3541 else
3543 /* Objects declared with block scope: */
3544 /* Reject two definitions, and reject a definition
3545 together with an external reference. */
3546 if (!(DECL_EXTERNAL (newdecl) && DECL_EXTERNAL (olddecl)))
3547 return G_("redeclaration of %q#D");
3548 return NULL;
3553 /* Hash and equality functions for the named_label table. */
3555 hashval_t
3556 named_label_hash::hash (const value_type entry)
3558 return IDENTIFIER_HASH_VALUE (entry->name);
3561 bool
3562 named_label_hash::equal (const value_type entry, compare_type name)
3564 return name == entry->name;
3567 /* Look for a label named ID in the current function. If one cannot
3568 be found, create one. Return the named_label_entry, or NULL on
3569 failure. */
3571 static named_label_entry *
3572 lookup_label_1 (tree id, bool making_local_p)
3574 auto_cond_timevar tv (TV_NAME_LOOKUP);
3576 /* You can't use labels at global scope. */
3577 if (current_function_decl == NULL_TREE)
3579 error ("label %qE referenced outside of any function", id);
3580 return NULL;
3583 if (!named_labels)
3584 named_labels = hash_table<named_label_hash>::create_ggc (13);
3586 hashval_t hash = IDENTIFIER_HASH_VALUE (id);
3587 named_label_entry **slot
3588 = named_labels->find_slot_with_hash (id, hash, INSERT);
3589 named_label_entry *old = *slot;
3591 if (old && old->label_decl)
3593 if (!making_local_p)
3594 return old;
3596 if (old->binding_level == current_binding_level)
3598 error ("local label %qE conflicts with existing label", id);
3599 inform (DECL_SOURCE_LOCATION (old->label_decl), "previous label");
3600 return NULL;
3604 /* We are making a new decl, create or reuse the named_label_entry */
3605 named_label_entry *ent = NULL;
3606 if (old && !old->label_decl)
3607 ent = old;
3608 else
3610 ent = ggc_cleared_alloc<named_label_entry> ();
3611 ent->name = id;
3612 ent->outer = old;
3613 *slot = ent;
3616 /* Now create the LABEL_DECL. */
3617 tree decl = build_decl (input_location, LABEL_DECL, id, void_type_node);
3619 DECL_CONTEXT (decl) = current_function_decl;
3620 SET_DECL_MODE (decl, VOIDmode);
3621 if (making_local_p)
3623 C_DECLARED_LABEL_FLAG (decl) = true;
3624 DECL_CHAIN (decl) = current_binding_level->names;
3625 current_binding_level->names = decl;
3628 ent->label_decl = decl;
3630 return ent;
3633 /* Wrapper for lookup_label_1. */
3635 tree
3636 lookup_label (tree id)
3638 named_label_entry *ent = lookup_label_1 (id, false);
3639 return ent ? ent->label_decl : NULL_TREE;
3642 /* Remember that we've seen &&ID. */
3644 void
3645 mark_label_addressed (tree id)
3647 named_label_entry *ent = lookup_label_1 (id, false);
3648 ent->addressed = true;
3651 tree
3652 declare_local_label (tree id)
3654 named_label_entry *ent = lookup_label_1 (id, true);
3655 return ent ? ent->label_decl : NULL_TREE;
3658 /* Returns true if it is ill-formed to jump past the declaration of DECL. */
3660 static bool
3661 decl_jump_unsafe (tree decl)
3663 /* [stmt.dcl]/3: A program that jumps from a point where a local variable
3664 with automatic storage duration is not in scope to a point where it is
3665 in scope is ill-formed unless the variable has scalar type, class type
3666 with a trivial default constructor and a trivial destructor, a
3667 cv-qualified version of one of these types, or an array of one of the
3668 preceding types and is declared without an initializer (8.5). */
3669 tree type = TREE_TYPE (decl);
3671 return (type != error_mark_node
3672 && VAR_P (decl)
3673 && !TREE_STATIC (decl)
3674 && (DECL_NONTRIVIALLY_INITIALIZED_P (decl)
3675 || variably_modified_type_p (type, NULL_TREE)));
3678 /* A subroutine of check_previous_goto_1 and check_goto to identify a branch
3679 to the user. */
3681 static bool
3682 identify_goto (tree decl, location_t loc, const location_t *locus,
3683 diagnostic_t diag_kind, bool computed)
3685 if (computed)
3686 diag_kind = DK_WARNING;
3687 bool complained
3688 = emit_diagnostic (diag_kind, loc, 0,
3689 decl ? G_("jump to label %qD")
3690 : G_("jump to case label"), decl);
3691 if (complained && locus)
3693 if (computed)
3694 inform (*locus, " as a possible target of computed goto");
3695 else
3696 inform (*locus, " from here");
3698 return complained;
3701 /* Check that a single previously seen jump to a newly defined label
3702 is OK. DECL is the LABEL_DECL or 0; LEVEL is the binding_level for
3703 the jump context; NAMES are the names in scope in LEVEL at the jump
3704 context; LOCUS is the source position of the jump or 0. COMPUTED
3705 is a vec of decls if the jump is a computed goto. Returns
3706 true if all is well. */
3708 static bool
3709 check_previous_goto_1 (tree decl, cp_binding_level* level, tree names,
3710 bool exited_omp, const location_t *locus,
3711 vec<tree,va_gc> *computed)
3713 cp_binding_level *b;
3714 bool complained = false;
3715 int identified = 0;
3716 bool saw_eh = false, saw_omp = false, saw_tm = false, saw_cxif = false;
3717 bool saw_ceif = false, saw_se = false;
3719 if (exited_omp)
3721 complained = identify_goto (decl, input_location, locus, DK_ERROR,
3722 computed);
3723 if (complained)
3724 inform (input_location, " exits OpenMP structured block");
3725 saw_omp = true;
3726 identified = 2;
3729 for (b = current_binding_level; b ; b = b->level_chain)
3731 tree new_decls, old_decls = (b == level ? names : NULL_TREE);
3733 for (new_decls = b->names; new_decls != old_decls;
3734 new_decls = (DECL_P (new_decls) ? DECL_CHAIN (new_decls)
3735 : TREE_CHAIN (new_decls)))
3737 bool problem = decl_jump_unsafe (new_decls);
3738 if (! problem)
3739 continue;
3741 if (!identified)
3743 complained = identify_goto (decl, input_location, locus, DK_ERROR,
3744 computed);
3745 identified = 2;
3747 if (complained)
3748 inform (DECL_SOURCE_LOCATION (new_decls),
3749 " crosses initialization of %q#D", new_decls);
3752 if (b == level)
3753 break;
3755 const char *inf = NULL;
3756 location_t loc = input_location;
3757 switch (b->kind)
3759 case sk_try:
3760 if (!saw_eh)
3761 inf = G_(" enters %<try%> block");
3762 saw_eh = true;
3763 break;
3765 case sk_catch:
3766 if (!saw_eh)
3767 inf = G_(" enters %<catch%> block");
3768 saw_eh = true;
3769 break;
3771 case sk_omp:
3772 if (!saw_omp)
3773 inf = G_(" enters OpenMP structured block");
3774 saw_omp = true;
3775 break;
3777 case sk_transaction:
3778 if (!saw_tm)
3779 inf = G_(" enters synchronized or atomic statement");
3780 saw_tm = true;
3781 break;
3783 case sk_stmt_expr:
3784 if (!saw_se)
3785 inf = G_(" enters statement expression");
3786 saw_se = true;
3787 break;
3789 case sk_block:
3790 if (!saw_cxif && level_for_constexpr_if (b->level_chain))
3792 inf = G_(" enters %<constexpr if%> statement");
3793 loc = EXPR_LOCATION (b->level_chain->this_entity);
3794 saw_cxif = true;
3796 else if (!saw_ceif && level_for_consteval_if (b->level_chain))
3798 inf = G_(" enters %<consteval if%> statement");
3799 loc = EXPR_LOCATION (b->level_chain->this_entity);
3800 saw_ceif = true;
3802 break;
3804 default:
3805 break;
3808 if (inf)
3810 if (identified < 2)
3811 complained = identify_goto (decl, input_location, locus, DK_ERROR,
3812 computed);
3813 identified = 2;
3814 if (complained)
3815 inform (loc, inf);
3819 if (!vec_safe_is_empty (computed))
3821 if (!identified)
3822 complained = identify_goto (decl, input_location, locus, DK_ERROR,
3823 computed);
3824 identified = 2;
3825 if (complained)
3826 for (tree d : computed)
3828 if (DECL_P (d))
3829 inform (DECL_SOURCE_LOCATION (d), " does not destroy %qD", d);
3830 else if (d == get_identifier ("catch"))
3831 inform (*locus, " does not clean up handled exception");
3835 return !identified;
3838 static void
3839 check_previous_goto (tree decl, struct named_label_use_entry *use)
3841 check_previous_goto_1 (decl, use->binding_level,
3842 use->names_in_scope, use->in_omp_scope,
3843 &use->o_goto_locus, use->computed_goto);
3846 static bool
3847 check_switch_goto (cp_binding_level* level)
3849 return check_previous_goto_1 (NULL_TREE, level, level->names,
3850 false, NULL, nullptr);
3853 /* Check that a new jump to a label ENT is OK. COMPUTED is true
3854 if this is a possible target of a computed goto. */
3856 void
3857 check_goto_1 (named_label_entry *ent, bool computed)
3859 tree decl = ent->label_decl;
3861 /* If the label hasn't been defined yet, defer checking. */
3862 if (! DECL_INITIAL (decl))
3864 /* Don't bother creating another use if the last goto had the
3865 same data, and will therefore create the same set of errors. */
3866 if (ent->uses
3867 && ent->uses->names_in_scope == current_binding_level->names)
3868 return;
3870 named_label_use_entry *new_use
3871 = ggc_alloc<named_label_use_entry> ();
3872 new_use->binding_level = current_binding_level;
3873 new_use->names_in_scope = current_binding_level->names;
3874 new_use->o_goto_locus = input_location;
3875 new_use->in_omp_scope = false;
3876 new_use->computed_goto = computed ? make_tree_vector () : nullptr;
3878 new_use->next = ent->uses;
3879 ent->uses = new_use;
3880 return;
3883 bool saw_catch = false, complained = false;
3884 int identified = 0;
3885 tree bad;
3886 unsigned ix;
3888 if (ent->in_try_scope || ent->in_catch_scope || ent->in_transaction_scope
3889 || ent->in_constexpr_if || ent->in_consteval_if
3890 || ent->in_omp_scope || ent->in_stmt_expr
3891 || !vec_safe_is_empty (ent->bad_decls))
3893 diagnostic_t diag_kind = DK_PERMERROR;
3894 if (ent->in_try_scope || ent->in_catch_scope || ent->in_constexpr_if
3895 || ent->in_consteval_if || ent->in_transaction_scope
3896 || ent->in_omp_scope || ent->in_stmt_expr)
3897 diag_kind = DK_ERROR;
3898 complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3899 &input_location, diag_kind, computed);
3900 identified = 1 + (diag_kind == DK_ERROR);
3903 FOR_EACH_VEC_SAFE_ELT (ent->bad_decls, ix, bad)
3905 bool problem = decl_jump_unsafe (bad);
3907 if (problem && DECL_ARTIFICIAL (bad))
3909 /* Can't skip init of __exception_info. */
3910 if (identified == 1)
3912 complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3913 &input_location, DK_ERROR, computed);
3914 identified = 2;
3916 if (complained)
3917 inform (DECL_SOURCE_LOCATION (bad), " enters %<catch%> block");
3918 saw_catch = true;
3920 else if (complained)
3921 inform (DECL_SOURCE_LOCATION (bad),
3922 " skips initialization of %q#D", bad);
3925 if (complained)
3927 if (ent->in_try_scope)
3928 inform (input_location, " enters %<try%> block");
3929 else if (ent->in_catch_scope && !saw_catch)
3930 inform (input_location, " enters %<catch%> block");
3931 else if (ent->in_transaction_scope)
3932 inform (input_location, " enters synchronized or atomic statement");
3933 else if (ent->in_constexpr_if)
3934 inform (input_location, " enters %<constexpr if%> statement");
3935 else if (ent->in_consteval_if)
3936 inform (input_location, " enters %<consteval if%> statement");
3937 else if (ent->in_stmt_expr)
3938 inform (input_location, " enters statement expression");
3941 if (ent->in_omp_scope)
3943 if (complained)
3944 inform (input_location, " enters OpenMP structured block");
3946 else if (flag_openmp)
3947 for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3949 if (b == ent->binding_level)
3950 break;
3951 if (b->kind == sk_omp)
3953 if (identified < 2)
3955 complained = identify_goto (decl,
3956 DECL_SOURCE_LOCATION (decl),
3957 &input_location, DK_ERROR,
3958 computed);
3959 identified = 2;
3961 if (complained)
3962 inform (input_location, " exits OpenMP structured block");
3963 break;
3967 /* Warn if a computed goto might involve a local variable going out of scope
3968 without being cleaned up. */
3969 if (computed)
3971 auto level = ent->binding_level;
3972 auto names = ent->names_in_scope;
3973 for (auto b = current_binding_level; ; b = b->level_chain)
3975 if (b->kind == sk_catch)
3977 if (!identified)
3979 complained
3980 = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3981 &input_location, DK_ERROR, computed);
3982 identified = 2;
3984 if (complained)
3985 inform (input_location,
3986 " does not clean up handled exception");
3988 tree end = b == level ? names : NULL_TREE;
3989 for (tree d = b->names; d != end; d = DECL_CHAIN (d))
3991 if (TREE_CODE (d) == VAR_DECL && !TREE_STATIC (d)
3992 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (d)))
3994 if (!identified)
3996 complained
3997 = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3998 &input_location, DK_ERROR, computed);
3999 identified = 2;
4001 if (complained)
4002 inform (DECL_SOURCE_LOCATION (d),
4003 " does not destroy %qD", d);
4006 if (b == level)
4007 break;
4012 /* Check that a new jump to a label DECL is OK. Called by
4013 finish_goto_stmt. */
4015 void
4016 check_goto (tree decl)
4018 if (!named_labels)
4019 return;
4020 if (TREE_CODE (decl) != LABEL_DECL)
4022 /* We don't know where a computed goto is jumping,
4023 so check all addressable labels. */
4024 for (auto iter = named_labels->begin ();
4025 iter != named_labels->end ();
4026 ++iter)
4028 auto ent = *iter;
4029 if (ent->addressed)
4030 check_goto_1 (ent, true);
4033 else
4035 hashval_t hash = IDENTIFIER_HASH_VALUE (DECL_NAME (decl));
4036 named_label_entry **slot
4037 = named_labels->find_slot_with_hash (DECL_NAME (decl), hash, NO_INSERT);
4038 named_label_entry *ent = *slot;
4039 check_goto_1 (ent, false);
4043 /* Check that a return is ok wrt OpenMP structured blocks.
4044 Called by finish_return_stmt. Returns true if all is well. */
4046 bool
4047 check_omp_return (void)
4049 for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
4050 if (b->kind == sk_omp)
4052 error ("invalid exit from OpenMP structured block");
4053 return false;
4055 else if (b->kind == sk_function_parms)
4056 break;
4057 return true;
4060 /* Define a label, specifying the location in the source file.
4061 Return the LABEL_DECL node for the label. */
4063 tree
4064 define_label (location_t location, tree name)
4066 auto_cond_timevar tv (TV_NAME_LOOKUP);
4068 /* After labels, make any new cleanups in the function go into their
4069 own new (temporary) binding contour. */
4070 for (cp_binding_level *p = current_binding_level;
4071 p->kind != sk_function_parms;
4072 p = p->level_chain)
4073 p->more_cleanups_ok = 0;
4075 named_label_entry *ent = lookup_label_1 (name, false);
4076 tree decl = ent->label_decl;
4078 if (DECL_INITIAL (decl) != NULL_TREE)
4080 error ("duplicate label %qD", decl);
4081 return error_mark_node;
4083 else
4085 /* Mark label as having been defined. */
4086 DECL_INITIAL (decl) = error_mark_node;
4087 /* Say where in the source. */
4088 DECL_SOURCE_LOCATION (decl) = location;
4090 ent->binding_level = current_binding_level;
4091 ent->names_in_scope = current_binding_level->names;
4093 for (named_label_use_entry *use = ent->uses; use; use = use->next)
4094 check_previous_goto (decl, use);
4095 ent->uses = NULL;
4098 return decl;
4101 struct cp_switch
4103 cp_binding_level *level;
4104 struct cp_switch *next;
4105 /* The SWITCH_STMT being built. */
4106 tree switch_stmt;
4107 /* A splay-tree mapping the low element of a case range to the high
4108 element, or NULL_TREE if there is no high element. Used to
4109 determine whether or not a new case label duplicates an old case
4110 label. We need a tree, rather than simply a hash table, because
4111 of the GNU case range extension. */
4112 splay_tree cases;
4113 /* Remember whether a default: case label has been seen. */
4114 bool has_default_p;
4115 /* Remember whether a BREAK_STMT has been seen in this SWITCH_STMT. */
4116 bool break_stmt_seen_p;
4117 /* Set if inside of {FOR,DO,WHILE}_BODY nested inside of a switch,
4118 where BREAK_STMT doesn't belong to the SWITCH_STMT. */
4119 bool in_loop_body_p;
4122 /* A stack of the currently active switch statements. The innermost
4123 switch statement is on the top of the stack. There is no need to
4124 mark the stack for garbage collection because it is only active
4125 during the processing of the body of a function, and we never
4126 collect at that point. */
4128 static struct cp_switch *switch_stack;
4130 /* Called right after a switch-statement condition is parsed.
4131 SWITCH_STMT is the switch statement being parsed. */
4133 void
4134 push_switch (tree switch_stmt)
4136 struct cp_switch *p = XNEW (struct cp_switch);
4137 p->level = current_binding_level;
4138 p->next = switch_stack;
4139 p->switch_stmt = switch_stmt;
4140 p->cases = splay_tree_new (case_compare, NULL, NULL);
4141 p->has_default_p = false;
4142 p->break_stmt_seen_p = false;
4143 p->in_loop_body_p = false;
4144 switch_stack = p;
4147 void
4148 pop_switch (void)
4150 struct cp_switch *cs = switch_stack;
4152 /* Emit warnings as needed. */
4153 location_t switch_location = cp_expr_loc_or_input_loc (cs->switch_stmt);
4154 tree cond = SWITCH_STMT_COND (cs->switch_stmt);
4155 const bool bool_cond_p
4156 = (SWITCH_STMT_TYPE (cs->switch_stmt)
4157 && TREE_CODE (SWITCH_STMT_TYPE (cs->switch_stmt)) == BOOLEAN_TYPE);
4158 if (!processing_template_decl)
4159 c_do_switch_warnings (cs->cases, switch_location,
4160 SWITCH_STMT_TYPE (cs->switch_stmt), cond,
4161 bool_cond_p);
4163 /* For the benefit of block_may_fallthru remember if the switch body
4164 case labels cover all possible values and if there are break; stmts. */
4165 if (cs->has_default_p
4166 || (!processing_template_decl
4167 && c_switch_covers_all_cases_p (cs->cases,
4168 SWITCH_STMT_TYPE (cs->switch_stmt))))
4169 SWITCH_STMT_ALL_CASES_P (cs->switch_stmt) = 1;
4170 if (!cs->break_stmt_seen_p)
4171 SWITCH_STMT_NO_BREAK_P (cs->switch_stmt) = 1;
4172 /* Now that we're done with the switch warnings, set the switch type
4173 to the type of the condition if the index type was of scoped enum type.
4174 (Such types don't participate in the integer promotions.) We do this
4175 because of bit-fields whose declared type is a scoped enum type:
4176 gimplification will use the lowered index type, but convert the
4177 case values to SWITCH_STMT_TYPE, which would have been the declared type
4178 and verify_gimple_switch doesn't accept that. */
4179 if (is_bitfield_expr_with_lowered_type (cond))
4180 SWITCH_STMT_TYPE (cs->switch_stmt) = TREE_TYPE (cond);
4181 gcc_assert (!cs->in_loop_body_p);
4182 splay_tree_delete (cs->cases);
4183 switch_stack = switch_stack->next;
4184 free (cs);
4187 /* Note that a BREAK_STMT is about to be added. If it is inside of
4188 a SWITCH_STMT and not inside of a loop body inside of it, note
4189 in switch_stack we've seen a BREAK_STMT. */
4191 void
4192 note_break_stmt (void)
4194 if (switch_stack && !switch_stack->in_loop_body_p)
4195 switch_stack->break_stmt_seen_p = true;
4198 /* Note the start of processing of an iteration statement's body.
4199 The note_break_stmt function will do nothing while processing it.
4200 Return a flag that should be passed to note_iteration_stmt_body_end. */
4202 bool
4203 note_iteration_stmt_body_start (void)
4205 if (!switch_stack)
4206 return false;
4207 bool ret = switch_stack->in_loop_body_p;
4208 switch_stack->in_loop_body_p = true;
4209 return ret;
4212 /* Note the end of processing of an iteration statement's body. */
4214 void
4215 note_iteration_stmt_body_end (bool prev)
4217 if (switch_stack)
4218 switch_stack->in_loop_body_p = prev;
4221 /* Convert a case constant VALUE in a switch to the type TYPE of the switch
4222 condition. Note that if TYPE and VALUE are already integral we don't
4223 really do the conversion because the language-independent
4224 warning/optimization code will work better that way. */
4226 static tree
4227 case_conversion (tree type, tree value)
4229 if (value == NULL_TREE)
4230 return value;
4232 value = mark_rvalue_use (value);
4234 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
4235 type = type_promotes_to (type);
4237 tree ovalue = value;
4238 /* The constant-expression VALUE shall be a converted constant expression
4239 of the adjusted type of the switch condition, which doesn't allow
4240 narrowing conversions. */
4241 value = build_converted_constant_expr (type, value, tf_warning_or_error);
4243 if (cxx_dialect >= cxx11
4244 && (SCOPED_ENUM_P (type)
4245 || !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ovalue))))
4246 /* Use the converted value. */;
4247 else
4248 /* The already integral case. */
4249 value = ovalue;
4251 return cxx_constant_value (value);
4254 /* Note that we've seen a definition of a case label, and complain if this
4255 is a bad place for one. */
4257 tree
4258 finish_case_label (location_t loc, tree low_value, tree high_value)
4260 tree cond, r;
4261 cp_binding_level *p;
4262 tree type;
4264 if (low_value == NULL_TREE && high_value == NULL_TREE)
4265 switch_stack->has_default_p = true;
4267 if (processing_template_decl)
4269 tree label;
4271 /* For templates, just add the case label; we'll do semantic
4272 analysis at instantiation-time. */
4273 label = build_decl (loc, LABEL_DECL, NULL_TREE, void_type_node);
4274 return add_stmt (build_case_label (low_value, high_value, label));
4277 /* Find the condition on which this switch statement depends. */
4278 cond = SWITCH_STMT_COND (switch_stack->switch_stmt);
4279 if (cond && TREE_CODE (cond) == TREE_LIST)
4280 cond = TREE_VALUE (cond);
4282 if (!check_switch_goto (switch_stack->level))
4283 return error_mark_node;
4285 type = SWITCH_STMT_TYPE (switch_stack->switch_stmt);
4286 if (type == error_mark_node)
4287 return error_mark_node;
4289 low_value = case_conversion (type, low_value);
4290 high_value = case_conversion (type, high_value);
4292 r = c_add_case_label (loc, switch_stack->cases, cond, low_value, high_value);
4294 /* After labels, make any new cleanups in the function go into their
4295 own new (temporary) binding contour. */
4296 for (p = current_binding_level;
4297 p->kind != sk_function_parms;
4298 p = p->level_chain)
4299 p->more_cleanups_ok = 0;
4301 return r;
4304 struct typename_info {
4305 tree scope;
4306 tree name;
4307 tree template_id;
4308 bool enum_p;
4309 bool class_p;
4312 struct typename_hasher : ggc_ptr_hash<tree_node>
4314 typedef typename_info *compare_type;
4316 /* Hash a TYPENAME_TYPE. */
4318 static hashval_t
4319 hash (tree context, tree fullname)
4321 hashval_t hash = 0;
4322 hash = iterative_hash_object (context, hash);
4323 hash = iterative_hash_object (fullname, hash);
4324 return hash;
4327 static hashval_t
4328 hash (const typename_info *ti)
4330 return typename_hasher::hash (ti->scope, ti->template_id);
4333 static hashval_t
4334 hash (tree t)
4336 return typename_hasher::hash (TYPE_CONTEXT (t), TYPENAME_TYPE_FULLNAME (t));
4339 /* Compare two TYPENAME_TYPEs. */
4341 static bool
4342 equal (tree t1, const typename_info *t2)
4344 return (TYPE_IDENTIFIER (t1) == t2->name
4345 && TYPE_CONTEXT (t1) == t2->scope
4346 && TYPENAME_TYPE_FULLNAME (t1) == t2->template_id
4347 && TYPENAME_IS_ENUM_P (t1) == t2->enum_p
4348 && TYPENAME_IS_CLASS_P (t1) == t2->class_p);
4352 /* Build a TYPENAME_TYPE. If the type is `typename T::t', CONTEXT is
4353 the type of `T', NAME is the IDENTIFIER_NODE for `t'.
4355 Returns the new TYPENAME_TYPE. */
4357 static GTY (()) hash_table<typename_hasher> *typename_htab;
4359 tree
4360 build_typename_type (tree context, tree name, tree fullname,
4361 enum tag_types tag_type)
4363 typename_info ti;
4365 if (typename_htab == NULL)
4366 typename_htab = hash_table<typename_hasher>::create_ggc (61);
4368 ti.scope = FROB_CONTEXT (context);
4369 ti.name = name;
4370 ti.template_id = fullname;
4371 ti.enum_p = tag_type == enum_type;
4372 ti.class_p = (tag_type == class_type
4373 || tag_type == record_type
4374 || tag_type == union_type);
4375 hashval_t hash = typename_hasher::hash (&ti);
4377 /* See if we already have this type. */
4378 tree *e = typename_htab->find_slot_with_hash (&ti, hash, INSERT);
4379 tree t = *e;
4380 if (*e)
4381 t = *e;
4382 else
4384 /* Build the TYPENAME_TYPE. */
4385 t = cxx_make_type (TYPENAME_TYPE);
4386 TYPE_CONTEXT (t) = ti.scope;
4387 TYPENAME_TYPE_FULLNAME (t) = ti.template_id;
4388 TYPENAME_IS_ENUM_P (t) = ti.enum_p;
4389 TYPENAME_IS_CLASS_P (t) = ti.class_p;
4391 /* Build the corresponding TYPE_DECL. */
4392 tree d = build_decl (input_location, TYPE_DECL, name, t);
4393 TYPE_NAME (t) = d;
4394 TYPE_STUB_DECL (t) = d;
4395 DECL_CONTEXT (d) = ti.scope;
4396 DECL_ARTIFICIAL (d) = 1;
4398 /* Store it in the hash table. */
4399 *e = t;
4401 /* TYPENAME_TYPEs must always be compared structurally, because
4402 they may or may not resolve down to another type depending on
4403 the currently open classes. */
4404 SET_TYPE_STRUCTURAL_EQUALITY (t);
4407 return t;
4410 /* Resolve `typename CONTEXT::NAME'. TAG_TYPE indicates the tag
4411 provided to name the type. Returns an appropriate type, unless an
4412 error occurs, in which case error_mark_node is returned. If we
4413 locate a non-artificial TYPE_DECL and TF_KEEP_TYPE_DECL is set, we
4414 return that, rather than the _TYPE it corresponds to, in other
4415 cases we look through the type decl. If TF_ERROR is set, complain
4416 about errors, otherwise be quiet. */
4418 tree
4419 make_typename_type (tree context, tree name, enum tag_types tag_type,
4420 tsubst_flags_t complain)
4422 tree fullname;
4423 tree t;
4424 bool want_template;
4426 if (name == error_mark_node
4427 || context == NULL_TREE
4428 || context == error_mark_node)
4429 return error_mark_node;
4431 if (TYPE_P (name))
4433 if (!(TYPE_LANG_SPECIFIC (name)
4434 && (CLASSTYPE_IS_TEMPLATE (name)
4435 || CLASSTYPE_USE_TEMPLATE (name))))
4436 name = TYPE_IDENTIFIER (name);
4437 else
4438 /* Create a TEMPLATE_ID_EXPR for the type. */
4439 name = build_nt (TEMPLATE_ID_EXPR,
4440 CLASSTYPE_TI_TEMPLATE (name),
4441 CLASSTYPE_TI_ARGS (name));
4443 else if (TREE_CODE (name) == TYPE_DECL)
4444 name = DECL_NAME (name);
4446 fullname = name;
4448 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
4450 name = TREE_OPERAND (name, 0);
4451 if (DECL_TYPE_TEMPLATE_P (name))
4452 name = TREE_OPERAND (fullname, 0) = DECL_NAME (name);
4453 if (TREE_CODE (name) != IDENTIFIER_NODE)
4455 if (complain & tf_error)
4456 error ("%qD is not a type", name);
4457 return error_mark_node;
4460 if (TREE_CODE (name) == TEMPLATE_DECL)
4462 if (complain & tf_error)
4463 error ("%qD used without template arguments", name);
4464 return error_mark_node;
4466 else if (is_overloaded_fn (name))
4468 if (complain & tf_error)
4469 error ("%qD is a function, not a type", name);
4470 return error_mark_node;
4472 gcc_assert (identifier_p (name));
4473 gcc_assert (TYPE_P (context));
4475 if (TREE_CODE (context) == TYPE_PACK_EXPANSION)
4476 /* This can happen for C++17 variadic using (c++/88986). */;
4477 else if (!MAYBE_CLASS_TYPE_P (context))
4479 if (complain & tf_error)
4480 error ("%q#T is not a class", context);
4481 return error_mark_node;
4484 /* When the CONTEXT is a dependent type, NAME could refer to a
4485 dependent base class of CONTEXT. But look inside it anyway
4486 if CONTEXT is a currently open scope, in case it refers to a
4487 member of the current instantiation or a non-dependent base;
4488 lookup will stop when we hit a dependent base. */
4489 if (!dependent_scope_p (context))
4491 /* We generally don't ignore non-types during TYPENAME_TYPE lookup
4492 (as per [temp.res.general]/3), unless
4493 - the tag corresponds to a class-key or 'enum' so
4494 [basic.lookup.elab] applies, or
4495 - the tag corresponds to scope_type or tf_qualifying_scope is
4496 set so [basic.lookup.qual]/1 applies.
4497 TODO: If we'd set/track the scope_type tag thoroughly on all
4498 TYPENAME_TYPEs that are followed by :: then we wouldn't need the
4499 tf_qualifying_scope flag. */
4500 bool want_type = (tag_type != none_type && tag_type != typename_type)
4501 || (complain & tf_qualifying_scope);
4502 t = lookup_member (context, name, /*protect=*/2, want_type, complain);
4504 else
4505 t = NULL_TREE;
4507 if ((!t || TREE_CODE (t) == TREE_LIST) && dependent_type_p (context))
4508 return build_typename_type (context, name, fullname, tag_type);
4510 want_template = TREE_CODE (fullname) == TEMPLATE_ID_EXPR;
4512 if (!t)
4514 if (complain & tf_error)
4516 if (!COMPLETE_TYPE_P (context))
4517 cxx_incomplete_type_error (NULL_TREE, context);
4518 else
4519 error (want_template ? G_("no class template named %q#T in %q#T")
4520 : G_("no type named %q#T in %q#T"), name, context);
4522 return error_mark_node;
4525 /* Pull out the template from an injected-class-name (or multiple). */
4526 if (want_template)
4527 t = maybe_get_template_decl_from_type_decl (t);
4529 if (TREE_CODE (t) == TREE_LIST)
4531 if (complain & tf_error)
4533 error ("lookup of %qT in %qT is ambiguous", name, context);
4534 print_candidates (t);
4536 return error_mark_node;
4539 if (want_template && !DECL_TYPE_TEMPLATE_P (t))
4541 if (complain & tf_error)
4542 error ("%<typename %T::%D%> names %q#T, which is not a class template",
4543 context, name, t);
4544 return error_mark_node;
4546 if (!want_template && TREE_CODE (t) != TYPE_DECL)
4548 if ((complain & tf_tst_ok) && cxx_dialect >= cxx17
4549 && DECL_TYPE_TEMPLATE_P (t))
4550 /* The caller permits this typename-specifier to name a template
4551 (because it appears in a CTAD-enabled context). */;
4552 else
4554 if (complain & tf_error)
4555 error ("%<typename %T::%D%> names %q#D, which is not a type",
4556 context, name, t);
4557 return error_mark_node;
4561 if (!check_accessibility_of_qualified_id (t, /*object_type=*/NULL_TREE,
4562 context, complain))
4563 return error_mark_node;
4565 if (!want_template && DECL_TYPE_TEMPLATE_P (t))
4566 return make_template_placeholder (t);
4568 if (want_template)
4570 t = lookup_template_class (t, TREE_OPERAND (fullname, 1),
4571 NULL_TREE, context,
4572 /*entering_scope=*/0,
4573 complain | tf_user);
4574 if (t == error_mark_node)
4575 return error_mark_node;
4576 t = TYPE_NAME (t);
4579 if (DECL_ARTIFICIAL (t) || !(complain & tf_keep_type_decl))
4580 t = TREE_TYPE (t);
4582 maybe_record_typedef_use (t);
4584 return t;
4587 /* Resolve `CONTEXT::template NAME'. Returns a TEMPLATE_DECL if the name
4588 can be resolved or an UNBOUND_CLASS_TEMPLATE, unless an error occurs,
4589 in which case error_mark_node is returned.
4591 If PARM_LIST is non-NULL, also make sure that the template parameter
4592 list of TEMPLATE_DECL matches.
4594 If COMPLAIN zero, don't complain about any errors that occur. */
4596 tree
4597 make_unbound_class_template (tree context, tree name, tree parm_list,
4598 tsubst_flags_t complain)
4600 if (TYPE_P (name))
4601 name = TYPE_IDENTIFIER (name);
4602 else if (DECL_P (name))
4603 name = DECL_NAME (name);
4604 gcc_assert (identifier_p (name));
4606 if (!dependent_type_p (context)
4607 || currently_open_class (context))
4609 tree tmpl = NULL_TREE;
4611 if (MAYBE_CLASS_TYPE_P (context))
4612 tmpl = lookup_field (context, name, 0, false);
4614 if (tmpl && TREE_CODE (tmpl) == TYPE_DECL)
4615 tmpl = maybe_get_template_decl_from_type_decl (tmpl);
4617 if (!tmpl || !DECL_TYPE_TEMPLATE_P (tmpl))
4619 if (complain & tf_error)
4620 error ("no class template named %q#T in %q#T", name, context);
4621 return error_mark_node;
4624 if (parm_list
4625 && !comp_template_parms (DECL_TEMPLATE_PARMS (tmpl), parm_list))
4627 if (complain & tf_error)
4629 error ("template parameters do not match template %qD", tmpl);
4630 inform (DECL_SOURCE_LOCATION (tmpl),
4631 "%qD declared here", tmpl);
4633 return error_mark_node;
4636 if (!perform_or_defer_access_check (TYPE_BINFO (context), tmpl, tmpl,
4637 complain))
4638 return error_mark_node;
4640 return tmpl;
4643 return make_unbound_class_template_raw (context, name, parm_list);
4646 /* Build an UNBOUND_CLASS_TEMPLATE. */
4648 tree
4649 make_unbound_class_template_raw (tree context, tree name, tree parm_list)
4651 /* Build the UNBOUND_CLASS_TEMPLATE. */
4652 tree t = cxx_make_type (UNBOUND_CLASS_TEMPLATE);
4653 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
4654 TREE_TYPE (t) = NULL_TREE;
4655 SET_TYPE_STRUCTURAL_EQUALITY (t);
4657 /* Build the corresponding TEMPLATE_DECL. */
4658 tree d = build_decl (input_location, TEMPLATE_DECL, name, t);
4659 TYPE_NAME (t) = d;
4660 TYPE_STUB_DECL (t) = d;
4661 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
4662 DECL_ARTIFICIAL (d) = 1;
4663 DECL_TEMPLATE_PARMS (d) = parm_list;
4665 return t;
4670 /* Push the declarations of builtin types into the global namespace.
4671 RID_INDEX is the index of the builtin type in the array
4672 RID_POINTERS. NAME is the name used when looking up the builtin
4673 type. TYPE is the _TYPE node for the builtin type.
4675 The calls to set_global_binding below should be
4676 eliminated. Built-in types should not be looked up name; their
4677 names are keywords that the parser can recognize. However, there
4678 is code in c-common.cc that uses identifier_global_value to look up
4679 built-in types by name. */
4681 void
4682 record_builtin_type (enum rid rid_index,
4683 const char* name,
4684 tree type)
4686 tree decl = NULL_TREE;
4688 if (name)
4690 tree tname = get_identifier (name);
4691 tree tdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, tname, type);
4692 DECL_ARTIFICIAL (tdecl) = 1;
4693 set_global_binding (tdecl);
4694 decl = tdecl;
4697 if ((int) rid_index < (int) RID_MAX)
4698 if (tree rname = ridpointers[(int) rid_index])
4699 if (!decl || DECL_NAME (decl) != rname)
4701 tree rdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, rname, type);
4702 DECL_ARTIFICIAL (rdecl) = 1;
4703 set_global_binding (rdecl);
4704 if (!decl)
4705 decl = rdecl;
4708 if (decl)
4710 if (!TYPE_NAME (type))
4711 TYPE_NAME (type) = decl;
4712 debug_hooks->type_decl (decl, 0);
4716 /* Push a type into the namespace so that the back ends ignore it. */
4718 static void
4719 record_unknown_type (tree type, const char* name)
4721 tree decl = pushdecl (build_decl (UNKNOWN_LOCATION,
4722 TYPE_DECL, get_identifier (name), type));
4723 /* Make sure the "unknown type" typedecl gets ignored for debug info. */
4724 DECL_IGNORED_P (decl) = 1;
4725 TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
4726 TYPE_SIZE (type) = TYPE_SIZE (void_type_node);
4727 SET_TYPE_ALIGN (type, 1);
4728 TYPE_USER_ALIGN (type) = 0;
4729 SET_TYPE_MODE (type, TYPE_MODE (void_type_node));
4732 /* Create all the predefined identifiers. */
4734 static void
4735 initialize_predefined_identifiers (void)
4737 struct predefined_identifier
4739 const char *name; /* Name. */
4740 tree *node; /* Node to store it in. */
4741 cp_identifier_kind kind; /* Kind of identifier. */
4744 /* A table of identifiers to create at startup. */
4745 static const predefined_identifier predefined_identifiers[] = {
4746 {"C++", &lang_name_cplusplus, cik_normal},
4747 {"C", &lang_name_c, cik_normal},
4748 /* Some of these names have a trailing space so that it is
4749 impossible for them to conflict with names written by users. */
4750 {"__ct ", &ctor_identifier, cik_ctor},
4751 {"__ct_base ", &base_ctor_identifier, cik_ctor},
4752 {"__ct_comp ", &complete_ctor_identifier, cik_ctor},
4753 {"__dt ", &dtor_identifier, cik_dtor},
4754 {"__dt_base ", &base_dtor_identifier, cik_dtor},
4755 {"__dt_comp ", &complete_dtor_identifier, cik_dtor},
4756 {"__dt_del ", &deleting_dtor_identifier, cik_dtor},
4757 {"__conv_op ", &conv_op_identifier, cik_conv_op},
4758 {"__in_chrg", &in_charge_identifier, cik_normal},
4759 {"__as_base ", &as_base_identifier, cik_normal},
4760 {"this", &this_identifier, cik_normal},
4761 {"__delta", &delta_identifier, cik_normal},
4762 {"__pfn", &pfn_identifier, cik_normal},
4763 {"_vptr", &vptr_identifier, cik_normal},
4764 {"__vtt_parm", &vtt_parm_identifier, cik_normal},
4765 {"::", &global_identifier, cik_normal},
4766 /* The demangler expects anonymous namespaces to be called
4767 something starting with '_GLOBAL__N_'. It no longer needs
4768 to be unique to the TU. */
4769 {"_GLOBAL__N_1", &anon_identifier, cik_normal},
4770 {"auto", &auto_identifier, cik_normal},
4771 {"decltype(auto)", &decltype_auto_identifier, cik_normal},
4772 {"initializer_list", &init_list_identifier, cik_normal},
4773 {"__for_range ", &for_range__identifier, cik_normal},
4774 {"__for_begin ", &for_begin__identifier, cik_normal},
4775 {"__for_end ", &for_end__identifier, cik_normal},
4776 {"__for_range", &for_range_identifier, cik_normal},
4777 {"__for_begin", &for_begin_identifier, cik_normal},
4778 {"__for_end", &for_end_identifier, cik_normal},
4779 {"abi_tag", &abi_tag_identifier, cik_normal},
4780 {"aligned", &aligned_identifier, cik_normal},
4781 {"begin", &begin_identifier, cik_normal},
4782 {"end", &end_identifier, cik_normal},
4783 {"get", &get__identifier, cik_normal},
4784 {"gnu", &gnu_identifier, cik_normal},
4785 {"tuple_element", &tuple_element_identifier, cik_normal},
4786 {"tuple_size", &tuple_size_identifier, cik_normal},
4787 {"type", &type_identifier, cik_normal},
4788 {"value", &value_identifier, cik_normal},
4789 {"_FUN", &fun_identifier, cik_normal},
4790 {"__closure", &closure_identifier, cik_normal},
4791 {"heap uninit", &heap_uninit_identifier, cik_normal},
4792 {"heap ", &heap_identifier, cik_normal},
4793 {"heap deleted", &heap_deleted_identifier, cik_normal},
4794 {"heap [] uninit", &heap_vec_uninit_identifier, cik_normal},
4795 {"heap []", &heap_vec_identifier, cik_normal},
4796 {"omp", &omp_identifier, cik_normal},
4797 {NULL, NULL, cik_normal}
4800 for (const predefined_identifier *pid = predefined_identifiers;
4801 pid->name; ++pid)
4803 *pid->node = get_identifier (pid->name);
4804 /* Some of these identifiers already have a special kind. */
4805 if (pid->kind != cik_normal)
4806 set_identifier_kind (*pid->node, pid->kind);
4810 /* Create the predefined scalar types of C,
4811 and some nodes representing standard constants (0, 1, (void *)0).
4812 Initialize the global binding level.
4813 Make definitions for built-in primitive functions. */
4815 void
4816 cxx_init_decl_processing (void)
4818 tree void_ftype;
4819 tree void_ftype_ptr;
4821 /* Create all the identifiers we need. */
4822 initialize_predefined_identifiers ();
4824 /* Create the global variables. */
4825 push_to_top_level ();
4827 current_function_decl = NULL_TREE;
4828 current_binding_level = NULL;
4829 /* Enter the global namespace. */
4830 gcc_assert (global_namespace == NULL_TREE);
4831 global_namespace = build_lang_decl (NAMESPACE_DECL, global_identifier,
4832 void_type_node);
4833 TREE_PUBLIC (global_namespace) = true;
4834 DECL_MODULE_EXPORT_P (global_namespace) = true;
4835 DECL_CONTEXT (global_namespace)
4836 = build_translation_unit_decl (get_identifier (main_input_filename));
4837 /* Remember whether we want the empty class passing ABI change warning
4838 in this TU. */
4839 TRANSLATION_UNIT_WARN_EMPTY_P (DECL_CONTEXT (global_namespace))
4840 = warn_abi && abi_version_crosses (12);
4841 debug_hooks->register_main_translation_unit
4842 (DECL_CONTEXT (global_namespace));
4843 begin_scope (sk_namespace, global_namespace);
4844 current_namespace = global_namespace;
4846 if (flag_visibility_ms_compat)
4847 default_visibility = VISIBILITY_HIDDEN;
4849 /* Initially, C. */
4850 current_lang_name = lang_name_c;
4852 /* Create the `std' namespace. */
4853 push_namespace (get_identifier ("std"));
4854 std_node = current_namespace;
4855 pop_namespace ();
4857 flag_noexcept_type = (cxx_dialect >= cxx17);
4859 c_common_nodes_and_builtins ();
4861 tree bool_ftype = build_function_type_list (boolean_type_node, NULL_TREE);
4862 tree decl
4863 = add_builtin_function ("__builtin_is_constant_evaluated",
4864 bool_ftype, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
4865 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4866 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4868 /* The concrete return type of __builtin_source_location is
4869 const std::source_location::__impl*, but we can't form the type
4870 at this point. So we initially declare it with an auto return
4871 type which we then "deduce" from require_deduced_type upon first use. */
4872 tree auto_ftype = build_function_type_list (make_auto (), NULL_TREE);
4873 decl = add_builtin_function ("__builtin_source_location",
4874 auto_ftype, CP_BUILT_IN_SOURCE_LOCATION,
4875 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4876 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4878 tree bool_vaftype = build_varargs_function_type_list (boolean_type_node,
4879 NULL_TREE);
4880 decl
4881 = add_builtin_function ("__builtin_is_corresponding_member",
4882 bool_vaftype,
4883 CP_BUILT_IN_IS_CORRESPONDING_MEMBER,
4884 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4885 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4887 decl
4888 = add_builtin_function ("__builtin_is_pointer_interconvertible_with_class",
4889 bool_vaftype,
4890 CP_BUILT_IN_IS_POINTER_INTERCONVERTIBLE_WITH_CLASS,
4891 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4892 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4894 integer_two_node = build_int_cst (NULL_TREE, 2);
4896 /* Guess at the initial static decls size. */
4897 vec_alloc (static_decls, 500);
4899 /* ... and keyed classes. */
4900 vec_alloc (keyed_classes, 100);
4902 record_builtin_type (RID_BOOL, "bool", boolean_type_node);
4903 truthvalue_type_node = boolean_type_node;
4904 truthvalue_false_node = boolean_false_node;
4905 truthvalue_true_node = boolean_true_node;
4907 empty_except_spec = build_tree_list (NULL_TREE, NULL_TREE);
4908 noexcept_true_spec = build_tree_list (boolean_true_node, NULL_TREE);
4909 noexcept_false_spec = build_tree_list (boolean_false_node, NULL_TREE);
4910 noexcept_deferred_spec = build_tree_list (make_node (DEFERRED_NOEXCEPT),
4911 NULL_TREE);
4913 #if 0
4914 record_builtin_type (RID_MAX, NULL, string_type_node);
4915 #endif
4917 delta_type_node = ptrdiff_type_node;
4918 vtable_index_type = ptrdiff_type_node;
4920 vtt_parm_type = build_pointer_type (const_ptr_type_node);
4921 void_ftype = build_function_type_list (void_type_node, NULL_TREE);
4922 void_ftype_ptr = build_function_type_list (void_type_node,
4923 ptr_type_node, NULL_TREE);
4924 void_ftype_ptr
4925 = build_exception_variant (void_ftype_ptr, empty_except_spec);
4927 /* Create the conversion operator marker. This operator's DECL_NAME
4928 is in the identifier table, so we can use identifier equality to
4929 find it. */
4930 conv_op_marker = build_lang_decl (FUNCTION_DECL, conv_op_identifier,
4931 void_ftype);
4933 /* C++ extensions */
4935 unknown_type_node = make_node (LANG_TYPE);
4936 record_unknown_type (unknown_type_node, "unknown type");
4938 /* Indirecting an UNKNOWN_TYPE node yields an UNKNOWN_TYPE node. */
4939 TREE_TYPE (unknown_type_node) = unknown_type_node;
4941 /* Looking up TYPE_POINTER_TO and TYPE_REFERENCE_TO yield the same
4942 result. */
4943 TYPE_POINTER_TO (unknown_type_node) = unknown_type_node;
4944 TYPE_REFERENCE_TO (unknown_type_node) = unknown_type_node;
4946 init_list_type_node = make_node (LANG_TYPE);
4947 record_unknown_type (init_list_type_node, "init list");
4949 /* Used when parsing to distinguish parameter-lists () and (void). */
4950 explicit_void_list_node = build_tree_list (NULL_TREE, void_type_node);
4953 /* Make sure we get a unique function type, so we can give
4954 its pointer type a name. (This wins for gdb.) */
4955 tree vfunc_type = make_node (FUNCTION_TYPE);
4956 TREE_TYPE (vfunc_type) = integer_type_node;
4957 TYPE_ARG_TYPES (vfunc_type) = NULL_TREE;
4958 layout_type (vfunc_type);
4960 vtable_entry_type = build_pointer_type (vfunc_type);
4962 record_builtin_type (RID_MAX, "__vtbl_ptr_type", vtable_entry_type);
4964 vtbl_type_node
4965 = build_cplus_array_type (vtable_entry_type, NULL_TREE);
4966 layout_type (vtbl_type_node);
4967 vtbl_type_node = cp_build_qualified_type (vtbl_type_node, TYPE_QUAL_CONST);
4968 record_builtin_type (RID_MAX, NULL, vtbl_type_node);
4969 vtbl_ptr_type_node = build_pointer_type (vtable_entry_type);
4970 layout_type (vtbl_ptr_type_node);
4971 record_builtin_type (RID_MAX, NULL, vtbl_ptr_type_node);
4973 push_namespace (get_identifier ("__cxxabiv1"));
4974 abi_node = current_namespace;
4975 pop_namespace ();
4977 any_targ_node = make_node (LANG_TYPE);
4978 record_unknown_type (any_targ_node, "any type");
4980 /* Now, C++. */
4981 current_lang_name = lang_name_cplusplus;
4983 if (aligned_new_threshold > 1
4984 && !pow2p_hwi (aligned_new_threshold))
4986 error ("%<-faligned-new=%d%> is not a power of two",
4987 aligned_new_threshold);
4988 aligned_new_threshold = 1;
4990 if (aligned_new_threshold == -1)
4991 aligned_new_threshold = (cxx_dialect >= cxx17) ? 1 : 0;
4992 if (aligned_new_threshold == 1)
4993 aligned_new_threshold = malloc_alignment () / BITS_PER_UNIT;
4996 tree newattrs, extvisattr;
4997 tree newtype, deltype;
4998 tree ptr_ftype_sizetype;
4999 tree new_eh_spec;
5001 ptr_ftype_sizetype
5002 = build_function_type_list (ptr_type_node, size_type_node, NULL_TREE);
5003 if (cxx_dialect == cxx98)
5005 tree bad_alloc_id;
5006 tree bad_alloc_type_node;
5007 tree bad_alloc_decl;
5009 push_nested_namespace (std_node);
5010 bad_alloc_id = get_identifier ("bad_alloc");
5011 bad_alloc_type_node = make_class_type (RECORD_TYPE);
5012 TYPE_CONTEXT (bad_alloc_type_node) = current_namespace;
5013 bad_alloc_decl
5014 = create_implicit_typedef (bad_alloc_id, bad_alloc_type_node);
5015 DECL_CONTEXT (bad_alloc_decl) = current_namespace;
5016 pop_nested_namespace (std_node);
5018 new_eh_spec
5019 = add_exception_specifier (NULL_TREE, bad_alloc_type_node, -1);
5021 else
5022 new_eh_spec = noexcept_false_spec;
5024 /* Ensure attribs.cc is initialized. */
5025 init_attributes ();
5027 extvisattr = build_tree_list (get_identifier ("externally_visible"),
5028 NULL_TREE);
5029 newattrs = tree_cons (get_identifier ("alloc_size"),
5030 build_tree_list (NULL_TREE, integer_one_node),
5031 extvisattr);
5032 newtype = cp_build_type_attribute_variant (ptr_ftype_sizetype, newattrs);
5033 newtype = build_exception_variant (newtype, new_eh_spec);
5034 deltype = cp_build_type_attribute_variant (void_ftype_ptr, extvisattr);
5035 deltype = build_exception_variant (deltype, empty_except_spec);
5036 tree opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
5037 DECL_IS_MALLOC (opnew) = 1;
5038 DECL_SET_IS_OPERATOR_NEW (opnew, true);
5039 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
5040 opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
5041 DECL_IS_MALLOC (opnew) = 1;
5042 DECL_SET_IS_OPERATOR_NEW (opnew, true);
5043 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
5044 tree opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
5045 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5046 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5047 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
5048 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5049 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5050 if (flag_sized_deallocation)
5052 /* Also push the sized deallocation variants:
5053 void operator delete(void*, std::size_t) throw();
5054 void operator delete[](void*, std::size_t) throw(); */
5055 tree void_ftype_ptr_size
5056 = build_function_type_list (void_type_node, ptr_type_node,
5057 size_type_node, NULL_TREE);
5058 deltype = cp_build_type_attribute_variant (void_ftype_ptr_size,
5059 extvisattr);
5060 deltype = build_exception_variant (deltype, empty_except_spec);
5061 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
5062 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5063 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5064 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
5065 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5066 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5069 if (aligned_new_threshold)
5071 push_nested_namespace (std_node);
5072 tree align_id = get_identifier ("align_val_t");
5073 align_type_node = start_enum (align_id, NULL_TREE, size_type_node,
5074 NULL_TREE, /*scoped*/true, NULL);
5075 pop_nested_namespace (std_node);
5077 /* operator new (size_t, align_val_t); */
5078 newtype = build_function_type_list (ptr_type_node, size_type_node,
5079 align_type_node, NULL_TREE);
5080 newtype = cp_build_type_attribute_variant (newtype, newattrs);
5081 newtype = build_exception_variant (newtype, new_eh_spec);
5082 opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
5083 DECL_IS_MALLOC (opnew) = 1;
5084 DECL_SET_IS_OPERATOR_NEW (opnew, true);
5085 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
5086 opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
5087 DECL_IS_MALLOC (opnew) = 1;
5088 DECL_SET_IS_OPERATOR_NEW (opnew, true);
5089 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
5091 /* operator delete (void *, align_val_t); */
5092 deltype = build_function_type_list (void_type_node, ptr_type_node,
5093 align_type_node, NULL_TREE);
5094 deltype = cp_build_type_attribute_variant (deltype, extvisattr);
5095 deltype = build_exception_variant (deltype, empty_except_spec);
5096 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
5097 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5098 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5099 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
5100 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5101 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5103 if (flag_sized_deallocation)
5105 /* operator delete (void *, size_t, align_val_t); */
5106 deltype = build_function_type_list (void_type_node, ptr_type_node,
5107 size_type_node, align_type_node,
5108 NULL_TREE);
5109 deltype = cp_build_type_attribute_variant (deltype, extvisattr);
5110 deltype = build_exception_variant (deltype, empty_except_spec);
5111 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
5112 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5113 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5114 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
5115 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
5116 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
5120 /* C++-specific nullptr initialization. */
5121 if (abi_version_at_least (9))
5122 SET_TYPE_ALIGN (nullptr_type_node, GET_MODE_ALIGNMENT (ptr_mode));
5123 record_builtin_type (RID_MAX, "decltype(nullptr)", nullptr_type_node);
5126 if (! supports_one_only ())
5127 flag_weak = 0;
5129 abort_fndecl
5130 = build_library_fn_ptr ("__cxa_pure_virtual", void_ftype,
5131 ECF_NORETURN | ECF_NOTHROW | ECF_COLD);
5132 if (flag_weak)
5133 /* If no definition is available, resolve references to NULL. */
5134 declare_weak (abort_fndecl);
5136 /* Perform other language dependent initializations. */
5137 init_class_processing ();
5138 init_rtti_processing ();
5139 init_template_processing ();
5141 if (flag_exceptions)
5142 init_exception_processing ();
5144 if (modules_p ())
5145 init_modules (parse_in);
5147 make_fname_decl = cp_make_fname_decl;
5148 start_fname_decls ();
5150 /* Show we use EH for cleanups. */
5151 if (flag_exceptions)
5152 using_eh_for_cleanups ();
5154 /* Check that the hardware interference sizes are at least
5155 alignof(max_align_t), as required by the standard. */
5156 const int max_align = max_align_t_align () / BITS_PER_UNIT;
5157 if (OPTION_SET_P (param_destruct_interfere_size))
5159 if (param_destruct_interfere_size < max_align)
5160 error ("%<--param destructive-interference-size=%d%> is less than "
5161 "%d", param_destruct_interfere_size, max_align);
5162 else if (param_destruct_interfere_size < param_l1_cache_line_size)
5163 warning (OPT_Winterference_size,
5164 "%<--param destructive-interference-size=%d%> "
5165 "is less than %<--param l1-cache-line-size=%d%>",
5166 param_destruct_interfere_size, param_l1_cache_line_size);
5168 else if (param_destruct_interfere_size)
5169 /* Assume the internal value is OK. */;
5170 else if (param_l1_cache_line_size >= max_align)
5171 param_destruct_interfere_size = param_l1_cache_line_size;
5172 /* else leave it unset. */
5174 if (OPTION_SET_P (param_construct_interfere_size))
5176 if (param_construct_interfere_size < max_align)
5177 error ("%<--param constructive-interference-size=%d%> is less than "
5178 "%d", param_construct_interfere_size, max_align);
5179 else if (param_construct_interfere_size > param_l1_cache_line_size
5180 && param_l1_cache_line_size >= max_align)
5181 warning (OPT_Winterference_size,
5182 "%<--param constructive-interference-size=%d%> "
5183 "is greater than %<--param l1-cache-line-size=%d%>",
5184 param_construct_interfere_size, param_l1_cache_line_size);
5186 else if (param_construct_interfere_size)
5187 /* Assume the internal value is OK. */;
5188 else if (param_l1_cache_line_size >= max_align)
5189 param_construct_interfere_size = param_l1_cache_line_size;
5192 /* Enter an abi node in global-module context. returns a cookie to
5193 give to pop_abi_namespace. */
5195 unsigned
5196 push_abi_namespace (tree node)
5198 push_nested_namespace (node);
5199 push_visibility ("default", 2);
5200 unsigned flags = module_kind;
5201 module_kind = 0;
5202 return flags;
5205 /* Pop an abi namespace, FLAGS is the cookie push_abi_namespace gave
5206 you. */
5208 void
5209 pop_abi_namespace (unsigned flags, tree node)
5211 module_kind = flags;
5212 pop_visibility (2);
5213 pop_nested_namespace (node);
5216 /* Create the VAR_DECL for __FUNCTION__ etc. ID is the name to give
5217 the decl, LOC is the location to give the decl, NAME is the
5218 initialization string and TYPE_DEP indicates whether NAME depended
5219 on the type of the function. We make use of that to detect
5220 __PRETTY_FUNCTION__ inside a template fn. This is being done lazily
5221 at the point of first use, so we mustn't push the decl now. */
5223 static tree
5224 cp_make_fname_decl (location_t loc, tree id, int type_dep)
5226 tree domain = NULL_TREE;
5227 tree init = NULL_TREE;
5229 if (!(type_dep && current_function_decl && in_template_context))
5231 const char *name = NULL;
5232 bool release_name = false;
5234 if (current_function_decl == NULL_TREE)
5235 name = "top level";
5236 else if (type_dep == 0)
5238 /* __FUNCTION__ */
5239 name = fname_as_string (type_dep);
5240 release_name = true;
5242 else
5244 /* __PRETTY_FUNCTION__ */
5245 gcc_checking_assert (type_dep == 1);
5246 name = cxx_printable_name (current_function_decl, 2);
5249 size_t length = strlen (name);
5250 domain = build_index_type (size_int (length));
5251 init = build_string (length + 1, name);
5252 if (release_name)
5253 free (const_cast<char *> (name));
5256 tree type = cp_build_qualified_type (char_type_node, TYPE_QUAL_CONST);
5257 type = build_cplus_array_type (type, domain);
5259 if (init)
5260 TREE_TYPE (init) = type;
5261 else
5262 init = error_mark_node;
5264 tree decl = build_decl (loc, VAR_DECL, id, type);
5266 TREE_READONLY (decl) = 1;
5267 DECL_ARTIFICIAL (decl) = 1;
5268 DECL_DECLARED_CONSTEXPR_P (decl) = 1;
5269 TREE_STATIC (decl) = 1;
5271 TREE_USED (decl) = 1;
5273 SET_DECL_VALUE_EXPR (decl, init);
5274 DECL_HAS_VALUE_EXPR_P (decl) = 1;
5275 /* For decl_constant_var_p. */
5276 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
5278 if (current_function_decl)
5280 DECL_CONTEXT (decl) = current_function_decl;
5281 decl = pushdecl_outermost_localscope (decl);
5282 if (decl != error_mark_node)
5283 add_decl_expr (decl);
5285 else
5287 DECL_THIS_STATIC (decl) = true;
5288 decl = pushdecl_top_level_and_finish (decl, NULL_TREE);
5291 return decl;
5294 /* Install DECL as a builtin function at current global scope. Return
5295 the new decl (if we found an existing version). Also installs it
5296 into ::std, if it's not '_*'. */
5298 tree
5299 cxx_builtin_function (tree decl)
5301 retrofit_lang_decl (decl);
5303 DECL_ARTIFICIAL (decl) = 1;
5304 SET_DECL_LANGUAGE (decl, lang_c);
5305 /* Runtime library routines are, by definition, available in an
5306 external shared object. */
5307 DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
5308 DECL_VISIBILITY_SPECIFIED (decl) = 1;
5310 tree id = DECL_NAME (decl);
5311 const char *name = IDENTIFIER_POINTER (id);
5312 bool hiding = false;
5313 if (name[0] != '_' || name[1] != '_')
5314 /* In the user's namespace, it must be declared before use. */
5315 hiding = true;
5316 else if (IDENTIFIER_LENGTH (id) > strlen ("___chk")
5317 && !startswith (name + 2, "builtin_")
5318 && 0 == memcmp (name + IDENTIFIER_LENGTH (id) - strlen ("_chk"),
5319 "_chk", strlen ("_chk") + 1))
5320 /* Treat __*_chk fortification functions as anticipated as well,
5321 unless they are __builtin_*_chk. */
5322 hiding = true;
5324 /* All builtins that don't begin with an '_' should additionally
5325 go in the 'std' namespace. */
5326 if (name[0] != '_')
5328 tree std_decl = copy_decl (decl);
5330 push_nested_namespace (std_node);
5331 DECL_CONTEXT (std_decl) = FROB_CONTEXT (std_node);
5332 pushdecl (std_decl, hiding);
5333 pop_nested_namespace (std_node);
5336 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5337 decl = pushdecl (decl, hiding);
5339 return decl;
5342 /* Like cxx_builtin_function, but guarantee the function is added to the global
5343 scope. This is to allow function specific options to add new machine
5344 dependent builtins when the target ISA changes via attribute((target(...)))
5345 which saves space on program startup if the program does not use non-generic
5346 ISAs. */
5348 tree
5349 cxx_builtin_function_ext_scope (tree decl)
5351 push_nested_namespace (global_namespace);
5352 decl = cxx_builtin_function (decl);
5353 pop_nested_namespace (global_namespace);
5355 return decl;
5358 /* Implement LANG_HOOKS_SIMULATE_BUILTIN_FUNCTION_DECL. */
5360 tree
5361 cxx_simulate_builtin_function_decl (tree decl)
5363 retrofit_lang_decl (decl);
5365 DECL_ARTIFICIAL (decl) = 1;
5366 SET_DECL_LANGUAGE (decl, lang_cplusplus);
5367 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5368 return pushdecl (decl);
5371 /* Generate a FUNCTION_DECL with the typical flags for a runtime library
5372 function. Not called directly. */
5374 static tree
5375 build_library_fn (tree name, enum tree_code operator_code, tree type,
5376 int ecf_flags)
5378 tree fn = build_lang_decl (FUNCTION_DECL, name, type);
5379 DECL_EXTERNAL (fn) = 1;
5380 TREE_PUBLIC (fn) = 1;
5381 DECL_ARTIFICIAL (fn) = 1;
5382 DECL_OVERLOADED_OPERATOR_CODE_RAW (fn)
5383 = OVL_OP_INFO (false, operator_code)->ovl_op_code;
5384 SET_DECL_LANGUAGE (fn, lang_c);
5385 /* Runtime library routines are, by definition, available in an
5386 external shared object. */
5387 DECL_VISIBILITY (fn) = VISIBILITY_DEFAULT;
5388 DECL_VISIBILITY_SPECIFIED (fn) = 1;
5389 set_call_expr_flags (fn, ecf_flags);
5390 return fn;
5393 /* Returns the _DECL for a library function with C++ linkage. */
5395 static tree
5396 build_cp_library_fn (tree name, enum tree_code operator_code, tree type,
5397 int ecf_flags)
5399 tree fn = build_library_fn (name, operator_code, type, ecf_flags);
5400 DECL_CONTEXT (fn) = FROB_CONTEXT (current_namespace);
5401 SET_DECL_LANGUAGE (fn, lang_cplusplus);
5402 return fn;
5405 /* Like build_library_fn, but takes a C string instead of an
5406 IDENTIFIER_NODE. */
5408 tree
5409 build_library_fn_ptr (const char* name, tree type, int ecf_flags)
5411 return build_library_fn (get_identifier (name), ERROR_MARK, type, ecf_flags);
5414 /* Like build_cp_library_fn, but takes a C string instead of an
5415 IDENTIFIER_NODE. */
5417 tree
5418 build_cp_library_fn_ptr (const char* name, tree type, int ecf_flags)
5420 return build_cp_library_fn (get_identifier (name), ERROR_MARK, type,
5421 ecf_flags);
5424 /* Like build_library_fn, but also pushes the function so that we will
5425 be able to find it via get_global_binding. Also, the function
5426 may throw exceptions listed in RAISES. */
5428 tree
5429 push_library_fn (tree name, tree type, tree raises, int ecf_flags)
5431 if (raises)
5432 type = build_exception_variant (type, raises);
5434 tree fn = build_library_fn (name, ERROR_MARK, type, ecf_flags);
5435 return pushdecl_top_level (fn);
5438 /* Like build_cp_library_fn, but also pushes the function so that it
5439 will be found by normal lookup. */
5441 static tree
5442 push_cp_library_fn (enum tree_code operator_code, tree type,
5443 int ecf_flags)
5445 tree fn = build_cp_library_fn (ovl_op_identifier (false, operator_code),
5446 operator_code, type, ecf_flags);
5447 pushdecl (fn);
5448 if (flag_tm)
5449 apply_tm_attr (fn, get_identifier ("transaction_safe"));
5450 return fn;
5453 /* Like push_library_fn, but also note that this function throws
5454 and does not return. Used for __throw_foo and the like. */
5456 tree
5457 push_throw_library_fn (tree name, tree type)
5459 tree fn = push_library_fn (name, type, NULL_TREE,
5460 ECF_NORETURN | ECF_XTHROW | ECF_COLD);
5461 return fn;
5464 /* When we call finish_struct for an anonymous union, we create
5465 default copy constructors and such. But, an anonymous union
5466 shouldn't have such things; this function undoes the damage to the
5467 anonymous union type T.
5469 (The reason that we create the synthesized methods is that we don't
5470 distinguish `union { int i; }' from `typedef union { int i; } U'.
5471 The first is an anonymous union; the second is just an ordinary
5472 union type.) */
5474 void
5475 fixup_anonymous_aggr (tree t)
5477 /* Wipe out memory of synthesized methods. */
5478 TYPE_HAS_USER_CONSTRUCTOR (t) = 0;
5479 TYPE_HAS_DEFAULT_CONSTRUCTOR (t) = 0;
5480 TYPE_HAS_COPY_CTOR (t) = 0;
5481 TYPE_HAS_CONST_COPY_CTOR (t) = 0;
5482 TYPE_HAS_COPY_ASSIGN (t) = 0;
5483 TYPE_HAS_CONST_COPY_ASSIGN (t) = 0;
5485 /* Splice the implicitly generated functions out of TYPE_FIELDS and diagnose
5486 invalid members. */
5487 for (tree probe, *prev_p = &TYPE_FIELDS (t); (probe = *prev_p);)
5489 if (TREE_CODE (probe) == FUNCTION_DECL && DECL_ARTIFICIAL (probe))
5490 *prev_p = DECL_CHAIN (probe);
5491 else
5492 prev_p = &DECL_CHAIN (probe);
5494 if (DECL_ARTIFICIAL (probe)
5495 && (!DECL_IMPLICIT_TYPEDEF_P (probe)
5496 || TYPE_ANON_P (TREE_TYPE (probe))))
5497 continue;
5499 if (TREE_CODE (probe) != FIELD_DECL
5500 || (TREE_PRIVATE (probe) || TREE_PROTECTED (probe)))
5502 /* We already complained about static data members in
5503 finish_static_data_member_decl. */
5504 if (!VAR_P (probe))
5506 auto_diagnostic_group d;
5507 if (permerror (DECL_SOURCE_LOCATION (probe),
5508 TREE_CODE (t) == UNION_TYPE
5509 ? "%q#D invalid; an anonymous union may "
5510 "only have public non-static data members"
5511 : "%q#D invalid; an anonymous struct may "
5512 "only have public non-static data members", probe))
5514 static bool hint;
5515 if (flag_permissive && !hint)
5517 hint = true;
5518 inform (DECL_SOURCE_LOCATION (probe),
5519 "this flexibility is deprecated and will be "
5520 "removed");
5527 /* Splice all functions out of CLASSTYPE_MEMBER_VEC. */
5528 vec<tree,va_gc>* vec = CLASSTYPE_MEMBER_VEC (t);
5529 unsigned store = 0;
5530 for (tree elt : vec)
5531 if (!is_overloaded_fn (elt))
5532 (*vec)[store++] = elt;
5533 vec_safe_truncate (vec, store);
5535 /* Wipe RTTI info. */
5536 CLASSTYPE_TYPEINFO_VAR (t) = NULL_TREE;
5538 /* Anonymous aggregates cannot have fields with ctors, dtors or complex
5539 assignment operators (because they cannot have these methods themselves).
5540 For anonymous unions this is already checked because they are not allowed
5541 in any union, otherwise we have to check it. */
5542 if (TREE_CODE (t) != UNION_TYPE)
5544 tree field, type;
5546 if (BINFO_N_BASE_BINFOS (TYPE_BINFO (t)))
5548 error_at (location_of (t), "anonymous struct with base classes");
5549 /* Avoid ICE after error on anon-struct9.C. */
5550 TYPE_NEEDS_CONSTRUCTING (t) = false;
5553 for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
5554 if (TREE_CODE (field) == FIELD_DECL)
5556 type = TREE_TYPE (field);
5557 if (CLASS_TYPE_P (type))
5559 if (TYPE_NEEDS_CONSTRUCTING (type))
5560 error ("member %q+#D with constructor not allowed "
5561 "in anonymous aggregate", field);
5562 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
5563 error ("member %q+#D with destructor not allowed "
5564 "in anonymous aggregate", field);
5565 if (TYPE_HAS_COMPLEX_COPY_ASSIGN (type))
5566 error ("member %q+#D with copy assignment operator "
5567 "not allowed in anonymous aggregate", field);
5573 /* Warn for an attribute located at LOCATION that appertains to the
5574 class type CLASS_TYPE that has not been properly placed after its
5575 class-key, in it class-specifier. */
5577 void
5578 warn_misplaced_attr_for_class_type (location_t location,
5579 tree class_type)
5581 gcc_assert (OVERLOAD_TYPE_P (class_type));
5583 auto_diagnostic_group d;
5584 if (warning_at (location, OPT_Wattributes,
5585 "attribute ignored in declaration "
5586 "of %q#T", class_type))
5587 inform (location,
5588 "attribute for %q#T must follow the %qs keyword",
5589 class_type, class_key_or_enum_as_string (class_type));
5592 /* Returns the cv-qualifiers that apply to the type specified
5593 by the DECLSPECS. */
5595 static int
5596 get_type_quals (const cp_decl_specifier_seq *declspecs)
5598 int type_quals = TYPE_UNQUALIFIED;
5600 if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5601 type_quals |= TYPE_QUAL_CONST;
5602 if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5603 type_quals |= TYPE_QUAL_VOLATILE;
5604 if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5605 type_quals |= TYPE_QUAL_RESTRICT;
5607 return type_quals;
5610 /* Make sure that a declaration with no declarator is well-formed, i.e.
5611 just declares a tagged type or anonymous union.
5613 Returns the type declared; or NULL_TREE if none. */
5615 tree
5616 check_tag_decl (cp_decl_specifier_seq *declspecs,
5617 bool explicit_type_instantiation_p)
5619 int saw_friend = decl_spec_seq_has_spec_p (declspecs, ds_friend);
5620 int saw_typedef = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
5621 /* If a class, struct, or enum type is declared by the DECLSPECS
5622 (i.e, if a class-specifier, enum-specifier, or non-typename
5623 elaborated-type-specifier appears in the DECLSPECS),
5624 DECLARED_TYPE is set to the corresponding type. */
5625 tree declared_type = NULL_TREE;
5626 bool error_p = false;
5628 if (declspecs->multiple_types_p)
5629 error_at (smallest_type_location (declspecs),
5630 "multiple types in one declaration");
5631 else if (declspecs->redefined_builtin_type)
5633 location_t loc = declspecs->locations[ds_redefined_builtin_type_spec];
5634 if (!in_system_header_at (loc))
5635 permerror (loc, "redeclaration of C++ built-in type %qT",
5636 declspecs->redefined_builtin_type);
5637 return NULL_TREE;
5640 if (declspecs->type
5641 && TYPE_P (declspecs->type)
5642 && ((TREE_CODE (declspecs->type) != TYPENAME_TYPE
5643 && MAYBE_CLASS_TYPE_P (declspecs->type))
5644 || TREE_CODE (declspecs->type) == ENUMERAL_TYPE))
5645 declared_type = declspecs->type;
5646 else if (declspecs->type == error_mark_node)
5647 error_p = true;
5649 if (type_uses_auto (declared_type))
5651 error_at (declspecs->locations[ds_type_spec],
5652 "%<auto%> can only be specified for variables "
5653 "or function declarations");
5654 return error_mark_node;
5657 if (declared_type && !OVERLOAD_TYPE_P (declared_type))
5658 declared_type = NULL_TREE;
5660 if (!declared_type && !saw_friend && !error_p)
5661 permerror (input_location, "declaration does not declare anything");
5662 /* Check for an anonymous union. */
5663 else if (declared_type && RECORD_OR_UNION_CODE_P (TREE_CODE (declared_type))
5664 && TYPE_UNNAMED_P (declared_type))
5666 /* 7/3 In a simple-declaration, the optional init-declarator-list
5667 can be omitted only when declaring a class (clause 9) or
5668 enumeration (7.2), that is, when the decl-specifier-seq contains
5669 either a class-specifier, an elaborated-type-specifier with
5670 a class-key (9.1), or an enum-specifier. In these cases and
5671 whenever a class-specifier or enum-specifier is present in the
5672 decl-specifier-seq, the identifiers in these specifiers are among
5673 the names being declared by the declaration (as class-name,
5674 enum-names, or enumerators, depending on the syntax). In such
5675 cases, and except for the declaration of an unnamed bit-field (9.6),
5676 the decl-specifier-seq shall introduce one or more names into the
5677 program, or shall redeclare a name introduced by a previous
5678 declaration. [Example:
5679 enum { }; // ill-formed
5680 typedef class { }; // ill-formed
5681 --end example] */
5682 if (saw_typedef)
5684 error_at (declspecs->locations[ds_typedef],
5685 "missing type-name in typedef-declaration");
5686 return NULL_TREE;
5688 /* Anonymous unions are objects, so they can have specifiers. */;
5689 SET_ANON_AGGR_TYPE_P (declared_type);
5691 if (TREE_CODE (declared_type) != UNION_TYPE)
5692 pedwarn (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (declared_type)),
5693 OPT_Wpedantic, "ISO C++ prohibits anonymous structs");
5696 else
5698 if (decl_spec_seq_has_spec_p (declspecs, ds_inline))
5699 error_at (declspecs->locations[ds_inline],
5700 "%<inline%> can only be specified for functions");
5701 else if (decl_spec_seq_has_spec_p (declspecs, ds_virtual))
5702 error_at (declspecs->locations[ds_virtual],
5703 "%<virtual%> can only be specified for functions");
5704 else if (saw_friend
5705 && (!current_class_type
5706 || current_scope () != current_class_type))
5707 error_at (declspecs->locations[ds_friend],
5708 "%<friend%> can only be specified inside a class");
5709 else if (decl_spec_seq_has_spec_p (declspecs, ds_explicit))
5710 error_at (declspecs->locations[ds_explicit],
5711 "%<explicit%> can only be specified for constructors");
5712 else if (declspecs->storage_class)
5713 error_at (declspecs->locations[ds_storage_class],
5714 "a storage class can only be specified for objects "
5715 "and functions");
5716 else if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5717 error_at (declspecs->locations[ds_const],
5718 "%<const%> can only be specified for objects and "
5719 "functions");
5720 else if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5721 error_at (declspecs->locations[ds_volatile],
5722 "%<volatile%> can only be specified for objects and "
5723 "functions");
5724 else if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5725 error_at (declspecs->locations[ds_restrict],
5726 "%<__restrict%> can only be specified for objects and "
5727 "functions");
5728 else if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
5729 error_at (declspecs->locations[ds_thread],
5730 "%<__thread%> can only be specified for objects "
5731 "and functions");
5732 else if (saw_typedef)
5733 warning_at (declspecs->locations[ds_typedef], 0,
5734 "%<typedef%> was ignored in this declaration");
5735 else if (decl_spec_seq_has_spec_p (declspecs, ds_constexpr))
5736 error_at (declspecs->locations[ds_constexpr],
5737 "%qs cannot be used for type declarations", "constexpr");
5738 else if (decl_spec_seq_has_spec_p (declspecs, ds_constinit))
5739 error_at (declspecs->locations[ds_constinit],
5740 "%qs cannot be used for type declarations", "constinit");
5741 else if (decl_spec_seq_has_spec_p (declspecs, ds_consteval))
5742 error_at (declspecs->locations[ds_consteval],
5743 "%qs cannot be used for type declarations", "consteval");
5746 if (declspecs->attributes && warn_attributes && declared_type)
5748 location_t loc;
5749 if (!CLASS_TYPE_P (declared_type)
5750 || !CLASSTYPE_TEMPLATE_INSTANTIATION (declared_type))
5751 /* For a non-template class, use the name location. */
5752 loc = location_of (declared_type);
5753 else
5754 /* For a template class (an explicit instantiation), use the
5755 current location. */
5756 loc = input_location;
5758 if (explicit_type_instantiation_p)
5759 /* [dcl.attr.grammar]/4:
5761 No attribute-specifier-seq shall appertain to an explicit
5762 instantiation. */
5764 if (warning_at (loc, OPT_Wattributes,
5765 "attribute ignored in explicit instantiation %q#T",
5766 declared_type))
5767 inform (loc,
5768 "no attribute can be applied to "
5769 "an explicit instantiation");
5771 else
5772 warn_misplaced_attr_for_class_type (loc, declared_type);
5775 /* Diagnose invalid application of contracts, if any. */
5776 if (find_contract (declspecs->attributes))
5777 diagnose_misapplied_contracts (declspecs->attributes);
5778 else
5779 diagnose_misapplied_contracts (declspecs->std_attributes);
5781 return declared_type;
5784 /* Called when a declaration is seen that contains no names to declare.
5785 If its type is a reference to a structure, union or enum inherited
5786 from a containing scope, shadow that tag name for the current scope
5787 with a forward reference.
5788 If its type defines a new named structure or union
5789 or defines an enum, it is valid but we need not do anything here.
5790 Otherwise, it is an error.
5792 C++: may have to grok the declspecs to learn about static,
5793 complain for anonymous unions.
5795 Returns the TYPE declared -- or NULL_TREE if none. */
5797 tree
5798 shadow_tag (cp_decl_specifier_seq *declspecs)
5800 tree t = check_tag_decl (declspecs,
5801 /*explicit_type_instantiation_p=*/false);
5803 if (!t)
5804 return NULL_TREE;
5806 t = maybe_process_partial_specialization (t);
5807 if (t == error_mark_node)
5808 return NULL_TREE;
5810 /* This is where the variables in an anonymous union are
5811 declared. An anonymous union declaration looks like:
5812 union { ... } ;
5813 because there is no declarator after the union, the parser
5814 sends that declaration here. */
5815 if (ANON_AGGR_TYPE_P (t))
5817 fixup_anonymous_aggr (t);
5819 if (TYPE_FIELDS (t))
5821 tree decl = grokdeclarator (/*declarator=*/NULL,
5822 declspecs, NORMAL, 0, NULL);
5823 finish_anon_union (decl);
5827 return t;
5830 /* Decode a "typename", such as "int **", returning a ..._TYPE node. */
5832 tree
5833 groktypename (cp_decl_specifier_seq *type_specifiers,
5834 const cp_declarator *declarator,
5835 bool is_template_arg)
5837 tree attrs;
5838 tree type;
5839 enum decl_context context
5840 = is_template_arg ? TEMPLATE_TYPE_ARG : TYPENAME;
5841 attrs = type_specifiers->attributes;
5842 type_specifiers->attributes = NULL_TREE;
5843 type = grokdeclarator (declarator, type_specifiers, context, 0, &attrs);
5844 if (attrs && type != error_mark_node)
5846 if (CLASS_TYPE_P (type))
5847 warning (OPT_Wattributes, "ignoring attributes applied to class type %qT "
5848 "outside of definition", type);
5849 else if (MAYBE_CLASS_TYPE_P (type))
5850 /* A template type parameter or other dependent type. */
5851 warning (OPT_Wattributes, "ignoring attributes applied to dependent "
5852 "type %qT without an associated declaration", type);
5853 else
5854 cplus_decl_attributes (&type, attrs, 0);
5856 return type;
5859 /* Process a DECLARATOR for a function-scope or namespace-scope
5860 variable or function declaration.
5861 (Function definitions go through start_function; class member
5862 declarations appearing in the body of the class go through
5863 grokfield.) The DECL corresponding to the DECLARATOR is returned.
5864 If an error occurs, the error_mark_node is returned instead.
5866 DECLSPECS are the decl-specifiers for the declaration. INITIALIZED is
5867 SD_INITIALIZED if an explicit initializer is present, or SD_DEFAULTED
5868 for an explicitly defaulted function, or SD_DELETED for an explicitly
5869 deleted function, but 0 (SD_UNINITIALIZED) if this is a variable
5870 implicitly initialized via a default constructor. It can also be
5871 SD_DECOMPOSITION which behaves much like SD_INITIALIZED, but we also
5872 mark the new decl as DECL_DECOMPOSITION_P.
5874 ATTRIBUTES and PREFIX_ATTRIBUTES are GNU attributes associated with this
5875 declaration.
5877 The scope represented by the context of the returned DECL is pushed
5878 (if it is not the global namespace) and is assigned to
5879 *PUSHED_SCOPE_P. The caller is then responsible for calling
5880 pop_scope on *PUSHED_SCOPE_P if it is set. */
5882 tree
5883 start_decl (const cp_declarator *declarator,
5884 cp_decl_specifier_seq *declspecs,
5885 int initialized,
5886 tree attributes,
5887 tree prefix_attributes,
5888 tree *pushed_scope_p)
5890 tree decl;
5891 tree context;
5892 bool was_public;
5893 int flags;
5894 bool alias;
5895 tree initial;
5897 *pushed_scope_p = NULL_TREE;
5899 if (prefix_attributes != error_mark_node)
5900 attributes = attr_chainon (attributes, prefix_attributes);
5902 decl = grokdeclarator (declarator, declspecs, NORMAL, initialized,
5903 &attributes);
5905 if (decl == NULL_TREE || VOID_TYPE_P (decl)
5906 || decl == error_mark_node
5907 || prefix_attributes == error_mark_node)
5908 return error_mark_node;
5910 context = CP_DECL_CONTEXT (decl);
5911 if (context != global_namespace)
5912 *pushed_scope_p = push_scope (context);
5914 if (initialized && TREE_CODE (decl) == TYPE_DECL)
5916 error_at (DECL_SOURCE_LOCATION (decl),
5917 "typedef %qD is initialized (use %qs instead)",
5918 decl, "decltype");
5919 return error_mark_node;
5922 /* Save the DECL_INITIAL value in case it gets clobbered to assist
5923 with attribute validation. */
5924 initial = DECL_INITIAL (decl);
5926 if (initialized)
5928 if (! toplevel_bindings_p ()
5929 && DECL_EXTERNAL (decl))
5930 warning (0, "declaration of %q#D has %<extern%> and is initialized",
5931 decl);
5932 DECL_EXTERNAL (decl) = 0;
5933 if (toplevel_bindings_p ())
5934 TREE_STATIC (decl) = 1;
5935 /* Tell 'cplus_decl_attributes' this is an initialized decl,
5936 even though we might not yet have the initializer expression. */
5937 if (!DECL_INITIAL (decl))
5938 DECL_INITIAL (decl) = error_mark_node;
5940 alias = lookup_attribute ("alias", DECL_ATTRIBUTES (decl)) != 0;
5942 if (alias && TREE_CODE (decl) == FUNCTION_DECL)
5943 record_key_method_defined (decl);
5945 /* If this is a typedef that names the class for linkage purposes
5946 (7.1.3p8), apply any attributes directly to the type. */
5947 if (TREE_CODE (decl) == TYPE_DECL
5948 && OVERLOAD_TYPE_P (TREE_TYPE (decl))
5949 && decl == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (decl))))
5950 flags = ATTR_FLAG_TYPE_IN_PLACE;
5951 else
5952 flags = 0;
5954 /* Set attributes here so if duplicate decl, will have proper attributes. */
5955 cplus_decl_attributes (&decl, attributes, flags);
5957 /* Restore the original DECL_INITIAL that we may have clobbered earlier to
5958 assist with attribute validation. */
5959 DECL_INITIAL (decl) = initial;
5961 /* Dllimported symbols cannot be defined. Static data members (which
5962 can be initialized in-class and dllimported) go through grokfield,
5963 not here, so we don't need to exclude those decls when checking for
5964 a definition. */
5965 if (initialized && DECL_DLLIMPORT_P (decl))
5967 error_at (DECL_SOURCE_LOCATION (decl),
5968 "definition of %q#D is marked %<dllimport%>", decl);
5969 DECL_DLLIMPORT_P (decl) = 0;
5972 /* If #pragma weak was used, mark the decl weak now. */
5973 if (!processing_template_decl && !DECL_DECOMPOSITION_P (decl))
5974 maybe_apply_pragma_weak (decl);
5976 if (TREE_CODE (decl) == FUNCTION_DECL
5977 && DECL_DECLARED_INLINE_P (decl)
5978 && DECL_UNINLINABLE (decl)
5979 && lookup_attribute ("noinline", DECL_ATTRIBUTES (decl)))
5980 warning_at (DECL_SOURCE_LOCATION (decl), 0,
5981 "inline function %qD given attribute %qs", decl, "noinline");
5983 if (TYPE_P (context) && COMPLETE_TYPE_P (complete_type (context)))
5985 bool this_tmpl = (current_template_depth
5986 > template_class_depth (context));
5987 if (VAR_P (decl))
5989 tree field = lookup_field (context, DECL_NAME (decl), 0, false);
5990 if (field == NULL_TREE
5991 || !(VAR_P (field) || variable_template_p (field)))
5992 error ("%q+#D is not a static data member of %q#T", decl, context);
5993 else if (variable_template_p (field)
5994 && (DECL_LANG_SPECIFIC (decl)
5995 && DECL_TEMPLATE_SPECIALIZATION (decl)))
5996 /* OK, specialization was already checked. */;
5997 else if (variable_template_p (field) && !this_tmpl)
5999 error_at (DECL_SOURCE_LOCATION (decl),
6000 "non-member-template declaration of %qD", decl);
6001 inform (DECL_SOURCE_LOCATION (field), "does not match "
6002 "member template declaration here");
6003 return error_mark_node;
6005 else
6007 if (variable_template_p (field))
6008 field = DECL_TEMPLATE_RESULT (field);
6010 if (DECL_CONTEXT (field) != context)
6012 if (!same_type_p (DECL_CONTEXT (field), context))
6013 permerror (input_location, "ISO C++ does not permit %<%T::%D%> "
6014 "to be defined as %<%T::%D%>",
6015 DECL_CONTEXT (field), DECL_NAME (decl),
6016 context, DECL_NAME (decl));
6017 DECL_CONTEXT (decl) = DECL_CONTEXT (field);
6019 /* Static data member are tricky; an in-class initialization
6020 still doesn't provide a definition, so the in-class
6021 declaration will have DECL_EXTERNAL set, but will have an
6022 initialization. Thus, duplicate_decls won't warn
6023 about this situation, and so we check here. */
6024 if (initialized && DECL_INITIALIZED_IN_CLASS_P (field))
6025 error ("duplicate initialization of %qD", decl);
6026 field = duplicate_decls (decl, field);
6027 if (field == error_mark_node)
6028 return error_mark_node;
6029 else if (field)
6030 decl = field;
6033 else
6035 tree field = check_classfn (context, decl,
6036 this_tmpl
6037 ? current_template_parms
6038 : NULL_TREE);
6039 if (field && field != error_mark_node
6040 && duplicate_decls (decl, field))
6041 decl = field;
6044 /* cp_finish_decl sets DECL_EXTERNAL if DECL_IN_AGGR_P is set. */
6045 DECL_IN_AGGR_P (decl) = 0;
6046 /* Do not mark DECL as an explicit specialization if it was not
6047 already marked as an instantiation; a declaration should
6048 never be marked as a specialization unless we know what
6049 template is being specialized. */
6050 if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
6052 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
6053 if (TREE_CODE (decl) == FUNCTION_DECL)
6054 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
6055 && DECL_DECLARED_INLINE_P (decl));
6056 else
6057 DECL_COMDAT (decl) = false;
6059 /* [temp.expl.spec] An explicit specialization of a static data
6060 member of a template is a definition if the declaration
6061 includes an initializer; otherwise, it is a declaration.
6063 We check for processing_specialization so this only applies
6064 to the new specialization syntax. */
6065 if (!initialized && processing_specialization)
6066 DECL_EXTERNAL (decl) = 1;
6069 if (DECL_EXTERNAL (decl) && ! DECL_TEMPLATE_SPECIALIZATION (decl)
6070 /* Aliases are definitions. */
6071 && !alias)
6073 if (DECL_VIRTUAL_P (decl) || !flag_contracts)
6074 permerror (declarator->id_loc,
6075 "declaration of %q#D outside of class is not definition",
6076 decl);
6077 else if (flag_contract_strict_declarations)
6078 warning_at (declarator->id_loc, OPT_fcontract_strict_declarations_,
6079 "declaration of %q#D outside of class is not definition",
6080 decl);
6084 /* Create a DECL_LANG_SPECIFIC so that DECL_DECOMPOSITION_P works. */
6085 if (initialized == SD_DECOMPOSITION)
6086 fit_decomposition_lang_decl (decl, NULL_TREE);
6088 was_public = TREE_PUBLIC (decl);
6090 if ((DECL_EXTERNAL (decl) || TREE_CODE (decl) == FUNCTION_DECL)
6091 && current_function_decl)
6093 /* A function-scope decl of some namespace-scope decl. */
6094 DECL_LOCAL_DECL_P (decl) = true;
6095 if (named_module_purview_p ())
6096 error_at (declarator->id_loc,
6097 "block-scope extern declaration %q#D not permitted"
6098 " in module purview", decl);
6101 /* Enter this declaration into the symbol table. Don't push the plain
6102 VAR_DECL for a variable template. */
6103 if (!template_parm_scope_p ()
6104 || !VAR_P (decl))
6105 decl = maybe_push_decl (decl);
6107 if (processing_template_decl)
6108 decl = push_template_decl (decl);
6110 if (decl == error_mark_node)
6111 return error_mark_node;
6113 if (VAR_P (decl)
6114 && DECL_NAMESPACE_SCOPE_P (decl) && !TREE_PUBLIC (decl) && !was_public
6115 && !DECL_THIS_STATIC (decl) && !DECL_ARTIFICIAL (decl)
6116 /* But not templated variables. */
6117 && !(DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)))
6119 /* This is a const variable with implicit 'static'. Set
6120 DECL_THIS_STATIC so we can tell it from variables that are
6121 !TREE_PUBLIC because of the anonymous namespace. */
6122 gcc_assert (CP_TYPE_CONST_P (TREE_TYPE (decl)) || errorcount);
6123 DECL_THIS_STATIC (decl) = 1;
6126 if (current_function_decl && VAR_P (decl)
6127 && DECL_DECLARED_CONSTEXPR_P (current_function_decl)
6128 && cxx_dialect < cxx23)
6130 bool ok = false;
6131 if (CP_DECL_THREAD_LOCAL_P (decl) && !DECL_REALLY_EXTERN (decl))
6132 error_at (DECL_SOURCE_LOCATION (decl),
6133 "%qD defined %<thread_local%> in %qs function only "
6134 "available with %<-std=c++2b%> or %<-std=gnu++2b%>", decl,
6135 DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
6136 ? "consteval" : "constexpr");
6137 else if (TREE_STATIC (decl))
6138 error_at (DECL_SOURCE_LOCATION (decl),
6139 "%qD defined %<static%> in %qs function only available "
6140 "with %<-std=c++2b%> or %<-std=gnu++2b%>", decl,
6141 DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
6142 ? "consteval" : "constexpr");
6143 else
6144 ok = true;
6145 if (!ok)
6146 cp_function_chain->invalid_constexpr = true;
6149 if (!processing_template_decl && VAR_P (decl))
6150 start_decl_1 (decl, initialized);
6152 return decl;
6155 /* Process the declaration of a variable DECL. INITIALIZED is true
6156 iff DECL is explicitly initialized. (INITIALIZED is false if the
6157 variable is initialized via an implicitly-called constructor.)
6158 This function must be called for ordinary variables (including, for
6159 example, implicit instantiations of templates), but must not be
6160 called for template declarations. */
6162 void
6163 start_decl_1 (tree decl, bool initialized)
6165 gcc_checking_assert (!processing_template_decl);
6167 if (error_operand_p (decl))
6168 return;
6170 gcc_checking_assert (VAR_P (decl));
6172 tree type = TREE_TYPE (decl);
6173 bool complete_p = COMPLETE_TYPE_P (type);
6174 bool aggregate_definition_p
6175 = MAYBE_CLASS_TYPE_P (type) && !DECL_EXTERNAL (decl);
6177 /* If an explicit initializer is present, or if this is a definition
6178 of an aggregate, then we need a complete type at this point.
6179 (Scalars are always complete types, so there is nothing to
6180 check.) This code just sets COMPLETE_P; errors (if necessary)
6181 are issued below. */
6182 if ((initialized || aggregate_definition_p)
6183 && !complete_p
6184 && COMPLETE_TYPE_P (complete_type (type)))
6186 complete_p = true;
6187 /* We will not yet have set TREE_READONLY on DECL if the type
6188 was "const", but incomplete, before this point. But, now, we
6189 have a complete type, so we can try again. */
6190 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
6193 if (initialized)
6194 /* Is it valid for this decl to have an initializer at all? */
6196 /* Don't allow initializations for incomplete types except for
6197 arrays which might be completed by the initialization. */
6198 if (complete_p)
6199 ; /* A complete type is ok. */
6200 else if (type_uses_auto (type))
6201 ; /* An auto type is ok. */
6202 else if (TREE_CODE (type) != ARRAY_TYPE)
6204 auto_diagnostic_group d;
6205 error ("variable %q#D has initializer but incomplete type", decl);
6206 maybe_suggest_missing_header (input_location,
6207 TYPE_IDENTIFIER (type),
6208 CP_TYPE_CONTEXT (type));
6209 type = TREE_TYPE (decl) = error_mark_node;
6211 else if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (type))))
6213 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
6214 error ("elements of array %q#D have incomplete type", decl);
6215 /* else we already gave an error in start_decl. */
6218 else if (aggregate_definition_p && !complete_p)
6220 if (type_uses_auto (type))
6221 gcc_assert (CLASS_PLACEHOLDER_TEMPLATE (type));
6222 else
6224 auto_diagnostic_group d;
6225 error ("aggregate %q#D has incomplete type and cannot be defined",
6226 decl);
6227 maybe_suggest_missing_header (input_location,
6228 TYPE_IDENTIFIER (type),
6229 CP_TYPE_CONTEXT (type));
6230 /* Change the type so that assemble_variable will give
6231 DECL an rtl we can live with: (mem (const_int 0)). */
6232 type = TREE_TYPE (decl) = error_mark_node;
6236 /* Create a new scope to hold this declaration if necessary.
6237 Whether or not a new scope is necessary cannot be determined
6238 until after the type has been completed; if the type is a
6239 specialization of a class template it is not until after
6240 instantiation has occurred that TYPE_HAS_NONTRIVIAL_DESTRUCTOR
6241 will be set correctly. */
6242 maybe_push_cleanup_level (type);
6245 /* Given a parenthesized list of values INIT, create a CONSTRUCTOR to handle
6246 C++20 P0960. TYPE is the type of the object we're initializing. */
6248 tree
6249 do_aggregate_paren_init (tree init, tree type)
6251 tree val = TREE_VALUE (init);
6253 if (TREE_CHAIN (init) == NULL_TREE)
6255 /* If the list has a single element and it's a string literal,
6256 then it's the initializer for the array as a whole. */
6257 if (TREE_CODE (type) == ARRAY_TYPE
6258 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
6259 && TREE_CODE (tree_strip_any_location_wrapper (val))
6260 == STRING_CST)
6261 return val;
6262 /* Handle non-standard extensions like compound literals. This also
6263 prevents triggering aggregate parenthesized-initialization in
6264 compiler-generated code for =default. */
6265 else if (same_type_ignoring_top_level_qualifiers_p (type,
6266 TREE_TYPE (val)))
6267 return val;
6270 init = build_constructor_from_list (init_list_type_node, init);
6271 CONSTRUCTOR_IS_DIRECT_INIT (init) = true;
6272 CONSTRUCTOR_IS_PAREN_INIT (init) = true;
6273 return init;
6276 /* Handle initialization of references. DECL, TYPE, and INIT have the
6277 same meaning as in cp_finish_decl. *CLEANUP must be NULL on entry,
6278 but will be set to a new CLEANUP_STMT if a temporary is created
6279 that must be destroyed subsequently.
6281 Returns an initializer expression to use to initialize DECL, or
6282 NULL if the initialization can be performed statically.
6284 Quotes on semantics can be found in ARM 8.4.3. */
6286 static tree
6287 grok_reference_init (tree decl, tree type, tree init, int flags)
6289 if (init == NULL_TREE)
6291 if ((DECL_LANG_SPECIFIC (decl) == 0
6292 || DECL_IN_AGGR_P (decl) == 0)
6293 && ! DECL_THIS_EXTERN (decl))
6294 error_at (DECL_SOURCE_LOCATION (decl),
6295 "%qD declared as reference but not initialized", decl);
6296 return NULL_TREE;
6299 tree ttype = TREE_TYPE (type);
6300 if (TREE_CODE (init) == TREE_LIST)
6302 /* This handles (C++20 only) code like
6304 const A& r(1, 2, 3);
6306 where we treat the parenthesized list as a CONSTRUCTOR. */
6307 if (TREE_TYPE (init) == NULL_TREE
6308 && CP_AGGREGATE_TYPE_P (ttype)
6309 && !DECL_DECOMPOSITION_P (decl)
6310 && (cxx_dialect >= cxx20))
6312 /* We don't know yet if we should treat const A& r(1) as
6313 const A& r{1}. */
6314 if (list_length (init) == 1)
6316 flags |= LOOKUP_AGGREGATE_PAREN_INIT;
6317 init = build_x_compound_expr_from_list (init, ELK_INIT,
6318 tf_warning_or_error);
6320 /* If the list had more than one element, the code is ill-formed
6321 pre-C++20, so we can build a constructor right away. */
6322 else
6323 init = do_aggregate_paren_init (init, ttype);
6325 else
6326 init = build_x_compound_expr_from_list (init, ELK_INIT,
6327 tf_warning_or_error);
6330 if (TREE_CODE (ttype) != ARRAY_TYPE
6331 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
6332 /* Note: default conversion is only called in very special cases. */
6333 init = decay_conversion (init, tf_warning_or_error);
6335 /* check_initializer handles this for non-reference variables, but for
6336 references we need to do it here or the initializer will get the
6337 incomplete array type and confuse later calls to
6338 cp_complete_array_type. */
6339 if (TREE_CODE (ttype) == ARRAY_TYPE
6340 && TYPE_DOMAIN (ttype) == NULL_TREE
6341 && (BRACE_ENCLOSED_INITIALIZER_P (init)
6342 || TREE_CODE (init) == STRING_CST))
6344 cp_complete_array_type (&ttype, init, false);
6345 if (ttype != TREE_TYPE (type))
6346 type = cp_build_reference_type (ttype, TYPE_REF_IS_RVALUE (type));
6349 /* Convert INIT to the reference type TYPE. This may involve the
6350 creation of a temporary, whose lifetime must be the same as that
6351 of the reference. If so, a DECL_EXPR for the temporary will be
6352 added just after the DECL_EXPR for DECL. That's why we don't set
6353 DECL_INITIAL for local references (instead assigning to them
6354 explicitly); we need to allow the temporary to be initialized
6355 first. */
6356 return initialize_reference (type, init, flags,
6357 tf_warning_or_error);
6360 /* Designated initializers in arrays are not supported in GNU C++.
6361 The parser cannot detect this error since it does not know whether
6362 a given brace-enclosed initializer is for a class type or for an
6363 array. This function checks that CE does not use a designated
6364 initializer. If it does, an error is issued. Returns true if CE
6365 is valid, i.e., does not have a designated initializer. */
6367 bool
6368 check_array_designated_initializer (constructor_elt *ce,
6369 unsigned HOST_WIDE_INT index)
6371 /* Designated initializers for array elements are not supported. */
6372 if (ce->index)
6374 /* The parser only allows identifiers as designated
6375 initializers. */
6376 if (ce->index == error_mark_node)
6378 error ("name used in a GNU-style designated "
6379 "initializer for an array");
6380 return false;
6382 else if (identifier_p (ce->index))
6384 error ("name %qD used in a GNU-style designated "
6385 "initializer for an array", ce->index);
6386 return false;
6389 tree ce_index = build_expr_type_conversion (WANT_INT | WANT_ENUM,
6390 ce->index, true);
6391 if (ce_index
6392 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ce_index))
6393 && (TREE_CODE (ce_index = fold_non_dependent_expr (ce_index))
6394 == INTEGER_CST))
6396 /* A C99 designator is OK if it matches the current index. */
6397 if (wi::to_wide (ce_index) == index)
6399 ce->index = ce_index;
6400 return true;
6402 else
6403 sorry ("non-trivial designated initializers not supported");
6405 else
6406 error_at (cp_expr_loc_or_input_loc (ce->index),
6407 "C99 designator %qE is not an integral constant-expression",
6408 ce->index);
6410 return false;
6413 return true;
6416 /* When parsing `int a[] = {1, 2};' we don't know the size of the
6417 array until we finish parsing the initializer. If that's the
6418 situation we're in, update DECL accordingly. */
6420 static void
6421 maybe_deduce_size_from_array_init (tree decl, tree init)
6423 tree type = TREE_TYPE (decl);
6425 if (TREE_CODE (type) == ARRAY_TYPE
6426 && TYPE_DOMAIN (type) == NULL_TREE
6427 && TREE_CODE (decl) != TYPE_DECL)
6429 /* do_default is really a C-ism to deal with tentative definitions.
6430 But let's leave it here to ease the eventual merge. */
6431 int do_default = !DECL_EXTERNAL (decl);
6432 tree initializer = init ? init : DECL_INITIAL (decl);
6433 int failure = 0;
6435 /* Check that there are no designated initializers in INIT, as
6436 those are not supported in GNU C++, and as the middle-end
6437 will crash if presented with a non-numeric designated
6438 initializer. */
6439 if (initializer && BRACE_ENCLOSED_INITIALIZER_P (initializer))
6441 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initializer);
6442 constructor_elt *ce;
6443 HOST_WIDE_INT i;
6444 FOR_EACH_VEC_SAFE_ELT (v, i, ce)
6446 if (instantiation_dependent_expression_p (ce->index))
6447 return;
6448 if (!check_array_designated_initializer (ce, i))
6449 failure = 1;
6450 /* If an un-designated initializer is type-dependent, we can't
6451 check brace elision yet. */
6452 if (ce->index == NULL_TREE
6453 && type_dependent_expression_p (ce->value))
6454 return;
6458 if (failure)
6459 TREE_TYPE (decl) = error_mark_node;
6460 else
6462 failure = cp_complete_array_type (&TREE_TYPE (decl), initializer,
6463 do_default);
6464 if (failure == 1)
6466 error_at (cp_expr_loc_or_loc (initializer,
6467 DECL_SOURCE_LOCATION (decl)),
6468 "initializer fails to determine size of %qD", decl);
6470 else if (failure == 2)
6472 if (do_default)
6474 error_at (DECL_SOURCE_LOCATION (decl),
6475 "array size missing in %qD", decl);
6477 /* If a `static' var's size isn't known, make it extern as
6478 well as static, so it does not get allocated. If it's not
6479 `static', then don't mark it extern; finish_incomplete_decl
6480 will give it a default size and it will get allocated. */
6481 else if (!pedantic && TREE_STATIC (decl) && !TREE_PUBLIC (decl))
6482 DECL_EXTERNAL (decl) = 1;
6484 else if (failure == 3)
6486 error_at (DECL_SOURCE_LOCATION (decl),
6487 "zero-size array %qD", decl);
6491 cp_apply_type_quals_to_decl (cp_type_quals (TREE_TYPE (decl)), decl);
6493 relayout_decl (decl);
6497 /* Set DECL_SIZE, DECL_ALIGN, etc. for DECL (a VAR_DECL), and issue
6498 any appropriate error messages regarding the layout. */
6500 static void
6501 layout_var_decl (tree decl)
6503 tree type;
6505 type = TREE_TYPE (decl);
6506 if (type == error_mark_node)
6507 return;
6509 /* If we haven't already laid out this declaration, do so now.
6510 Note that we must not call complete type for an external object
6511 because it's type might involve templates that we are not
6512 supposed to instantiate yet. (And it's perfectly valid to say
6513 `extern X x' for some incomplete type `X'.) */
6514 if (!DECL_EXTERNAL (decl))
6515 complete_type (type);
6516 if (!DECL_SIZE (decl)
6517 && TREE_TYPE (decl) != error_mark_node
6518 && complete_or_array_type_p (type))
6519 layout_decl (decl, 0);
6521 if (!DECL_EXTERNAL (decl) && DECL_SIZE (decl) == NULL_TREE)
6523 /* An automatic variable with an incomplete type: that is an error.
6524 Don't talk about array types here, since we took care of that
6525 message in grokdeclarator. */
6526 error_at (DECL_SOURCE_LOCATION (decl),
6527 "storage size of %qD isn%'t known", decl);
6528 TREE_TYPE (decl) = error_mark_node;
6530 #if 0
6531 /* Keep this code around in case we later want to control debug info
6532 based on whether a type is "used". (jason 1999-11-11) */
6534 else if (!DECL_EXTERNAL (decl) && MAYBE_CLASS_TYPE_P (ttype))
6535 /* Let debugger know it should output info for this type. */
6536 note_debug_info_needed (ttype);
6538 if (TREE_STATIC (decl) && DECL_CLASS_SCOPE_P (decl))
6539 note_debug_info_needed (DECL_CONTEXT (decl));
6540 #endif
6542 if ((DECL_EXTERNAL (decl) || TREE_STATIC (decl))
6543 && DECL_SIZE (decl) != NULL_TREE
6544 && ! TREE_CONSTANT (DECL_SIZE (decl)))
6546 if (TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST
6547 && !DECL_LOCAL_DECL_P (decl))
6548 constant_expression_warning (DECL_SIZE (decl));
6549 else
6551 error_at (DECL_SOURCE_LOCATION (decl),
6552 "storage size of %qD isn%'t constant", decl);
6553 TREE_TYPE (decl) = error_mark_node;
6554 type = error_mark_node;
6558 /* If the final element initializes a flexible array field, add the size of
6559 that initializer to DECL's size. */
6560 if (type != error_mark_node
6561 && DECL_INITIAL (decl)
6562 && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
6563 && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl)))
6564 && DECL_SIZE (decl) != NULL_TREE
6565 && TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST
6566 && COMPLETE_TYPE_P (type)
6567 && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST
6568 && tree_int_cst_equal (DECL_SIZE (decl), TYPE_SIZE (type)))
6570 constructor_elt &elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ();
6571 if (elt.index)
6573 tree itype = TREE_TYPE (elt.index);
6574 tree vtype = TREE_TYPE (elt.value);
6575 if (TREE_CODE (itype) == ARRAY_TYPE
6576 && TYPE_DOMAIN (itype) == NULL
6577 && TREE_CODE (vtype) == ARRAY_TYPE
6578 && COMPLETE_TYPE_P (vtype))
6580 DECL_SIZE (decl)
6581 = size_binop (PLUS_EXPR, DECL_SIZE (decl), TYPE_SIZE (vtype));
6582 DECL_SIZE_UNIT (decl)
6583 = size_binop (PLUS_EXPR, DECL_SIZE_UNIT (decl),
6584 TYPE_SIZE_UNIT (vtype));
6590 /* If a local static variable is declared in an inline function, or if
6591 we have a weak definition, we must endeavor to create only one
6592 instance of the variable at link-time. */
6594 void
6595 maybe_commonize_var (tree decl)
6597 /* Don't mess with __FUNCTION__ and similar. But do handle structured
6598 bindings. */
6599 if (DECL_ARTIFICIAL (decl) && !DECL_DECOMPOSITION_P (decl))
6600 return;
6602 /* Static data in a function with comdat linkage also has comdat
6603 linkage. */
6604 if ((TREE_STATIC (decl)
6605 && DECL_FUNCTION_SCOPE_P (decl)
6606 && vague_linkage_p (DECL_CONTEXT (decl)))
6607 || (TREE_PUBLIC (decl) && DECL_INLINE_VAR_P (decl)))
6609 if (flag_weak)
6611 /* With weak symbols, we simply make the variable COMDAT;
6612 that will cause copies in multiple translations units to
6613 be merged. */
6614 comdat_linkage (decl);
6616 else
6618 if (DECL_INITIAL (decl) == NULL_TREE
6619 || DECL_INITIAL (decl) == error_mark_node)
6621 /* Without weak symbols, we can use COMMON to merge
6622 uninitialized variables. */
6623 TREE_PUBLIC (decl) = 1;
6624 DECL_COMMON (decl) = 1;
6626 else
6628 /* While for initialized variables, we must use internal
6629 linkage -- which means that multiple copies will not
6630 be merged. */
6631 TREE_PUBLIC (decl) = 0;
6632 DECL_COMMON (decl) = 0;
6633 DECL_INTERFACE_KNOWN (decl) = 1;
6634 const char *msg;
6635 if (DECL_INLINE_VAR_P (decl))
6636 msg = G_("sorry: semantics of inline variable "
6637 "%q#D are wrong (you%'ll wind up with "
6638 "multiple copies)");
6639 else
6640 msg = G_("sorry: semantics of inline function "
6641 "static data %q#D are wrong (you%'ll wind "
6642 "up with multiple copies)");
6643 if (warning_at (DECL_SOURCE_LOCATION (decl), 0,
6644 msg, decl))
6645 inform (DECL_SOURCE_LOCATION (decl),
6646 "you can work around this by removing the initializer");
6652 /* Issue an error message if DECL is an uninitialized const variable.
6653 CONSTEXPR_CONTEXT_P is true when the function is called in a constexpr
6654 context from potential_constant_expression. Returns true if all is well,
6655 false otherwise. */
6657 bool
6658 check_for_uninitialized_const_var (tree decl, bool constexpr_context_p,
6659 tsubst_flags_t complain)
6661 tree type = strip_array_types (TREE_TYPE (decl));
6663 /* ``Unless explicitly declared extern, a const object does not have
6664 external linkage and must be initialized. ($8.4; $12.1)'' ARM
6665 7.1.6 */
6666 if (VAR_P (decl)
6667 && !TYPE_REF_P (type)
6668 && (CP_TYPE_CONST_P (type)
6669 /* C++20 permits trivial default initialization in constexpr
6670 context (P1331R2). */
6671 || (cxx_dialect < cxx20
6672 && (constexpr_context_p
6673 || var_in_constexpr_fn (decl))))
6674 && !DECL_NONTRIVIALLY_INITIALIZED_P (decl))
6676 tree field = default_init_uninitialized_part (type);
6677 if (!field)
6678 return true;
6680 bool show_notes = true;
6682 if (!constexpr_context_p || cxx_dialect >= cxx20)
6684 if (CP_TYPE_CONST_P (type))
6686 if (complain & tf_error)
6687 show_notes = permerror (DECL_SOURCE_LOCATION (decl),
6688 "uninitialized %<const %D%>", decl);
6690 else
6692 if (!is_instantiation_of_constexpr (current_function_decl)
6693 && (complain & tf_error))
6694 error_at (DECL_SOURCE_LOCATION (decl),
6695 "uninitialized variable %qD in %<constexpr%> "
6696 "function", decl);
6697 else
6698 show_notes = false;
6699 cp_function_chain->invalid_constexpr = true;
6702 else if (complain & tf_error)
6703 error_at (DECL_SOURCE_LOCATION (decl),
6704 "uninitialized variable %qD in %<constexpr%> context",
6705 decl);
6707 if (show_notes && CLASS_TYPE_P (type) && (complain & tf_error))
6709 tree defaulted_ctor;
6711 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)),
6712 "%q#T has no user-provided default constructor", type);
6713 defaulted_ctor = in_class_defaulted_default_constructor (type);
6714 if (defaulted_ctor)
6715 inform (DECL_SOURCE_LOCATION (defaulted_ctor),
6716 "constructor is not user-provided because it is "
6717 "explicitly defaulted in the class body");
6718 inform (DECL_SOURCE_LOCATION (field),
6719 "and the implicitly-defined constructor does not "
6720 "initialize %q#D", field);
6723 return false;
6726 return true;
6729 /* Structure holding the current initializer being processed by reshape_init.
6730 CUR is a pointer to the current element being processed, END is a pointer
6731 after the last element present in the initializer. */
6732 struct reshape_iter
6734 constructor_elt *cur;
6735 constructor_elt *end;
6738 static tree reshape_init_r (tree, reshape_iter *, tree, tsubst_flags_t);
6740 /* FIELD is an element of TYPE_FIELDS or NULL. In the former case, the value
6741 returned is the next FIELD_DECL (possibly FIELD itself) that can be
6742 initialized as if for an aggregate class. If there are no more such fields,
6743 the return value will be NULL. */
6745 tree
6746 next_aggregate_field (tree field)
6748 while (field
6749 && (TREE_CODE (field) != FIELD_DECL
6750 || DECL_UNNAMED_BIT_FIELD (field)
6751 || (DECL_ARTIFICIAL (field)
6752 /* In C++17, aggregates can have bases. */
6753 && !(cxx_dialect >= cxx17 && DECL_FIELD_IS_BASE (field)))))
6754 field = DECL_CHAIN (field);
6756 return field;
6759 /* FIELD is an element of TYPE_FIELDS or NULL. In the former case, the value
6760 returned is the next FIELD_DECL (possibly FIELD itself) that corresponds
6761 to a subobject. If there are no more such fields, the return value will be
6762 NULL. */
6764 tree
6765 next_subobject_field (tree field)
6767 while (field
6768 && (TREE_CODE (field) != FIELD_DECL
6769 || DECL_UNNAMED_BIT_FIELD (field)
6770 || (DECL_ARTIFICIAL (field)
6771 && !DECL_FIELD_IS_BASE (field)
6772 && !DECL_VIRTUAL_P (field))))
6773 field = DECL_CHAIN (field);
6775 return field;
6778 /* Return true for [dcl.init.list] direct-list-initialization from
6779 single element of enumeration with a fixed underlying type. */
6781 bool
6782 is_direct_enum_init (tree type, tree init)
6784 if (cxx_dialect >= cxx17
6785 && TREE_CODE (type) == ENUMERAL_TYPE
6786 && ENUM_FIXED_UNDERLYING_TYPE_P (type)
6787 && TREE_CODE (init) == CONSTRUCTOR
6788 && CONSTRUCTOR_IS_DIRECT_INIT (init)
6789 && CONSTRUCTOR_NELTS (init) == 1
6790 /* DR 2374: The single element needs to be implicitly
6791 convertible to the underlying type of the enum. */
6792 && !type_dependent_expression_p (CONSTRUCTOR_ELT (init, 0)->value)
6793 && can_convert_arg (ENUM_UNDERLYING_TYPE (type),
6794 TREE_TYPE (CONSTRUCTOR_ELT (init, 0)->value),
6795 CONSTRUCTOR_ELT (init, 0)->value,
6796 LOOKUP_IMPLICIT, tf_none))
6797 return true;
6798 return false;
6801 /* Subroutine of reshape_init_array and reshape_init_vector, which does
6802 the actual work. ELT_TYPE is the element type of the array. MAX_INDEX is an
6803 INTEGER_CST representing the size of the array minus one (the maximum index),
6804 or NULL_TREE if the array was declared without specifying the size. D is
6805 the iterator within the constructor. */
6807 static tree
6808 reshape_init_array_1 (tree elt_type, tree max_index, reshape_iter *d,
6809 tree first_initializer_p, tsubst_flags_t complain)
6811 tree new_init;
6812 bool sized_array_p = (max_index && TREE_CONSTANT (max_index));
6813 unsigned HOST_WIDE_INT max_index_cst = 0;
6814 unsigned HOST_WIDE_INT index;
6816 /* The initializer for an array is always a CONSTRUCTOR. If this is the
6817 outermost CONSTRUCTOR and the element type is non-aggregate, we don't need
6818 to build a new one. But don't reuse if not complaining; if this is
6819 tentative, we might also reshape to another type (95319). */
6820 bool reuse = (first_initializer_p
6821 && (complain & tf_error)
6822 && !CP_AGGREGATE_TYPE_P (elt_type)
6823 && !TREE_SIDE_EFFECTS (first_initializer_p));
6824 if (reuse)
6825 new_init = first_initializer_p;
6826 else
6827 new_init = build_constructor (init_list_type_node, NULL);
6829 if (sized_array_p)
6831 /* Minus 1 is used for zero sized arrays. */
6832 if (integer_all_onesp (max_index))
6833 return new_init;
6835 if (tree_fits_uhwi_p (max_index))
6836 max_index_cst = tree_to_uhwi (max_index);
6837 /* sizetype is sign extended, not zero extended. */
6838 else
6839 max_index_cst = tree_to_uhwi (fold_convert (size_type_node, max_index));
6842 /* Loop until there are no more initializers. */
6843 for (index = 0;
6844 d->cur != d->end && (!sized_array_p || index <= max_index_cst);
6845 ++index)
6847 tree elt_init;
6848 constructor_elt *old_cur = d->cur;
6850 if (d->cur->index)
6851 CONSTRUCTOR_IS_DESIGNATED_INIT (new_init) = true;
6852 check_array_designated_initializer (d->cur, index);
6853 elt_init = reshape_init_r (elt_type, d,
6854 /*first_initializer_p=*/NULL_TREE,
6855 complain);
6856 if (elt_init == error_mark_node)
6857 return error_mark_node;
6858 tree idx = size_int (index);
6859 if (reuse)
6861 old_cur->index = idx;
6862 old_cur->value = elt_init;
6864 else
6865 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
6866 idx, elt_init);
6867 if (!TREE_CONSTANT (elt_init))
6868 TREE_CONSTANT (new_init) = false;
6870 /* This can happen with an invalid initializer (c++/54501). */
6871 if (d->cur == old_cur && !sized_array_p)
6872 break;
6875 return new_init;
6878 /* Subroutine of reshape_init_r, processes the initializers for arrays.
6879 Parameters are the same of reshape_init_r. */
6881 static tree
6882 reshape_init_array (tree type, reshape_iter *d, tree first_initializer_p,
6883 tsubst_flags_t complain)
6885 tree max_index = NULL_TREE;
6887 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
6889 if (TYPE_DOMAIN (type))
6890 max_index = array_type_nelts (type);
6892 return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6893 first_initializer_p, complain);
6896 /* Subroutine of reshape_init_r, processes the initializers for vectors.
6897 Parameters are the same of reshape_init_r. */
6899 static tree
6900 reshape_init_vector (tree type, reshape_iter *d, tsubst_flags_t complain)
6902 tree max_index = NULL_TREE;
6904 gcc_assert (VECTOR_TYPE_P (type));
6906 if (COMPOUND_LITERAL_P (d->cur->value))
6908 tree value = d->cur->value;
6909 if (!same_type_p (TREE_TYPE (value), type))
6911 if (complain & tf_error)
6912 error ("invalid type %qT as initializer for a vector of type %qT",
6913 TREE_TYPE (d->cur->value), type);
6914 value = error_mark_node;
6916 ++d->cur;
6917 return value;
6920 /* For a vector, we initialize it as an array of the appropriate size. */
6921 if (VECTOR_TYPE_P (type))
6922 max_index = size_int (TYPE_VECTOR_SUBPARTS (type) - 1);
6924 return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6925 NULL_TREE, complain);
6928 /* Subroutine of reshape_init*: We're initializing an element with TYPE from
6929 INIT, in isolation from any designator or other initializers. */
6931 static tree
6932 reshape_single_init (tree type, tree init, tsubst_flags_t complain)
6934 /* We could also implement this by wrapping init in a new CONSTRUCTOR and
6935 calling reshape_init, but this way can just live on the stack. */
6936 constructor_elt elt = { /*index=*/NULL_TREE, init };
6937 reshape_iter iter = { &elt, &elt + 1 };
6938 return reshape_init_r (type, &iter,
6939 /*first_initializer_p=*/NULL_TREE,
6940 complain);
6943 /* Subroutine of reshape_init_r, processes the initializers for classes
6944 or union. Parameters are the same of reshape_init_r. */
6946 static tree
6947 reshape_init_class (tree type, reshape_iter *d, bool first_initializer_p,
6948 tsubst_flags_t complain)
6950 tree field;
6951 tree new_init;
6953 gcc_assert (CLASS_TYPE_P (type));
6955 /* The initializer for a class is always a CONSTRUCTOR. */
6956 new_init = build_constructor (init_list_type_node, NULL);
6958 int binfo_idx = -1;
6959 tree binfo = TYPE_BINFO (type);
6960 tree base_binfo = NULL_TREE;
6961 if (cxx_dialect >= cxx17 && uses_template_parms (type))
6963 /* We get here from maybe_aggr_guide for C++20 class template argument
6964 deduction. In this case we need to look through the binfo because a
6965 template doesn't have base fields. */
6966 binfo_idx = 0;
6967 BINFO_BASE_ITERATE (binfo, binfo_idx, base_binfo);
6969 if (base_binfo)
6970 field = base_binfo;
6971 else
6972 field = next_aggregate_field (TYPE_FIELDS (type));
6974 if (!field)
6976 /* [dcl.init.aggr]
6978 An initializer for an aggregate member that is an
6979 empty class shall have the form of an empty
6980 initializer-list {}. */
6981 if (!first_initializer_p)
6983 if (complain & tf_error)
6984 error ("initializer for %qT must be brace-enclosed", type);
6985 return error_mark_node;
6987 return new_init;
6990 /* For C++20 CTAD, handle pack expansions in the base list. */
6991 tree last_was_pack_expansion = NULL_TREE;
6993 /* Loop through the initializable fields, gathering initializers. */
6994 while (d->cur != d->end)
6996 tree field_init;
6997 constructor_elt *old_cur = d->cur;
6998 bool direct_desig = false;
7000 /* Handle C++20 designated initializers. */
7001 if (d->cur->index)
7003 if (d->cur->index == error_mark_node)
7004 return error_mark_node;
7006 if (TREE_CODE (d->cur->index) == FIELD_DECL)
7008 /* We already reshaped this; we should have returned early from
7009 reshape_init. */
7010 gcc_checking_assert (false);
7011 if (field != d->cur->index)
7013 if (tree id = DECL_NAME (d->cur->index))
7014 gcc_checking_assert (d->cur->index
7015 == get_class_binding (type, id));
7016 field = d->cur->index;
7019 else if (TREE_CODE (d->cur->index) == IDENTIFIER_NODE)
7021 CONSTRUCTOR_IS_DESIGNATED_INIT (new_init) = true;
7022 field = get_class_binding (type, d->cur->index);
7023 direct_desig = true;
7025 else
7027 if (complain & tf_error)
7028 error ("%<[%E] =%> used in a GNU-style designated initializer"
7029 " for class %qT", d->cur->index, type);
7030 return error_mark_node;
7033 if (!field && ANON_AGGR_TYPE_P (type))
7034 /* Apparently the designator isn't for a member of this anonymous
7035 struct, so head back to the enclosing class. */
7036 break;
7038 if (!field || TREE_CODE (field) != FIELD_DECL)
7040 if (complain & tf_error)
7042 if (field && TREE_CODE (field) == TREE_LIST)
7044 error ("request for member %qD is ambiguous",
7045 d->cur->index);
7046 print_candidates (field);
7048 else
7049 error ("%qT has no non-static data member named %qD", type,
7050 d->cur->index);
7052 return error_mark_node;
7055 /* If the element is an anonymous union object and the initializer
7056 list is a designated-initializer-list, the anonymous union object
7057 is initialized by the designated-initializer-list { D }, where D
7058 is the designated-initializer-clause naming a member of the
7059 anonymous union object. */
7060 tree ictx = DECL_CONTEXT (field);
7061 if (!same_type_ignoring_top_level_qualifiers_p (ictx, type))
7063 /* Find the anon aggr that is a direct member of TYPE. */
7064 while (ANON_AGGR_TYPE_P (ictx))
7066 tree cctx = TYPE_CONTEXT (ictx);
7067 if (same_type_ignoring_top_level_qualifiers_p (cctx, type))
7068 goto found;
7069 ictx = cctx;
7072 /* Not found, e.g. FIELD is a member of a base class. */
7073 if (complain & tf_error)
7074 error ("%qD is not a direct member of %qT", field, type);
7075 return error_mark_node;
7077 found:
7078 /* Now find the TYPE member with that anon aggr type. */
7079 tree aafield = TYPE_FIELDS (type);
7080 for (; aafield; aafield = TREE_CHAIN (aafield))
7081 if (TREE_TYPE (aafield) == ictx)
7082 break;
7083 gcc_assert (aafield);
7084 field = aafield;
7085 direct_desig = false;
7089 /* If we processed all the member of the class, we are done. */
7090 if (!field)
7091 break;
7093 last_was_pack_expansion = (PACK_EXPANSION_P (TREE_TYPE (field))
7094 ? field : NULL_TREE);
7095 if (last_was_pack_expansion)
7096 /* Each non-trailing aggregate element that is a pack expansion is
7097 assumed to correspond to no elements of the initializer list. */
7098 goto continue_;
7100 if (direct_desig)
7102 /* The designated field F is initialized from this one element.
7104 Note that we don't want to do this if we found the designator
7105 inside an anon aggr above; we use the normal code to implement:
7107 "If the element is an anonymous union member and the initializer
7108 list is a brace-enclosed designated- initializer-list, the element
7109 is initialized by the designated-initializer-list { D }, where D
7110 is the designated- initializer-clause naming a member of the
7111 anonymous union member." */
7112 field_init = reshape_single_init (TREE_TYPE (field),
7113 d->cur->value, complain);
7114 d->cur++;
7116 else
7117 field_init = reshape_init_r (TREE_TYPE (field), d,
7118 /*first_initializer_p=*/NULL_TREE,
7119 complain);
7121 if (field_init == error_mark_node)
7122 return error_mark_node;
7124 if (d->cur == old_cur && d->cur->index)
7126 /* This can happen with an invalid initializer for a flexible
7127 array member (c++/54441). */
7128 if (complain & tf_error)
7129 error ("invalid initializer for %q#D", field);
7130 return error_mark_node;
7133 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init), field, field_init);
7135 /* [dcl.init.aggr]
7137 When a union is initialized with a brace-enclosed
7138 initializer, the braces shall only contain an
7139 initializer for the first member of the union. */
7140 if (TREE_CODE (type) == UNION_TYPE)
7141 break;
7143 continue_:
7144 if (base_binfo)
7146 if (BINFO_BASE_ITERATE (binfo, ++binfo_idx, base_binfo))
7147 field = base_binfo;
7148 else
7149 field = next_aggregate_field (TYPE_FIELDS (type));
7151 else
7152 field = next_aggregate_field (DECL_CHAIN (field));
7155 /* A trailing aggregate element that is a pack expansion is assumed to
7156 correspond to all remaining elements of the initializer list (if any). */
7157 if (last_was_pack_expansion)
7159 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
7160 last_was_pack_expansion, d->cur->value);
7161 while (d->cur != d->end)
7162 d->cur++;
7165 return new_init;
7168 /* Subroutine of reshape_init_r. We're in a context where C99 initializer
7169 designators are not valid; either complain or return true to indicate
7170 that reshape_init_r should return error_mark_node. */
7172 static bool
7173 has_designator_problem (reshape_iter *d, tsubst_flags_t complain)
7175 if (d->cur->index)
7177 if (complain & tf_error)
7178 error_at (cp_expr_loc_or_input_loc (d->cur->index),
7179 "C99 designator %qE outside aggregate initializer",
7180 d->cur->index);
7181 else
7182 return true;
7184 return false;
7187 /* Subroutine of reshape_init, which processes a single initializer (part of
7188 a CONSTRUCTOR). TYPE is the type of the variable being initialized, D is the
7189 iterator within the CONSTRUCTOR which points to the initializer to process.
7190 If this is the first initializer of the outermost CONSTRUCTOR node,
7191 FIRST_INITIALIZER_P is that CONSTRUCTOR; otherwise, it is NULL_TREE. */
7193 static tree
7194 reshape_init_r (tree type, reshape_iter *d, tree first_initializer_p,
7195 tsubst_flags_t complain)
7197 tree init = d->cur->value;
7199 if (error_operand_p (init))
7200 return error_mark_node;
7202 if (first_initializer_p && !CP_AGGREGATE_TYPE_P (type)
7203 && has_designator_problem (d, complain))
7204 return error_mark_node;
7206 tree stripped_init = tree_strip_any_location_wrapper (init);
7208 if (TREE_CODE (type) == COMPLEX_TYPE)
7210 /* A complex type can be initialized from one or two initializers,
7211 but braces are not elided. */
7212 d->cur++;
7213 if (BRACE_ENCLOSED_INITIALIZER_P (stripped_init))
7215 if (CONSTRUCTOR_NELTS (stripped_init) > 2)
7217 if (complain & tf_error)
7218 error ("too many initializers for %qT", type);
7219 else
7220 return error_mark_node;
7223 else if (first_initializer_p && d->cur != d->end)
7225 vec<constructor_elt, va_gc> *v = 0;
7226 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
7227 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, d->cur->value);
7228 if (has_designator_problem (d, complain))
7229 return error_mark_node;
7230 d->cur++;
7231 init = build_constructor (init_list_type_node, v);
7233 return init;
7236 /* A non-aggregate type is always initialized with a single
7237 initializer. */
7238 if (!CP_AGGREGATE_TYPE_P (type)
7239 /* As is an array with dependent bound, which we can see
7240 during C++20 aggregate CTAD. */
7241 || (cxx_dialect >= cxx20
7242 && TREE_CODE (type) == ARRAY_TYPE
7243 && uses_template_parms (TYPE_DOMAIN (type))))
7245 /* It is invalid to initialize a non-aggregate type with a
7246 brace-enclosed initializer before C++0x.
7247 We need to check for BRACE_ENCLOSED_INITIALIZER_P here because
7248 of g++.old-deja/g++.mike/p7626.C: a pointer-to-member constant is
7249 a CONSTRUCTOR (with a record type). */
7250 if (TREE_CODE (stripped_init) == CONSTRUCTOR
7251 /* Don't complain about a capture-init. */
7252 && !CONSTRUCTOR_IS_DIRECT_INIT (stripped_init)
7253 && BRACE_ENCLOSED_INITIALIZER_P (stripped_init)) /* p7626.C */
7255 if (SCALAR_TYPE_P (type))
7257 if (cxx_dialect < cxx11)
7259 if (complain & tf_error)
7260 error ("braces around scalar initializer for type %qT",
7261 type);
7262 init = error_mark_node;
7264 else if (first_initializer_p
7265 || (CONSTRUCTOR_NELTS (stripped_init) > 0
7266 && (BRACE_ENCLOSED_INITIALIZER_P
7267 (CONSTRUCTOR_ELT (stripped_init,0)->value))))
7269 if (complain & tf_error)
7270 error ("too many braces around scalar initializer "
7271 "for type %qT", type);
7272 init = error_mark_node;
7275 else
7276 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
7279 d->cur++;
7280 return init;
7283 /* "If T is a class type and the initializer list has a single element of
7284 type cv U, where U is T or a class derived from T, the object is
7285 initialized from that element." Even if T is an aggregate. */
7286 if (cxx_dialect >= cxx11 && (CLASS_TYPE_P (type) || VECTOR_TYPE_P (type))
7287 && first_initializer_p
7288 /* But not if it's a designated init. */
7289 && !d->cur->index
7290 && d->end - d->cur == 1
7291 && reference_related_p (type, TREE_TYPE (init)))
7293 d->cur++;
7294 return init;
7297 /* [dcl.init.aggr]
7299 All implicit type conversions (clause _conv_) are considered when
7300 initializing the aggregate member with an initializer from an
7301 initializer-list. If the initializer can initialize a member,
7302 the member is initialized. Otherwise, if the member is itself a
7303 non-empty subaggregate, brace elision is assumed and the
7304 initializer is considered for the initialization of the first
7305 member of the subaggregate. */
7306 if ((TREE_CODE (init) != CONSTRUCTOR || COMPOUND_LITERAL_P (init))
7307 /* But don't try this for the first initializer, since that would be
7308 looking through the outermost braces; A a2 = { a1 }; is not a
7309 valid aggregate initialization. */
7310 && !first_initializer_p
7311 && (same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (init))
7312 || can_convert_arg (type, TREE_TYPE (init), init, LOOKUP_NORMAL,
7313 complain)))
7315 d->cur++;
7316 return init;
7319 /* [dcl.init.string]
7321 A char array (whether plain char, signed char, or unsigned char)
7322 can be initialized by a string-literal (optionally enclosed in
7323 braces); a wchar_t array can be initialized by a wide
7324 string-literal (optionally enclosed in braces). */
7325 if (TREE_CODE (type) == ARRAY_TYPE
7326 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type))))
7328 tree str_init = init;
7329 tree stripped_str_init = stripped_init;
7330 reshape_iter stripd = {};
7332 /* Strip one level of braces if and only if they enclose a single
7333 element (as allowed by [dcl.init.string]). */
7334 if (!first_initializer_p
7335 && TREE_CODE (stripped_str_init) == CONSTRUCTOR
7336 && CONSTRUCTOR_NELTS (stripped_str_init) == 1)
7338 stripd.cur = CONSTRUCTOR_ELT (stripped_str_init, 0);
7339 str_init = stripd.cur->value;
7340 stripped_str_init = tree_strip_any_location_wrapper (str_init);
7343 /* If it's a string literal, then it's the initializer for the array
7344 as a whole. Otherwise, continue with normal initialization for
7345 array types (one value per array element). */
7346 if (TREE_CODE (stripped_str_init) == STRING_CST)
7348 if ((first_initializer_p && has_designator_problem (d, complain))
7349 || (stripd.cur && has_designator_problem (&stripd, complain)))
7350 return error_mark_node;
7351 d->cur++;
7352 return str_init;
7356 /* The following cases are about aggregates. If we are not within a full
7357 initializer already, and there is not a CONSTRUCTOR, it means that there
7358 is a missing set of braces (that is, we are processing the case for
7359 which reshape_init exists). */
7360 bool braces_elided_p = false;
7361 if (!first_initializer_p)
7363 if (TREE_CODE (stripped_init) == CONSTRUCTOR)
7365 tree init_type = TREE_TYPE (init);
7366 if (init_type && TYPE_PTRMEMFUNC_P (init_type))
7367 /* There is no need to call reshape_init for pointer-to-member
7368 function initializers, as they are always constructed correctly
7369 by the front end. Here we have e.g. {.__pfn=0B, .__delta=0},
7370 which is missing outermost braces. We should warn below, and
7371 one of the routines below will wrap it in additional { }. */;
7372 /* For a nested compound literal, proceed to specialized routines,
7373 to handle initialization of arrays and similar. */
7374 else if (COMPOUND_LITERAL_P (stripped_init))
7375 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
7376 /* If we have an unresolved designator, we need to find the member it
7377 designates within TYPE, so proceed to the routines below. For
7378 FIELD_DECL or INTEGER_CST designators, we're already initializing
7379 the designated element. */
7380 else if (d->cur->index
7381 && TREE_CODE (d->cur->index) == IDENTIFIER_NODE)
7382 /* Brace elision with designators is only permitted for anonymous
7383 aggregates. */
7384 gcc_checking_assert (ANON_AGGR_TYPE_P (type));
7385 /* A CONSTRUCTOR of the target's type is a previously
7386 digested initializer. */
7387 else if (same_type_ignoring_top_level_qualifiers_p (type, init_type))
7389 ++d->cur;
7390 return init;
7392 else
7394 /* Something that hasn't been reshaped yet. */
7395 ++d->cur;
7396 gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
7397 return reshape_init (type, init, complain);
7401 if (complain & tf_warning)
7402 warning (OPT_Wmissing_braces,
7403 "missing braces around initializer for %qT",
7404 type);
7405 braces_elided_p = true;
7408 /* Dispatch to specialized routines. */
7409 tree new_init;
7410 if (CLASS_TYPE_P (type))
7411 new_init = reshape_init_class (type, d, first_initializer_p, complain);
7412 else if (TREE_CODE (type) == ARRAY_TYPE)
7413 new_init = reshape_init_array (type, d, first_initializer_p, complain);
7414 else if (VECTOR_TYPE_P (type))
7415 new_init = reshape_init_vector (type, d, complain);
7416 else
7417 gcc_unreachable();
7419 if (braces_elided_p
7420 && TREE_CODE (new_init) == CONSTRUCTOR)
7421 CONSTRUCTOR_BRACES_ELIDED_P (new_init) = true;
7423 return new_init;
7426 /* Undo the brace-elision allowed by [dcl.init.aggr] in a
7427 brace-enclosed aggregate initializer.
7429 INIT is the CONSTRUCTOR containing the list of initializers describing
7430 a brace-enclosed initializer for an entity of the indicated aggregate TYPE.
7431 It may not presently match the shape of the TYPE; for example:
7433 struct S { int a; int b; };
7434 struct S a[] = { 1, 2, 3, 4 };
7436 Here INIT will hold a vector of four elements, rather than a
7437 vector of two elements, each itself a vector of two elements. This
7438 routine transforms INIT from the former form into the latter. The
7439 revised CONSTRUCTOR node is returned. */
7441 tree
7442 reshape_init (tree type, tree init, tsubst_flags_t complain)
7444 vec<constructor_elt, va_gc> *v;
7445 reshape_iter d;
7446 tree new_init;
7448 gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (init));
7450 v = CONSTRUCTOR_ELTS (init);
7452 /* An empty constructor does not need reshaping, and it is always a valid
7453 initializer. */
7454 if (vec_safe_is_empty (v))
7455 return init;
7457 if ((*v)[0].index && TREE_CODE ((*v)[0].index) == FIELD_DECL)
7458 /* Already reshaped. */
7459 return init;
7461 /* Brace elision is not performed for a CONSTRUCTOR representing
7462 parenthesized aggregate initialization. */
7463 if (CONSTRUCTOR_IS_PAREN_INIT (init))
7465 tree elt = (*v)[0].value;
7466 /* If we're initializing a char array from a string-literal that is
7467 enclosed in braces, unwrap it here. */
7468 if (TREE_CODE (type) == ARRAY_TYPE
7469 && vec_safe_length (v) == 1
7470 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
7471 && TREE_CODE (tree_strip_any_location_wrapper (elt)) == STRING_CST)
7472 return elt;
7473 return init;
7476 /* Handle [dcl.init.list] direct-list-initialization from
7477 single element of enumeration with a fixed underlying type. */
7478 if (is_direct_enum_init (type, init))
7480 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
7481 type = cv_unqualified (type);
7482 if (check_narrowing (ENUM_UNDERLYING_TYPE (type), elt, complain))
7484 warning_sentinel w (warn_useless_cast);
7485 warning_sentinel w2 (warn_ignored_qualifiers);
7486 return cp_build_c_cast (input_location, type, elt,
7487 tf_warning_or_error);
7489 else
7490 return error_mark_node;
7493 /* Recurse on this CONSTRUCTOR. */
7494 d.cur = &(*v)[0];
7495 d.end = d.cur + v->length ();
7497 new_init = reshape_init_r (type, &d, init, complain);
7498 if (new_init == error_mark_node)
7499 return error_mark_node;
7501 /* Make sure all the element of the constructor were used. Otherwise,
7502 issue an error about exceeding initializers. */
7503 if (d.cur != d.end)
7505 if (complain & tf_error)
7506 error ("too many initializers for %qT", type);
7507 return error_mark_node;
7510 if (CONSTRUCTOR_IS_DIRECT_INIT (init)
7511 && BRACE_ENCLOSED_INITIALIZER_P (new_init))
7512 CONSTRUCTOR_IS_DIRECT_INIT (new_init) = true;
7513 if (CONSTRUCTOR_IS_DESIGNATED_INIT (init)
7514 && BRACE_ENCLOSED_INITIALIZER_P (new_init))
7515 gcc_checking_assert (CONSTRUCTOR_IS_DESIGNATED_INIT (new_init)
7516 || seen_error ());
7518 return new_init;
7521 /* Verify array initializer. Returns true if errors have been reported. */
7523 bool
7524 check_array_initializer (tree decl, tree type, tree init)
7526 tree element_type = TREE_TYPE (type);
7528 /* Structured binding when initialized with an array type needs
7529 to have complete type. */
7530 if (decl
7531 && DECL_DECOMPOSITION_P (decl)
7532 && !DECL_DECOMP_BASE (decl)
7533 && !COMPLETE_TYPE_P (type))
7535 error_at (DECL_SOURCE_LOCATION (decl),
7536 "structured binding has incomplete type %qT", type);
7537 TREE_TYPE (decl) = error_mark_node;
7538 return true;
7541 /* The array type itself need not be complete, because the
7542 initializer may tell us how many elements are in the array.
7543 But, the elements of the array must be complete. */
7544 if (!COMPLETE_TYPE_P (complete_type (element_type)))
7546 if (decl)
7547 error_at (DECL_SOURCE_LOCATION (decl),
7548 "elements of array %q#D have incomplete type", decl);
7549 else
7550 error ("elements of array %q#T have incomplete type", type);
7551 return true;
7554 location_t loc = (decl ? location_of (decl) : input_location);
7555 if (!verify_type_context (loc, TCTX_ARRAY_ELEMENT, element_type))
7556 return true;
7558 /* A compound literal can't have variable size. */
7559 if (init && !decl
7560 && ((COMPLETE_TYPE_P (type) && !TREE_CONSTANT (TYPE_SIZE (type)))
7561 || !TREE_CONSTANT (TYPE_SIZE (element_type))))
7563 error ("variable-sized compound literal");
7564 return true;
7566 return false;
7569 /* Subroutine of check_initializer; args are passed down from that function.
7570 Set stmts_are_full_exprs_p to 1 across a call to build_aggr_init. */
7572 static tree
7573 build_aggr_init_full_exprs (tree decl, tree init, int flags)
7575 gcc_assert (stmts_are_full_exprs_p ());
7576 if (init)
7577 maybe_warn_pessimizing_move (init, TREE_TYPE (decl), /*return_p*/false);
7578 return build_aggr_init (decl, init, flags, tf_warning_or_error);
7581 /* Verify INIT (the initializer for DECL), and record the
7582 initialization in DECL_INITIAL, if appropriate. CLEANUP is as for
7583 grok_reference_init.
7585 If the return value is non-NULL, it is an expression that must be
7586 evaluated dynamically to initialize DECL. */
7588 static tree
7589 check_initializer (tree decl, tree init, int flags, vec<tree, va_gc> **cleanups)
7591 tree type;
7592 tree init_code = NULL;
7593 tree core_type;
7595 /* Things that are going to be initialized need to have complete
7596 type. */
7597 TREE_TYPE (decl) = type = complete_type (TREE_TYPE (decl));
7599 if (DECL_HAS_VALUE_EXPR_P (decl))
7601 /* A variable with DECL_HAS_VALUE_EXPR_P set is just a placeholder,
7602 it doesn't have storage to be initialized. */
7603 gcc_assert (init == NULL_TREE);
7604 return NULL_TREE;
7607 if (type == error_mark_node)
7608 /* We will have already complained. */
7609 return NULL_TREE;
7611 if (TREE_CODE (type) == ARRAY_TYPE)
7613 if (check_array_initializer (decl, type, init))
7614 return NULL_TREE;
7616 else if (!COMPLETE_TYPE_P (type))
7618 error_at (DECL_SOURCE_LOCATION (decl),
7619 "%q#D has incomplete type", decl);
7620 TREE_TYPE (decl) = error_mark_node;
7621 return NULL_TREE;
7623 else
7624 /* There is no way to make a variable-sized class type in GNU C++. */
7625 gcc_assert (TREE_CONSTANT (TYPE_SIZE (type)));
7627 if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
7629 int init_len = CONSTRUCTOR_NELTS (init);
7630 if (SCALAR_TYPE_P (type))
7632 if (init_len == 0)
7634 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
7635 init = build_zero_init (type, NULL_TREE, false);
7637 else if (init_len != 1 && TREE_CODE (type) != COMPLEX_TYPE)
7639 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
7640 "scalar object %qD requires one element in "
7641 "initializer", decl);
7642 TREE_TYPE (decl) = error_mark_node;
7643 return NULL_TREE;
7648 if (TREE_CODE (decl) == CONST_DECL)
7650 gcc_assert (!TYPE_REF_P (type));
7652 DECL_INITIAL (decl) = init;
7654 gcc_assert (init != NULL_TREE);
7655 init = NULL_TREE;
7657 else if (!init && DECL_REALLY_EXTERN (decl))
7659 else if (init || type_build_ctor_call (type)
7660 || TYPE_REF_P (type))
7662 if (TYPE_REF_P (type))
7664 init = grok_reference_init (decl, type, init, flags);
7665 flags |= LOOKUP_ALREADY_DIGESTED;
7667 else if (!init)
7668 check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
7669 tf_warning_or_error);
7670 /* Do not reshape constructors of vectors (they don't need to be
7671 reshaped. */
7672 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
7674 if (is_std_init_list (type))
7676 init = perform_implicit_conversion (type, init,
7677 tf_warning_or_error);
7678 flags |= LOOKUP_ALREADY_DIGESTED;
7680 else if (TYPE_NON_AGGREGATE_CLASS (type))
7682 /* Don't reshape if the class has constructors. */
7683 if (cxx_dialect == cxx98)
7684 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
7685 "in C++98 %qD must be initialized by "
7686 "constructor, not by %<{...}%>",
7687 decl);
7689 else if (VECTOR_TYPE_P (type) && TYPE_VECTOR_OPAQUE (type))
7691 error ("opaque vector types cannot be initialized");
7692 init = error_mark_node;
7694 else
7696 init = reshape_init (type, init, tf_warning_or_error);
7697 flags |= LOOKUP_NO_NARROWING;
7700 /* [dcl.init] "Otherwise, if the destination type is an array, the object
7701 is initialized as follows..." So handle things like
7703 int a[](1, 2, 3);
7705 which is permitted in C++20 by P0960. */
7706 else if (TREE_CODE (init) == TREE_LIST
7707 && TREE_TYPE (init) == NULL_TREE
7708 && TREE_CODE (type) == ARRAY_TYPE
7709 && !DECL_DECOMPOSITION_P (decl)
7710 && (cxx_dialect >= cxx20))
7711 init = do_aggregate_paren_init (init, type);
7712 else if (TREE_CODE (init) == TREE_LIST
7713 && TREE_TYPE (init) != unknown_type_node
7714 && !MAYBE_CLASS_TYPE_P (type))
7716 gcc_assert (TREE_CODE (decl) != RESULT_DECL);
7718 /* We get here with code like `int a (2);' */
7719 init = build_x_compound_expr_from_list (init, ELK_INIT,
7720 tf_warning_or_error);
7723 /* If DECL has an array type without a specific bound, deduce the
7724 array size from the initializer. */
7725 maybe_deduce_size_from_array_init (decl, init);
7726 type = TREE_TYPE (decl);
7727 if (type == error_mark_node)
7728 return NULL_TREE;
7730 if (((type_build_ctor_call (type) || CLASS_TYPE_P (type))
7731 && !(flags & LOOKUP_ALREADY_DIGESTED)
7732 && !(init && BRACE_ENCLOSED_INITIALIZER_P (init)
7733 && CP_AGGREGATE_TYPE_P (type)
7734 && (CLASS_TYPE_P (type)
7735 /* The call to build_aggr_init below could end up
7736 calling build_vec_init, which may break when we
7737 are processing a template. */
7738 || processing_template_decl
7739 || !TYPE_NEEDS_CONSTRUCTING (type)
7740 || type_has_extended_temps (type))))
7741 || (DECL_DECOMPOSITION_P (decl) && TREE_CODE (type) == ARRAY_TYPE))
7743 init_code = build_aggr_init_full_exprs (decl, init, flags);
7745 /* A constructor call is a non-trivial initializer even if
7746 it isn't explicitly written. */
7747 if (TREE_SIDE_EFFECTS (init_code))
7748 DECL_NONTRIVIALLY_INITIALIZED_P (decl) = true;
7750 /* If this is a constexpr initializer, expand_default_init will
7751 have returned an INIT_EXPR rather than a CALL_EXPR. In that
7752 case, pull the initializer back out and pass it down into
7753 store_init_value. */
7754 while (true)
7756 if (TREE_CODE (init_code) == EXPR_STMT
7757 || TREE_CODE (init_code) == STMT_EXPR
7758 || TREE_CODE (init_code) == CONVERT_EXPR)
7759 init_code = TREE_OPERAND (init_code, 0);
7760 else if (TREE_CODE (init_code) == BIND_EXPR)
7761 init_code = BIND_EXPR_BODY (init_code);
7762 else
7763 break;
7765 if (TREE_CODE (init_code) == INIT_EXPR)
7767 /* In C++20, the call to build_aggr_init could have created
7768 an INIT_EXPR with a CONSTRUCTOR as the RHS to handle
7769 A(1, 2). */
7770 tree rhs = TREE_OPERAND (init_code, 1);
7771 if (processing_template_decl && TREE_CODE (rhs) == TARGET_EXPR)
7772 /* Avoid leaking TARGET_EXPR into template trees. */
7773 rhs = build_implicit_conv_flags (type, init, flags);
7774 init = rhs;
7776 init_code = NULL_TREE;
7777 /* Don't call digest_init; it's unnecessary and will complain
7778 about aggregate initialization of non-aggregate classes. */
7779 flags |= LOOKUP_ALREADY_DIGESTED;
7781 else if (DECL_DECLARED_CONSTEXPR_P (decl)
7782 || DECL_DECLARED_CONSTINIT_P (decl))
7784 /* Declared constexpr or constinit, but no suitable initializer;
7785 massage init appropriately so we can pass it into
7786 store_init_value for the error. */
7787 tree new_init = NULL_TREE;
7788 if (!processing_template_decl
7789 && TREE_CODE (init_code) == CALL_EXPR)
7790 new_init = build_cplus_new (type, init_code, tf_none);
7791 else if (CLASS_TYPE_P (type)
7792 && (!init || TREE_CODE (init) == TREE_LIST))
7793 new_init = build_functional_cast (input_location, type,
7794 init, tf_none);
7795 if (new_init)
7797 init = new_init;
7798 if (TREE_CODE (init) == TARGET_EXPR
7799 && !(flags & LOOKUP_ONLYCONVERTING))
7800 TARGET_EXPR_DIRECT_INIT_P (init) = true;
7802 init_code = NULL_TREE;
7804 else
7805 init = NULL_TREE;
7808 if (init && TREE_CODE (init) != TREE_VEC)
7810 init_code = store_init_value (decl, init, cleanups, flags);
7812 if (DECL_INITIAL (decl)
7813 && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
7814 && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl))))
7816 tree elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ().value;
7817 if (TREE_CODE (TREE_TYPE (elt)) == ARRAY_TYPE
7818 && TYPE_SIZE (TREE_TYPE (elt)) == NULL_TREE)
7819 cp_complete_array_type (&TREE_TYPE (elt), elt, false);
7822 if (pedantic && TREE_CODE (type) == ARRAY_TYPE
7823 && DECL_INITIAL (decl)
7824 && TREE_CODE (DECL_INITIAL (decl)) == STRING_CST
7825 && PAREN_STRING_LITERAL_P (DECL_INITIAL (decl)))
7826 warning_at (cp_expr_loc_or_loc (DECL_INITIAL (decl),
7827 DECL_SOURCE_LOCATION (decl)),
7828 0, "array %qD initialized by parenthesized "
7829 "string literal %qE",
7830 decl, DECL_INITIAL (decl));
7831 init = NULL_TREE;
7834 else
7836 if (CLASS_TYPE_P (core_type = strip_array_types (type))
7837 && (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type)
7838 || CLASSTYPE_REF_FIELDS_NEED_INIT (core_type)))
7839 diagnose_uninitialized_cst_or_ref_member (core_type, /*using_new=*/false,
7840 /*complain=*/true);
7842 check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
7843 tf_warning_or_error);
7846 if (init && init != error_mark_node)
7847 init_code = cp_build_init_expr (decl, init);
7849 if (init_code && !TREE_SIDE_EFFECTS (init_code)
7850 && init_code != error_mark_node)
7851 init_code = NULL_TREE;
7853 if (init_code)
7855 /* We might have set these in cp_finish_decl. */
7856 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = false;
7857 TREE_CONSTANT (decl) = false;
7860 if (init_code
7861 && DECL_IN_AGGR_P (decl)
7862 && DECL_INITIALIZED_IN_CLASS_P (decl))
7864 static int explained = 0;
7866 if (cxx_dialect < cxx11)
7867 error ("initializer invalid for static member with constructor");
7868 else if (cxx_dialect < cxx17)
7869 error ("non-constant in-class initialization invalid for static "
7870 "member %qD", decl);
7871 else
7872 error ("non-constant in-class initialization invalid for non-inline "
7873 "static member %qD", decl);
7874 if (!explained)
7876 inform (input_location,
7877 "(an out of class initialization is required)");
7878 explained = 1;
7880 return NULL_TREE;
7883 return init_code;
7886 /* If DECL is not a local variable, give it RTL. */
7888 static void
7889 make_rtl_for_nonlocal_decl (tree decl, tree init, const char* asmspec)
7891 int toplev = toplevel_bindings_p ();
7892 int defer_p;
7894 /* Set the DECL_ASSEMBLER_NAME for the object. */
7895 if (asmspec)
7897 /* The `register' keyword, when used together with an
7898 asm-specification, indicates that the variable should be
7899 placed in a particular register. */
7900 if (VAR_P (decl) && DECL_REGISTER (decl))
7902 set_user_assembler_name (decl, asmspec);
7903 DECL_HARD_REGISTER (decl) = 1;
7905 else
7907 if (TREE_CODE (decl) == FUNCTION_DECL
7908 && fndecl_built_in_p (decl, BUILT_IN_NORMAL))
7909 set_builtin_user_assembler_name (decl, asmspec);
7910 set_user_assembler_name (decl, asmspec);
7911 if (DECL_LOCAL_DECL_P (decl))
7912 if (auto ns_decl = DECL_LOCAL_DECL_ALIAS (decl))
7913 /* We have to propagate the name to the ns-alias.
7914 This is horrible, as we're affecting a
7915 possibly-shared decl. Again, a one-true-decl
7916 model breaks down. */
7917 if (ns_decl != error_mark_node)
7918 set_user_assembler_name (ns_decl, asmspec);
7922 /* Handle non-variables up front. */
7923 if (!VAR_P (decl))
7925 rest_of_decl_compilation (decl, toplev, at_eof);
7926 return;
7929 /* If we see a class member here, it should be a static data
7930 member. */
7931 if (DECL_LANG_SPECIFIC (decl) && DECL_IN_AGGR_P (decl))
7933 gcc_assert (TREE_STATIC (decl));
7934 /* An in-class declaration of a static data member should be
7935 external; it is only a declaration, and not a definition. */
7936 if (init == NULL_TREE)
7937 gcc_assert (DECL_EXTERNAL (decl)
7938 || !TREE_PUBLIC (decl));
7941 /* We don't create any RTL for local variables. */
7942 if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
7943 return;
7945 /* We defer emission of local statics until the corresponding
7946 DECL_EXPR is expanded. But with constexpr its function might never
7947 be expanded, so go ahead and tell cgraph about the variable now. */
7948 defer_p = ((DECL_FUNCTION_SCOPE_P (decl)
7949 && !var_in_maybe_constexpr_fn (decl))
7950 || DECL_VIRTUAL_P (decl));
7952 /* Defer template instantiations. */
7953 if (DECL_LANG_SPECIFIC (decl)
7954 && DECL_IMPLICIT_INSTANTIATION (decl))
7955 defer_p = 1;
7957 /* If we're not deferring, go ahead and assemble the variable. */
7958 if (!defer_p)
7959 rest_of_decl_compilation (decl, toplev, at_eof);
7962 /* walk_tree helper for wrap_temporary_cleanups, below. */
7964 static tree
7965 wrap_cleanups_r (tree *stmt_p, int *walk_subtrees, void *data)
7967 /* Stop at types or full-expression boundaries. */
7968 if (TYPE_P (*stmt_p)
7969 || TREE_CODE (*stmt_p) == CLEANUP_POINT_EXPR)
7971 *walk_subtrees = 0;
7972 return NULL_TREE;
7975 if (TREE_CODE (*stmt_p) == TARGET_EXPR)
7977 tree guard = (tree)data;
7978 tree tcleanup = TARGET_EXPR_CLEANUP (*stmt_p);
7980 if (tcleanup && !CLEANUP_EH_ONLY (*stmt_p)
7981 && !expr_noexcept_p (tcleanup, tf_none))
7983 tcleanup = build2 (TRY_CATCH_EXPR, void_type_node, tcleanup, guard);
7984 /* Tell honor_protect_cleanup_actions to handle this as a separate
7985 cleanup. */
7986 TRY_CATCH_IS_CLEANUP (tcleanup) = 1;
7987 TARGET_EXPR_CLEANUP (*stmt_p) = tcleanup;
7991 return NULL_TREE;
7994 /* We're initializing a local variable which has a cleanup GUARD. If there
7995 are any temporaries used in the initializer INIT of this variable, we
7996 need to wrap their cleanups with TRY_CATCH_EXPR (, GUARD) so that the
7997 variable will be cleaned up properly if one of them throws.
7999 Unfortunately, there's no way to express this properly in terms of
8000 nesting, as the regions for the temporaries overlap the region for the
8001 variable itself; if there are two temporaries, the variable needs to be
8002 the first thing destroyed if either of them throws. However, we only
8003 want to run the variable's cleanup if it actually got constructed. So
8004 we need to guard the temporary cleanups with the variable's cleanup if
8005 they are run on the normal path, but not if they are run on the
8006 exceptional path. We implement this by telling
8007 honor_protect_cleanup_actions to strip the variable cleanup from the
8008 exceptional path.
8010 Another approach could be to make the variable cleanup region enclose
8011 initialization, but depend on a flag to indicate that the variable is
8012 initialized; that's effectively what we do for arrays. But the current
8013 approach works fine for non-arrays, and has no code overhead in the usual
8014 case where the temporary destructors are noexcept. */
8016 static void
8017 wrap_temporary_cleanups (tree init, tree guard)
8019 if (TREE_CODE (guard) == BIND_EXPR)
8021 /* An array cleanup region already encloses any temporary cleanups,
8022 don't wrap it around them again. */
8023 gcc_checking_assert (BIND_EXPR_VEC_DTOR (guard));
8024 return;
8026 cp_walk_tree_without_duplicates (&init, wrap_cleanups_r, (void *)guard);
8029 /* Generate code to initialize DECL (a local variable). */
8031 static void
8032 initialize_local_var (tree decl, tree init)
8034 tree type = TREE_TYPE (decl);
8035 tree cleanup;
8036 int already_used;
8038 gcc_assert (VAR_P (decl)
8039 || TREE_CODE (decl) == RESULT_DECL);
8040 gcc_assert (!TREE_STATIC (decl));
8042 if (DECL_SIZE (decl) == NULL_TREE)
8044 /* If we used it already as memory, it must stay in memory. */
8045 DECL_INITIAL (decl) = NULL_TREE;
8046 TREE_ADDRESSABLE (decl) = TREE_USED (decl);
8047 return;
8050 if (type == error_mark_node)
8051 return;
8053 /* Compute and store the initial value. */
8054 already_used = TREE_USED (decl) || TREE_USED (type);
8055 if (TREE_USED (type))
8056 DECL_READ_P (decl) = 1;
8058 /* Generate a cleanup, if necessary. */
8059 cleanup = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
8061 /* Perform the initialization. */
8062 if (init)
8064 tree rinit = (TREE_CODE (init) == INIT_EXPR
8065 ? TREE_OPERAND (init, 1) : NULL_TREE);
8066 if (rinit && !TREE_SIDE_EFFECTS (rinit)
8067 && TREE_OPERAND (init, 0) == decl)
8069 /* Stick simple initializers in DECL_INITIAL so that
8070 -Wno-init-self works (c++/34772). */
8071 DECL_INITIAL (decl) = rinit;
8073 if (warn_init_self && TYPE_REF_P (type))
8075 STRIP_NOPS (rinit);
8076 if (rinit == decl)
8077 warning_at (DECL_SOURCE_LOCATION (decl),
8078 OPT_Winit_self,
8079 "reference %qD is initialized with itself", decl);
8082 else
8084 int saved_stmts_are_full_exprs_p;
8086 /* If we're only initializing a single object, guard the
8087 destructors of any temporaries used in its initializer with
8088 its destructor. */
8089 if (cleanup)
8090 wrap_temporary_cleanups (init, cleanup);
8092 gcc_assert (building_stmt_list_p ());
8093 saved_stmts_are_full_exprs_p = stmts_are_full_exprs_p ();
8094 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
8095 finish_expr_stmt (init);
8096 current_stmt_tree ()->stmts_are_full_exprs_p =
8097 saved_stmts_are_full_exprs_p;
8101 /* Set this to 0 so we can tell whether an aggregate which was
8102 initialized was ever used. Don't do this if it has a
8103 destructor, so we don't complain about the 'resource
8104 allocation is initialization' idiom. Now set
8105 attribute((unused)) on types so decls of that type will be
8106 marked used. (see TREE_USED, above.) */
8107 if (TYPE_NEEDS_CONSTRUCTING (type)
8108 && ! already_used
8109 && TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
8110 && DECL_NAME (decl))
8111 TREE_USED (decl) = 0;
8112 else if (already_used)
8113 TREE_USED (decl) = 1;
8115 if (cleanup)
8116 finish_decl_cleanup (decl, cleanup);
8119 /* DECL is a VAR_DECL for a compiler-generated variable with static
8120 storage duration (like a virtual table) whose initializer is a
8121 compile-time constant. Initialize the variable and provide it to the
8122 back end. */
8124 void
8125 initialize_artificial_var (tree decl, vec<constructor_elt, va_gc> *v)
8127 tree init;
8128 gcc_assert (DECL_ARTIFICIAL (decl));
8129 init = build_constructor (TREE_TYPE (decl), v);
8130 gcc_assert (TREE_CODE (init) == CONSTRUCTOR);
8131 DECL_INITIAL (decl) = init;
8132 DECL_INITIALIZED_P (decl) = 1;
8133 /* Mark the decl as constexpr so that we can access its content
8134 at compile time. */
8135 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
8136 DECL_DECLARED_CONSTEXPR_P (decl) = true;
8137 determine_visibility (decl);
8138 layout_var_decl (decl);
8139 maybe_commonize_var (decl);
8140 make_rtl_for_nonlocal_decl (decl, init, /*asmspec=*/NULL);
8143 /* INIT is the initializer for a variable, as represented by the
8144 parser. Returns true iff INIT is value-dependent. */
8146 static bool
8147 value_dependent_init_p (tree init)
8149 if (TREE_CODE (init) == TREE_LIST)
8150 /* A parenthesized initializer, e.g.: int i (3, 2); ? */
8151 return any_value_dependent_elements_p (init);
8152 else if (TREE_CODE (init) == CONSTRUCTOR)
8153 /* A brace-enclosed initializer, e.g.: int i = { 3 }; ? */
8155 if (dependent_type_p (TREE_TYPE (init)))
8156 return true;
8158 vec<constructor_elt, va_gc> *elts;
8159 size_t nelts;
8160 size_t i;
8162 elts = CONSTRUCTOR_ELTS (init);
8163 nelts = vec_safe_length (elts);
8164 for (i = 0; i < nelts; ++i)
8165 if (value_dependent_init_p ((*elts)[i].value))
8166 return true;
8168 else
8169 /* It must be a simple expression, e.g., int i = 3; */
8170 return value_dependent_expression_p (init);
8172 return false;
8175 // Returns true if a DECL is VAR_DECL with the concept specifier.
8176 static inline bool
8177 is_concept_var (tree decl)
8179 return (VAR_P (decl)
8180 // Not all variables have DECL_LANG_SPECIFIC.
8181 && DECL_LANG_SPECIFIC (decl)
8182 && DECL_DECLARED_CONCEPT_P (decl));
8185 /* A helper function to be called via walk_tree. If any label exists
8186 under *TP, it is (going to be) forced. Set has_forced_label_in_static. */
8188 static tree
8189 notice_forced_label_r (tree *tp, int *walk_subtrees, void *)
8191 if (TYPE_P (*tp))
8192 *walk_subtrees = 0;
8193 if (TREE_CODE (*tp) == LABEL_DECL)
8194 cfun->has_forced_label_in_static = 1;
8195 return NULL_TREE;
8198 /* Return true if DECL has either a trivial destructor, or for C++20
8199 is constexpr and has a constexpr destructor. */
8201 static bool
8202 decl_maybe_constant_destruction (tree decl, tree type)
8204 return (TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
8205 || (cxx_dialect >= cxx20
8206 && VAR_P (decl)
8207 && DECL_DECLARED_CONSTEXPR_P (decl)
8208 && type_has_constexpr_destructor (strip_array_types (type))));
8211 static tree declare_simd_adjust_this (tree *, int *, void *);
8213 /* Helper function of omp_declare_variant_finalize. Finalize one
8214 "omp declare variant base" attribute. Return true if it should be
8215 removed. */
8217 static bool
8218 omp_declare_variant_finalize_one (tree decl, tree attr)
8220 if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
8222 walk_tree (&TREE_VALUE (TREE_VALUE (attr)), declare_simd_adjust_this,
8223 DECL_ARGUMENTS (decl), NULL);
8224 walk_tree (&TREE_PURPOSE (TREE_VALUE (attr)), declare_simd_adjust_this,
8225 DECL_ARGUMENTS (decl), NULL);
8228 tree ctx = TREE_VALUE (TREE_VALUE (attr));
8229 tree simd = omp_get_context_selector (ctx, OMP_TRAIT_SET_CONSTRUCT,
8230 OMP_TRAIT_CONSTRUCT_SIMD);
8231 if (simd)
8233 TREE_VALUE (simd)
8234 = c_omp_declare_simd_clauses_to_numbers (DECL_ARGUMENTS (decl),
8235 OMP_TS_PROPERTIES (simd));
8236 /* FIXME, adjusting simd args unimplemented. */
8237 return true;
8240 tree chain = TREE_CHAIN (TREE_VALUE (attr));
8241 location_t varid_loc
8242 = cp_expr_loc_or_input_loc (TREE_PURPOSE (TREE_CHAIN (chain)));
8243 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
8244 cp_id_kind idk = (cp_id_kind) tree_to_uhwi (TREE_VALUE (chain));
8245 tree variant = TREE_PURPOSE (TREE_VALUE (attr));
8247 location_t save_loc = input_location;
8248 input_location = varid_loc;
8250 releasing_vec args;
8251 tree parm = DECL_ARGUMENTS (decl);
8252 if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
8253 parm = DECL_CHAIN (parm);
8254 for (; parm; parm = DECL_CHAIN (parm))
8255 if (type_dependent_expression_p (parm))
8256 vec_safe_push (args, build_constructor (TREE_TYPE (parm), NULL));
8257 else if (MAYBE_CLASS_TYPE_P (TREE_TYPE (parm)))
8258 vec_safe_push (args, build_local_temp (TREE_TYPE (parm)));
8259 else
8260 vec_safe_push (args, build_zero_cst (TREE_TYPE (parm)));
8262 bool koenig_p = false;
8263 if (idk == CP_ID_KIND_UNQUALIFIED || idk == CP_ID_KIND_TEMPLATE_ID)
8265 if (identifier_p (variant)
8266 /* In C++20, we may need to perform ADL for a template
8267 name. */
8268 || (TREE_CODE (variant) == TEMPLATE_ID_EXPR
8269 && identifier_p (TREE_OPERAND (variant, 0))))
8271 if (!args->is_empty ())
8273 koenig_p = true;
8274 if (!any_type_dependent_arguments_p (args))
8275 variant = perform_koenig_lookup (variant, args,
8276 tf_warning_or_error);
8278 else
8279 variant = unqualified_fn_lookup_error (variant);
8281 else if (!args->is_empty () && is_overloaded_fn (variant))
8283 tree fn = get_first_fn (variant);
8284 fn = STRIP_TEMPLATE (fn);
8285 if (!((TREE_CODE (fn) == USING_DECL && DECL_DEPENDENT_P (fn))
8286 || DECL_FUNCTION_MEMBER_P (fn)
8287 || DECL_LOCAL_DECL_P (fn)))
8289 koenig_p = true;
8290 if (!any_type_dependent_arguments_p (args))
8291 variant = perform_koenig_lookup (variant, args,
8292 tf_warning_or_error);
8297 if (idk == CP_ID_KIND_QUALIFIED)
8298 variant = finish_call_expr (variant, &args, /*disallow_virtual=*/true,
8299 koenig_p, tf_warning_or_error);
8300 else
8301 variant = finish_call_expr (variant, &args, /*disallow_virtual=*/false,
8302 koenig_p, tf_warning_or_error);
8303 if (variant == error_mark_node && !processing_template_decl)
8304 return true;
8306 variant = cp_get_callee_fndecl_nofold (variant);
8307 input_location = save_loc;
8309 if (variant)
8311 const char *varname = IDENTIFIER_POINTER (DECL_NAME (variant));
8312 if (!comptypes (TREE_TYPE (decl), TREE_TYPE (variant), 0))
8314 error_at (varid_loc, "variant %qD and base %qD have incompatible "
8315 "types", variant, decl);
8316 return true;
8318 if (fndecl_built_in_p (variant)
8319 && (startswith (varname, "__builtin_")
8320 || startswith (varname, "__sync_")
8321 || startswith (varname, "__atomic_")))
8323 error_at (varid_loc, "variant %qD is a built-in", variant);
8324 return true;
8326 else
8328 tree construct
8329 = omp_get_context_selector_list (ctx, OMP_TRAIT_SET_CONSTRUCT);
8330 omp_mark_declare_variant (match_loc, variant, construct);
8331 if (!omp_context_selector_matches (ctx))
8332 return true;
8333 TREE_PURPOSE (TREE_VALUE (attr)) = variant;
8336 else if (!processing_template_decl)
8338 error_at (varid_loc, "could not find variant declaration");
8339 return true;
8342 return false;
8345 /* Helper function, finish up "omp declare variant base" attribute
8346 now that there is a DECL. ATTR is the first "omp declare variant base"
8347 attribute. */
8349 void
8350 omp_declare_variant_finalize (tree decl, tree attr)
8352 size_t attr_len = strlen ("omp declare variant base");
8353 tree *list = &DECL_ATTRIBUTES (decl);
8354 bool remove_all = false;
8355 location_t match_loc = DECL_SOURCE_LOCATION (decl);
8356 if (TREE_CHAIN (TREE_VALUE (attr))
8357 && TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))
8358 && EXPR_HAS_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))))
8359 match_loc = EXPR_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr))));
8360 if (DECL_CONSTRUCTOR_P (decl))
8362 error_at (match_loc, "%<declare variant%> on constructor %qD", decl);
8363 remove_all = true;
8365 else if (DECL_DESTRUCTOR_P (decl))
8367 error_at (match_loc, "%<declare variant%> on destructor %qD", decl);
8368 remove_all = true;
8370 else if (DECL_DEFAULTED_FN (decl))
8372 error_at (match_loc, "%<declare variant%> on defaulted %qD", decl);
8373 remove_all = true;
8375 else if (DECL_DELETED_FN (decl))
8377 error_at (match_loc, "%<declare variant%> on deleted %qD", decl);
8378 remove_all = true;
8380 else if (DECL_VIRTUAL_P (decl))
8382 error_at (match_loc, "%<declare variant%> on virtual %qD", decl);
8383 remove_all = true;
8385 /* This loop is like private_lookup_attribute, except that it works
8386 with tree * rather than tree, as we might want to remove the
8387 attributes that are diagnosed as errorneous. */
8388 while (*list)
8390 tree attr = get_attribute_name (*list);
8391 size_t ident_len = IDENTIFIER_LENGTH (attr);
8392 if (cmp_attribs ("omp declare variant base", attr_len,
8393 IDENTIFIER_POINTER (attr), ident_len))
8395 if (remove_all || omp_declare_variant_finalize_one (decl, *list))
8397 *list = TREE_CHAIN (*list);
8398 continue;
8401 list = &TREE_CHAIN (*list);
8405 static void cp_maybe_mangle_decomp (tree, cp_decomp *);
8407 /* Finish processing of a declaration;
8408 install its line number and initial value.
8409 If the length of an array type is not known before,
8410 it must be determined now, from the initial value, or it is an error.
8412 INIT is the initializer (if any) for DECL. If INIT_CONST_EXPR_P is
8413 true, then INIT is an integral constant expression.
8415 FLAGS is LOOKUP_ONLYCONVERTING if the = init syntax was used, else 0
8416 if the (init) syntax was used.
8418 DECOMP is first identifier's DECL and identifier count in a structured
8419 bindings, nullptr if not a structured binding. */
8421 void
8422 cp_finish_decl (tree decl, tree init, bool init_const_expr_p,
8423 tree asmspec_tree, int flags, cp_decomp *decomp)
8425 vec<tree, va_gc> *cleanups = NULL;
8426 const char *asmspec = NULL;
8427 int was_readonly = 0;
8428 bool var_definition_p = false;
8429 tree auto_node;
8431 if (decl == error_mark_node)
8432 return;
8433 else if (! decl)
8435 if (init)
8436 error ("assignment (not initialization) in declaration");
8437 return;
8440 gcc_assert (TREE_CODE (decl) != RESULT_DECL);
8441 /* Parameters are handled by store_parm_decls, not cp_finish_decl. */
8442 gcc_assert (TREE_CODE (decl) != PARM_DECL);
8444 tree type = TREE_TYPE (decl);
8445 if (type == error_mark_node)
8446 return;
8448 if (VAR_P (decl) && is_copy_initialization (init))
8449 flags |= LOOKUP_ONLYCONVERTING;
8451 /* Warn about register storage specifiers except when in GNU global
8452 or local register variable extension. */
8453 if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec_tree == NULL_TREE)
8455 if (cxx_dialect >= cxx17)
8456 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
8457 "ISO C++17 does not allow %<register%> storage "
8458 "class specifier");
8459 else
8460 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
8461 "%<register%> storage class specifier used");
8464 /* If a name was specified, get the string. */
8465 if (at_namespace_scope_p ())
8466 asmspec_tree = maybe_apply_renaming_pragma (decl, asmspec_tree);
8467 if (asmspec_tree && asmspec_tree != error_mark_node)
8468 asmspec = TREE_STRING_POINTER (asmspec_tree);
8470 bool in_class_decl
8471 = (current_class_type
8472 && CP_DECL_CONTEXT (decl) == current_class_type
8473 && TYPE_BEING_DEFINED (current_class_type)
8474 && !CLASSTYPE_TEMPLATE_INSTANTIATION (current_class_type));
8476 if (in_class_decl
8477 && (DECL_INITIAL (decl) || init))
8478 DECL_INITIALIZED_IN_CLASS_P (decl) = 1;
8480 if (VAR_P (decl)
8481 && (auto_node = type_uses_auto (type)))
8483 tree d_init;
8484 if (init == NULL_TREE)
8486 if (DECL_LANG_SPECIFIC (decl)
8487 && DECL_TEMPLATE_INSTANTIATION (decl)
8488 && !DECL_TEMPLATE_INSTANTIATED (decl))
8490 /* init is null because we're deferring instantiating the
8491 initializer until we need it. Well, we need it now. */
8492 instantiate_decl (decl, /*defer_ok*/true, /*expl*/false);
8493 return;
8496 if (CLASS_PLACEHOLDER_TEMPLATE (auto_node))
8497 /* Class deduction with no initializer is OK. */;
8498 else
8500 /* Ordinary auto deduction without an initializer, a situation
8501 which grokdeclarator already detects and rejects for the most
8502 part. But we can still get here if we're instantiating a
8503 variable template before we've fully parsed (and attached) its
8504 initializer, e.g. template<class> auto x = x<int>; */
8505 error_at (DECL_SOURCE_LOCATION (decl),
8506 "declaration of %q#D has no initializer", decl);
8507 TREE_TYPE (decl) = error_mark_node;
8508 return;
8511 d_init = init;
8512 if (d_init)
8514 if (TREE_CODE (d_init) == TREE_LIST
8515 && !CLASS_PLACEHOLDER_TEMPLATE (auto_node))
8516 d_init = build_x_compound_expr_from_list (d_init, ELK_INIT,
8517 tf_warning_or_error);
8518 d_init = resolve_nondeduced_context (d_init, tf_warning_or_error);
8519 /* Force auto deduction now. Use tf_none to avoid redundant warnings
8520 on deprecated-14.C. */
8521 mark_single_function (d_init, tf_none);
8523 enum auto_deduction_context adc = adc_variable_type;
8524 if (DECL_DECOMPOSITION_P (decl))
8525 adc = adc_decomp_type;
8526 tree outer_targs = NULL_TREE;
8527 if (PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node)
8528 && DECL_LANG_SPECIFIC (decl)
8529 && DECL_TEMPLATE_INFO (decl)
8530 && !DECL_FUNCTION_SCOPE_P (decl))
8531 /* The outer template arguments might be needed for satisfaction.
8532 (For function scope variables, do_auto_deduction will obtain the
8533 outer template arguments from current_function_decl.) */
8534 outer_targs = DECL_TI_ARGS (decl);
8535 type = TREE_TYPE (decl) = do_auto_deduction (type, d_init, auto_node,
8536 tf_warning_or_error, adc,
8537 outer_targs, flags);
8538 if (type == error_mark_node)
8539 return;
8540 if (TREE_CODE (type) == FUNCTION_TYPE)
8542 error ("initializer for %<decltype(auto) %D%> has function type; "
8543 "did you forget the %<()%>?", decl);
8544 TREE_TYPE (decl) = error_mark_node;
8545 return;
8547 /* As in start_decl_1, complete so TREE_READONLY is set properly. */
8548 if (!processing_template_decl
8549 && !type_uses_auto (type)
8550 && !COMPLETE_TYPE_P (complete_type (type)))
8552 error_at (location_of (decl),
8553 "deduced type %qT for %qD is incomplete", type, decl);
8554 cxx_incomplete_type_inform (type);
8555 TREE_TYPE (decl) = error_mark_node;
8556 return;
8558 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
8560 /* Update the type of the corresponding TEMPLATE_DECL to match. */
8561 if (DECL_LANG_SPECIFIC (decl)
8562 && DECL_TEMPLATE_INFO (decl)
8563 && DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (decl)) == decl)
8564 TREE_TYPE (DECL_TI_TEMPLATE (decl)) = type;
8567 if (ensure_literal_type_for_constexpr_object (decl) == error_mark_node)
8569 DECL_DECLARED_CONSTEXPR_P (decl) = 0;
8570 if (VAR_P (decl) && DECL_CLASS_SCOPE_P (decl))
8572 init = NULL_TREE;
8573 DECL_EXTERNAL (decl) = 1;
8577 if (VAR_P (decl)
8578 && DECL_CLASS_SCOPE_P (decl)
8579 && verify_type_context (DECL_SOURCE_LOCATION (decl),
8580 TCTX_STATIC_STORAGE, type)
8581 && DECL_INITIALIZED_IN_CLASS_P (decl))
8582 check_static_variable_definition (decl, type);
8584 if (!processing_template_decl && VAR_P (decl) && is_global_var (decl))
8586 type_context_kind context = (DECL_THREAD_LOCAL_P (decl)
8587 ? TCTX_THREAD_STORAGE
8588 : TCTX_STATIC_STORAGE);
8589 verify_type_context (input_location, context, TREE_TYPE (decl));
8592 if (init && TREE_CODE (decl) == FUNCTION_DECL)
8594 tree clone;
8595 if (init == ridpointers[(int)RID_DELETE])
8597 /* FIXME check this is 1st decl. */
8598 DECL_DELETED_FN (decl) = 1;
8599 DECL_DECLARED_INLINE_P (decl) = 1;
8600 DECL_INITIAL (decl) = error_mark_node;
8601 FOR_EACH_CLONE (clone, decl)
8603 DECL_DELETED_FN (clone) = 1;
8604 DECL_DECLARED_INLINE_P (clone) = 1;
8605 DECL_INITIAL (clone) = error_mark_node;
8607 init = NULL_TREE;
8609 else if (init == ridpointers[(int)RID_DEFAULT])
8611 if (defaultable_fn_check (decl))
8612 DECL_DEFAULTED_FN (decl) = 1;
8613 else
8614 DECL_INITIAL (decl) = NULL_TREE;
8618 if (init && VAR_P (decl))
8620 DECL_NONTRIVIALLY_INITIALIZED_P (decl) = 1;
8621 /* If DECL is a reference, then we want to know whether init is a
8622 reference constant; init_const_expr_p as passed tells us whether
8623 it's an rvalue constant. */
8624 if (TYPE_REF_P (type))
8625 init_const_expr_p = potential_constant_expression (init);
8626 if (init_const_expr_p)
8628 /* Set these flags now for templates. We'll update the flags in
8629 store_init_value for instantiations. */
8630 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
8631 if (decl_maybe_constant_var_p (decl)
8632 /* FIXME setting TREE_CONSTANT on refs breaks the back end. */
8633 && !TYPE_REF_P (type))
8634 TREE_CONSTANT (decl) = true;
8636 /* This is handled mostly by gimplify.cc, but we have to deal with
8637 not warning about int x = x; as it is a GCC extension to turn off
8638 this warning but only if warn_init_self is zero. */
8639 if (!DECL_EXTERNAL (decl)
8640 && !TREE_STATIC (decl)
8641 && decl == tree_strip_any_location_wrapper (init)
8642 && !warning_enabled_at (DECL_SOURCE_LOCATION (decl), OPT_Winit_self))
8643 suppress_warning (decl, OPT_Winit_self);
8645 else if (VAR_P (decl)
8646 && COMPLETE_TYPE_P (type)
8647 && !TYPE_REF_P (type)
8648 && !dependent_type_p (type)
8649 && is_really_empty_class (type, /*ignore_vptr*/false))
8650 /* We have no initializer but there's nothing to initialize anyway.
8651 Treat DECL as constant due to c++/109876. */
8652 TREE_CONSTANT (decl) = true;
8654 if (flag_openmp
8655 && TREE_CODE (decl) == FUNCTION_DECL
8656 /* #pragma omp declare variant on methods handled in finish_struct
8657 instead. */
8658 && (!DECL_OBJECT_MEMBER_FUNCTION_P (decl)
8659 || COMPLETE_TYPE_P (DECL_CONTEXT (decl))))
8660 if (tree attr = lookup_attribute ("omp declare variant base",
8661 DECL_ATTRIBUTES (decl)))
8662 omp_declare_variant_finalize (decl, attr);
8664 if (processing_template_decl)
8666 bool type_dependent_p;
8668 /* Add this declaration to the statement-tree. */
8669 if (at_function_scope_p ())
8670 add_decl_expr (decl);
8672 type_dependent_p = dependent_type_p (type);
8674 if (check_for_bare_parameter_packs (init))
8676 init = NULL_TREE;
8677 DECL_INITIAL (decl) = NULL_TREE;
8680 /* Generally, initializers in templates are expanded when the
8681 template is instantiated. But, if DECL is a variable constant
8682 then it can be used in future constant expressions, so its value
8683 must be available. */
8685 bool dep_init = false;
8687 if (!VAR_P (decl) || type_dependent_p)
8688 /* We can't do anything if the decl has dependent type. */;
8689 else if (!init && is_concept_var (decl))
8691 error ("variable concept has no initializer");
8692 init = boolean_true_node;
8694 else if (init
8695 && (init_const_expr_p || DECL_DECLARED_CONSTEXPR_P (decl))
8696 && !TYPE_REF_P (type)
8697 && decl_maybe_constant_var_p (decl)
8698 && !(dep_init = value_dependent_init_p (init)))
8700 /* This variable seems to be a non-dependent constant, so process
8701 its initializer. If check_initializer returns non-null the
8702 initialization wasn't constant after all. */
8703 tree init_code;
8704 cleanups = make_tree_vector ();
8705 init_code = check_initializer (decl, init, flags, &cleanups);
8706 if (init_code == NULL_TREE)
8707 init = NULL_TREE;
8708 release_tree_vector (cleanups);
8710 else
8712 gcc_assert (!DECL_PRETTY_FUNCTION_P (decl));
8713 /* Try to deduce array size. */
8714 maybe_deduce_size_from_array_init (decl, init);
8715 /* And complain about multiple initializers. */
8716 if (init && TREE_CODE (init) == TREE_LIST && TREE_CHAIN (init)
8717 && !MAYBE_CLASS_TYPE_P (type))
8718 init = build_x_compound_expr_from_list (init, ELK_INIT,
8719 tf_warning_or_error);
8722 if (init)
8723 DECL_INITIAL (decl) = init;
8725 if (dep_init)
8727 retrofit_lang_decl (decl);
8728 SET_DECL_DEPENDENT_INIT_P (decl, true);
8731 if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec)
8733 set_user_assembler_name (decl, asmspec);
8734 DECL_HARD_REGISTER (decl) = 1;
8736 return;
8739 /* Just store non-static data member initializers for later. */
8740 if (init && TREE_CODE (decl) == FIELD_DECL)
8741 DECL_INITIAL (decl) = init;
8743 /* Take care of TYPE_DECLs up front. */
8744 if (TREE_CODE (decl) == TYPE_DECL)
8746 if (type != error_mark_node
8747 && MAYBE_CLASS_TYPE_P (type) && DECL_NAME (decl))
8749 if (TREE_TYPE (DECL_NAME (decl)) && TREE_TYPE (decl) != type)
8750 warning (0, "shadowing previous type declaration of %q#D", decl);
8751 set_identifier_type_value (DECL_NAME (decl), decl);
8754 /* If we have installed this as the canonical typedef for this
8755 type, and that type has not been defined yet, delay emitting
8756 the debug information for it, as we will emit it later. */
8757 if (TYPE_MAIN_DECL (TREE_TYPE (decl)) == decl
8758 && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
8759 TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
8761 rest_of_decl_compilation (decl, DECL_FILE_SCOPE_P (decl),
8762 at_eof);
8763 return;
8766 /* A reference will be modified here, as it is initialized. */
8767 if (! DECL_EXTERNAL (decl)
8768 && TREE_READONLY (decl)
8769 && TYPE_REF_P (type))
8771 was_readonly = 1;
8772 TREE_READONLY (decl) = 0;
8775 /* This needs to happen before extend_ref_init_temps. */
8776 if (VAR_OR_FUNCTION_DECL_P (decl))
8778 if (VAR_P (decl))
8779 maybe_commonize_var (decl);
8780 determine_visibility (decl);
8783 if (VAR_P (decl))
8785 duration_kind dk = decl_storage_duration (decl);
8786 /* [dcl.constinit]/1 "The constinit specifier shall be applied
8787 only to a declaration of a variable with static or thread storage
8788 duration." */
8789 if (DECL_DECLARED_CONSTINIT_P (decl)
8790 && !(dk == dk_thread || dk == dk_static))
8792 error_at (DECL_SOURCE_LOCATION (decl),
8793 "%<constinit%> can only be applied to a variable with "
8794 "static or thread storage duration");
8795 return;
8798 if (decomp)
8799 cp_maybe_mangle_decomp (decl, decomp);
8801 /* If this is a local variable that will need a mangled name,
8802 register it now. We must do this before processing the
8803 initializer for the variable, since the initialization might
8804 require a guard variable, and since the mangled name of the
8805 guard variable will depend on the mangled name of this
8806 variable. */
8807 if (DECL_FUNCTION_SCOPE_P (decl)
8808 && TREE_STATIC (decl)
8809 && !DECL_ARTIFICIAL (decl))
8811 /* The variable holding an anonymous union will have had its
8812 discriminator set in finish_anon_union, after which it's
8813 NAME will have been cleared. */
8814 if (DECL_NAME (decl))
8815 determine_local_discriminator (decl);
8816 /* Normally has_forced_label_in_static is set during GIMPLE
8817 lowering, but [cd]tors are never actually compiled directly.
8818 We need to set this early so we can deal with the label
8819 address extension. */
8820 if ((DECL_CONSTRUCTOR_P (current_function_decl)
8821 || DECL_DESTRUCTOR_P (current_function_decl))
8822 && init)
8824 walk_tree (&init, notice_forced_label_r, NULL, NULL);
8825 add_local_decl (cfun, decl);
8827 /* And make sure it's in the symbol table for
8828 c_parse_final_cleanups to find. */
8829 varpool_node::get_create (decl);
8832 /* Convert the initializer to the type of DECL, if we have not
8833 already initialized DECL. */
8834 if (!DECL_INITIALIZED_P (decl)
8835 /* If !DECL_EXTERNAL then DECL is being defined. In the
8836 case of a static data member initialized inside the
8837 class-specifier, there can be an initializer even if DECL
8838 is *not* defined. */
8839 && (!DECL_EXTERNAL (decl) || init))
8841 cleanups = make_tree_vector ();
8842 init = check_initializer (decl, init, flags, &cleanups);
8844 /* Handle:
8846 [dcl.init]
8848 The memory occupied by any object of static storage
8849 duration is zero-initialized at program startup before
8850 any other initialization takes place.
8852 We cannot create an appropriate initializer until after
8853 the type of DECL is finalized. If DECL_INITIAL is set,
8854 then the DECL is statically initialized, and any
8855 necessary zero-initialization has already been performed. */
8856 if (TREE_STATIC (decl) && !DECL_INITIAL (decl))
8857 DECL_INITIAL (decl) = build_zero_init (TREE_TYPE (decl),
8858 /*nelts=*/NULL_TREE,
8859 /*static_storage_p=*/true);
8860 /* Remember that the initialization for this variable has
8861 taken place. */
8862 DECL_INITIALIZED_P (decl) = 1;
8863 /* This declaration is the definition of this variable,
8864 unless we are initializing a static data member within
8865 the class specifier. */
8866 if (!DECL_EXTERNAL (decl))
8867 var_definition_p = true;
8869 /* If the variable has an array type, lay out the type, even if
8870 there is no initializer. It is valid to index through the
8871 array, and we must get TYPE_ALIGN set correctly on the array
8872 type. */
8873 else if (TREE_CODE (type) == ARRAY_TYPE)
8874 layout_type (type);
8876 if (TREE_STATIC (decl)
8877 && !at_function_scope_p ()
8878 && current_function_decl == NULL)
8879 /* So decl is a global variable or a static member of a
8880 non local class. Record the types it uses
8881 so that we can decide later to emit debug info for them. */
8882 record_types_used_by_current_var_decl (decl);
8885 /* Add this declaration to the statement-tree. This needs to happen
8886 after the call to check_initializer so that the DECL_EXPR for a
8887 reference temp is added before the DECL_EXPR for the reference itself. */
8888 if (DECL_FUNCTION_SCOPE_P (decl))
8890 /* If we're building a variable sized type, and we might be
8891 reachable other than via the top of the current binding
8892 level, then create a new BIND_EXPR so that we deallocate
8893 the object at the right time. */
8894 if (VAR_P (decl)
8895 && DECL_SIZE (decl)
8896 && !TREE_CONSTANT (DECL_SIZE (decl))
8897 && STATEMENT_LIST_HAS_LABEL (cur_stmt_list))
8899 tree bind;
8900 bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL);
8901 TREE_SIDE_EFFECTS (bind) = 1;
8902 add_stmt (bind);
8903 BIND_EXPR_BODY (bind) = push_stmt_list ();
8905 add_decl_expr (decl);
8908 /* Let the middle end know about variables and functions -- but not
8909 static data members in uninstantiated class templates. */
8910 if (VAR_OR_FUNCTION_DECL_P (decl))
8912 if (VAR_P (decl))
8914 layout_var_decl (decl);
8915 if (!flag_weak)
8916 /* Check again now that we have an initializer. */
8917 maybe_commonize_var (decl);
8918 /* A class-scope constexpr variable with an out-of-class declaration.
8919 C++17 makes them implicitly inline, but still force it out. */
8920 if (DECL_INLINE_VAR_P (decl)
8921 && !DECL_VAR_DECLARED_INLINE_P (decl)
8922 && !DECL_TEMPLATE_INSTANTIATION (decl)
8923 && !in_class_decl)
8924 mark_needed (decl);
8927 if (var_definition_p
8928 /* With -fmerge-all-constants, gimplify_init_constructor
8929 might add TREE_STATIC to aggregate variables. */
8930 && (TREE_STATIC (decl)
8931 || (flag_merge_constants >= 2
8932 && AGGREGATE_TYPE_P (type))))
8934 /* If a TREE_READONLY variable needs initialization
8935 at runtime, it is no longer readonly and we need to
8936 avoid MEM_READONLY_P being set on RTL created for it. */
8937 if (init)
8939 if (TREE_READONLY (decl))
8940 TREE_READONLY (decl) = 0;
8941 was_readonly = 0;
8943 else if (was_readonly)
8944 TREE_READONLY (decl) = 1;
8946 /* Likewise if it needs destruction. */
8947 if (!decl_maybe_constant_destruction (decl, type))
8948 TREE_READONLY (decl) = 0;
8950 else if (VAR_P (decl)
8951 && CP_DECL_THREAD_LOCAL_P (decl)
8952 && (!DECL_EXTERNAL (decl) || flag_extern_tls_init)
8953 && (was_readonly || TREE_READONLY (decl))
8954 && var_needs_tls_wrapper (decl))
8956 /* TLS variables need dynamic initialization by the TLS wrapper
8957 function, we don't want to hoist accesses to it before the
8958 wrapper. */
8959 was_readonly = 0;
8960 TREE_READONLY (decl) = 0;
8963 make_rtl_for_nonlocal_decl (decl, init, asmspec);
8965 /* Check for abstractness of the type. */
8966 if (var_definition_p)
8967 abstract_virtuals_error (decl, type);
8969 if (TREE_TYPE (decl) == error_mark_node)
8970 /* No initialization required. */
8972 else if (TREE_CODE (decl) == FUNCTION_DECL)
8974 if (init)
8976 if (init == ridpointers[(int)RID_DEFAULT])
8978 /* An out-of-class default definition is defined at
8979 the point where it is explicitly defaulted. */
8980 if (DECL_DELETED_FN (decl))
8981 maybe_explain_implicit_delete (decl);
8982 else if (DECL_INITIAL (decl) == error_mark_node)
8983 synthesize_method (decl);
8985 else
8986 error_at (cp_expr_loc_or_loc (init,
8987 DECL_SOURCE_LOCATION (decl)),
8988 "function %q#D is initialized like a variable",
8989 decl);
8991 /* else no initialization required. */
8993 else if (DECL_EXTERNAL (decl)
8994 && ! (DECL_LANG_SPECIFIC (decl)
8995 && DECL_NOT_REALLY_EXTERN (decl)))
8997 /* check_initializer will have done any constant initialization. */
8999 /* A variable definition. */
9000 else if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
9001 /* Initialize the local variable. */
9002 initialize_local_var (decl, init);
9004 /* If a variable is defined, and then a subsequent
9005 definition with external linkage is encountered, we will
9006 get here twice for the same variable. We want to avoid
9007 calling expand_static_init more than once. For variables
9008 that are not static data members, we can call
9009 expand_static_init only when we actually process the
9010 initializer. It is not legal to redeclare a static data
9011 member, so this issue does not arise in that case. */
9012 else if (var_definition_p && TREE_STATIC (decl))
9013 expand_static_init (decl, init);
9016 /* If a CLEANUP_STMT was created to destroy a temporary bound to a
9017 reference, insert it in the statement-tree now. */
9018 if (cleanups)
9020 for (tree t : *cleanups)
9022 push_cleanup (NULL_TREE, t, false);
9023 /* As in initialize_local_var. */
9024 wrap_temporary_cleanups (init, t);
9026 release_tree_vector (cleanups);
9029 if (was_readonly)
9030 TREE_READONLY (decl) = 1;
9032 if (flag_openmp
9033 && VAR_P (decl)
9034 && lookup_attribute ("omp declare target implicit",
9035 DECL_ATTRIBUTES (decl)))
9037 DECL_ATTRIBUTES (decl)
9038 = remove_attribute ("omp declare target implicit",
9039 DECL_ATTRIBUTES (decl));
9040 complete_type (TREE_TYPE (decl));
9041 if (!omp_mappable_type (TREE_TYPE (decl)))
9043 error ("%q+D in declare target directive does not have mappable"
9044 " type", decl);
9045 if (TREE_TYPE (decl) != error_mark_node
9046 && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
9047 cxx_incomplete_type_inform (TREE_TYPE (decl));
9049 else if (!lookup_attribute ("omp declare target",
9050 DECL_ATTRIBUTES (decl))
9051 && !lookup_attribute ("omp declare target link",
9052 DECL_ATTRIBUTES (decl)))
9054 DECL_ATTRIBUTES (decl)
9055 = tree_cons (get_identifier ("omp declare target"),
9056 NULL_TREE, DECL_ATTRIBUTES (decl));
9057 symtab_node *node = symtab_node::get (decl);
9058 if (node != NULL)
9060 node->offloadable = 1;
9061 if (ENABLE_OFFLOADING)
9063 g->have_offload = true;
9064 if (is_a <varpool_node *> (node))
9065 vec_safe_push (offload_vars, decl);
9071 /* This is the last point we can lower alignment so give the target the
9072 chance to do so. */
9073 if (VAR_P (decl)
9074 && !is_global_var (decl)
9075 && !DECL_HARD_REGISTER (decl))
9076 targetm.lower_local_decl_alignment (decl);
9078 invoke_plugin_callbacks (PLUGIN_FINISH_DECL, decl);
9081 /* For class TYPE return itself or some its bases that contain
9082 any direct non-static data members. Return error_mark_node if an
9083 error has been diagnosed. */
9085 static tree
9086 find_decomp_class_base (location_t loc, tree type, tree ret)
9088 bool member_seen = false;
9089 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
9090 if (TREE_CODE (field) != FIELD_DECL
9091 || DECL_ARTIFICIAL (field)
9092 || DECL_UNNAMED_BIT_FIELD (field))
9093 continue;
9094 else if (ret)
9095 return type;
9096 else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
9098 if (TREE_CODE (TREE_TYPE (field)) == RECORD_TYPE)
9099 error_at (loc, "cannot decompose class type %qT because it has an "
9100 "anonymous struct member", type);
9101 else
9102 error_at (loc, "cannot decompose class type %qT because it has an "
9103 "anonymous union member", type);
9104 inform (DECL_SOURCE_LOCATION (field), "declared here");
9105 return error_mark_node;
9107 else if (!accessible_p (type, field, true))
9109 error_at (loc, "cannot decompose inaccessible member %qD of %qT",
9110 field, type);
9111 inform (DECL_SOURCE_LOCATION (field),
9112 TREE_PRIVATE (field)
9113 ? G_("declared private here")
9114 : G_("declared protected here"));
9115 return error_mark_node;
9117 else
9118 member_seen = true;
9120 tree base_binfo, binfo;
9121 tree orig_ret = ret;
9122 int i;
9123 if (member_seen)
9124 ret = type;
9125 for (binfo = TYPE_BINFO (type), i = 0;
9126 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
9128 tree t = find_decomp_class_base (loc, TREE_TYPE (base_binfo), ret);
9129 if (t == error_mark_node)
9130 return error_mark_node;
9131 if (t != NULL_TREE && t != ret)
9133 if (ret == type)
9135 error_at (loc, "cannot decompose class type %qT: both it and "
9136 "its base class %qT have non-static data members",
9137 type, t);
9138 return error_mark_node;
9140 else if (orig_ret != NULL_TREE)
9141 return t;
9142 else if (ret != NULL_TREE)
9144 error_at (loc, "cannot decompose class type %qT: its base "
9145 "classes %qT and %qT have non-static data "
9146 "members", type, ret, t);
9147 return error_mark_node;
9149 else
9150 ret = t;
9153 return ret;
9156 /* Return std::tuple_size<TYPE>::value. */
9158 static tree
9159 get_tuple_size (tree type)
9161 tree args = make_tree_vec (1);
9162 TREE_VEC_ELT (args, 0) = type;
9163 tree inst = lookup_template_class (tuple_size_identifier, args,
9164 /*in_decl*/NULL_TREE,
9165 /*context*/std_node,
9166 /*entering_scope*/false, tf_none);
9167 inst = complete_type (inst);
9168 if (inst == error_mark_node
9169 || !COMPLETE_TYPE_P (inst)
9170 || !CLASS_TYPE_P (type))
9171 return NULL_TREE;
9172 tree val = lookup_qualified_name (inst, value_identifier,
9173 LOOK_want::NORMAL, /*complain*/false);
9174 if (val == error_mark_node)
9175 return NULL_TREE;
9176 if (VAR_P (val) || TREE_CODE (val) == CONST_DECL)
9177 val = maybe_constant_value (val);
9178 if (TREE_CODE (val) == INTEGER_CST)
9179 return val;
9180 else
9181 return error_mark_node;
9184 /* Return std::tuple_element<I,TYPE>::type. */
9186 static tree
9187 get_tuple_element_type (tree type, unsigned i)
9189 tree args = make_tree_vec (2);
9190 TREE_VEC_ELT (args, 0) = build_int_cst (integer_type_node, i);
9191 TREE_VEC_ELT (args, 1) = type;
9192 tree inst = lookup_template_class (tuple_element_identifier, args,
9193 /*in_decl*/NULL_TREE,
9194 /*context*/std_node,
9195 /*entering_scope*/false,
9196 tf_warning_or_error);
9197 return make_typename_type (inst, type_identifier,
9198 none_type, tf_warning_or_error);
9201 /* Return e.get<i>() or get<i>(e). */
9203 static tree
9204 get_tuple_decomp_init (tree decl, unsigned i)
9206 tree targs = make_tree_vec (1);
9207 TREE_VEC_ELT (targs, 0) = build_int_cst (integer_type_node, i);
9209 tree etype = TREE_TYPE (decl);
9210 tree e = convert_from_reference (decl);
9212 /* [The id-expression] e is an lvalue if the type of the entity e is an
9213 lvalue reference and an xvalue otherwise. */
9214 if (!TYPE_REF_P (etype)
9215 || TYPE_REF_IS_RVALUE (etype))
9216 e = move (e);
9218 tree fns = lookup_qualified_name (TREE_TYPE (e), get__identifier,
9219 LOOK_want::NORMAL, /*complain*/false);
9220 bool use_member_get = false;
9222 /* To use a member get, member lookup must find at least one
9223 declaration that is a function template
9224 whose first template parameter is a non-type parameter. */
9225 for (lkp_iterator iter (MAYBE_BASELINK_FUNCTIONS (fns)); iter; ++iter)
9227 tree fn = *iter;
9228 if (TREE_CODE (fn) == TEMPLATE_DECL)
9230 tree tparms = DECL_TEMPLATE_PARMS (fn);
9231 tree parm = TREE_VEC_ELT (INNERMOST_TEMPLATE_PARMS (tparms), 0);
9232 if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
9234 use_member_get = true;
9235 break;
9240 if (use_member_get)
9242 fns = lookup_template_function (fns, targs);
9243 return build_new_method_call (e, fns, /*args*/NULL,
9244 /*path*/NULL_TREE, LOOKUP_NORMAL,
9245 /*fn_p*/NULL, tf_warning_or_error);
9247 else
9249 releasing_vec args (make_tree_vector_single (e));
9250 fns = lookup_template_function (get__identifier, targs);
9251 fns = perform_koenig_lookup (fns, args, tf_warning_or_error);
9252 return finish_call_expr (fns, &args, /*novirt*/false,
9253 /*koenig*/true, tf_warning_or_error);
9257 /* It's impossible to recover the decltype of a tuple decomposition variable
9258 based on the actual type of the variable, so store it in a hash table. */
9260 static GTY((cache)) decl_tree_cache_map *decomp_type_table;
9262 tree
9263 lookup_decomp_type (tree v)
9265 return *decomp_type_table->get (v);
9268 /* Mangle a decomposition declaration if needed. Arguments like
9269 in cp_finish_decomp. */
9271 static void
9272 cp_maybe_mangle_decomp (tree decl, cp_decomp *decomp)
9274 if (!processing_template_decl
9275 && !error_operand_p (decl)
9276 && TREE_STATIC (decl))
9278 auto_vec<tree, 16> v;
9279 v.safe_grow (decomp->count, true);
9280 tree d = decomp->decl;
9281 for (unsigned int i = 0; i < decomp->count; i++, d = DECL_CHAIN (d))
9282 v[decomp->count - i - 1] = d;
9283 if (DECL_FUNCTION_SCOPE_P (decl))
9285 size_t sz = 3;
9286 for (unsigned int i = 0; i < decomp->count; ++i)
9287 sz += IDENTIFIER_LENGTH (DECL_NAME (v[i])) + 1;
9288 char *name = XALLOCAVEC (char, sz);
9289 name[0] = 'D';
9290 name[1] = 'C';
9291 char *p = name + 2;
9292 for (unsigned int i = 0; i < decomp->count; ++i)
9294 size_t len = IDENTIFIER_LENGTH (DECL_NAME (v[i]));
9295 *p++ = ' ';
9296 memcpy (p, IDENTIFIER_POINTER (DECL_NAME (v[i])), len);
9297 p += len;
9299 *p = '\0';
9300 determine_local_discriminator (decl, get_identifier (name));
9302 SET_DECL_ASSEMBLER_NAME (decl, mangle_decomp (decl, v));
9303 maybe_apply_pragma_weak (decl);
9307 /* Finish a decomposition declaration. DECL is the underlying declaration
9308 "e", FIRST is the head of a chain of decls for the individual identifiers
9309 chained through DECL_CHAIN in reverse order and COUNT is the number of
9310 those decls. */
9312 void
9313 cp_finish_decomp (tree decl, cp_decomp *decomp)
9315 tree first = decomp->decl;
9316 unsigned count = decomp->count;
9317 if (error_operand_p (decl))
9319 error_out:
9320 while (count--)
9322 TREE_TYPE (first) = error_mark_node;
9323 if (DECL_HAS_VALUE_EXPR_P (first))
9325 SET_DECL_VALUE_EXPR (first, NULL_TREE);
9326 DECL_HAS_VALUE_EXPR_P (first) = 0;
9328 first = DECL_CHAIN (first);
9330 if (DECL_P (decl) && DECL_NAMESPACE_SCOPE_P (decl))
9331 SET_DECL_ASSEMBLER_NAME (decl, get_identifier ("<decomp>"));
9332 return;
9335 location_t loc = DECL_SOURCE_LOCATION (decl);
9336 if (type_dependent_expression_p (decl)
9337 /* This happens for range for when not in templates.
9338 Still add the DECL_VALUE_EXPRs for later processing. */
9339 || (!processing_template_decl
9340 && type_uses_auto (TREE_TYPE (decl))))
9342 for (unsigned int i = 0; i < count; i++)
9344 if (!DECL_HAS_VALUE_EXPR_P (first))
9346 tree v = build_nt (ARRAY_REF, decl,
9347 size_int (count - i - 1),
9348 NULL_TREE, NULL_TREE);
9349 SET_DECL_VALUE_EXPR (first, v);
9350 DECL_HAS_VALUE_EXPR_P (first) = 1;
9352 if (processing_template_decl)
9353 fit_decomposition_lang_decl (first, decl);
9354 first = DECL_CHAIN (first);
9356 return;
9359 auto_vec<tree, 16> v;
9360 v.safe_grow (count, true);
9361 tree d = first;
9362 for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
9364 v[count - i - 1] = d;
9365 fit_decomposition_lang_decl (d, decl);
9368 tree type = TREE_TYPE (decl);
9369 tree dexp = decl;
9371 if (TYPE_REF_P (type))
9373 dexp = convert_from_reference (dexp);
9374 type = complete_type (TREE_TYPE (type));
9375 if (type == error_mark_node)
9376 goto error_out;
9377 if (!COMPLETE_TYPE_P (type))
9379 error_at (loc, "structured binding refers to incomplete type %qT",
9380 type);
9381 goto error_out;
9385 tree eltype = NULL_TREE;
9386 unsigned HOST_WIDE_INT eltscnt = 0;
9387 if (TREE_CODE (type) == ARRAY_TYPE)
9389 tree nelts;
9390 nelts = array_type_nelts_top (type);
9391 if (nelts == error_mark_node)
9392 goto error_out;
9393 if (!tree_fits_uhwi_p (nelts))
9395 error_at (loc, "cannot decompose variable length array %qT", type);
9396 goto error_out;
9398 eltscnt = tree_to_uhwi (nelts);
9399 if (count != eltscnt)
9401 cnt_mismatch:
9402 if (count > eltscnt)
9403 error_n (loc, count,
9404 "%u name provided for structured binding",
9405 "%u names provided for structured binding", count);
9406 else
9407 error_n (loc, count,
9408 "only %u name provided for structured binding",
9409 "only %u names provided for structured binding", count);
9410 inform_n (loc, eltscnt,
9411 "while %qT decomposes into %wu element",
9412 "while %qT decomposes into %wu elements",
9413 type, eltscnt);
9414 goto error_out;
9416 eltype = TREE_TYPE (type);
9417 for (unsigned int i = 0; i < count; i++)
9419 TREE_TYPE (v[i]) = eltype;
9420 layout_decl (v[i], 0);
9421 if (processing_template_decl)
9422 continue;
9423 tree t = unshare_expr (dexp);
9424 t = build4 (ARRAY_REF, eltype, t, size_int (i), NULL_TREE, NULL_TREE);
9425 SET_DECL_VALUE_EXPR (v[i], t);
9426 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9429 /* 2 GNU extensions. */
9430 else if (TREE_CODE (type) == COMPLEX_TYPE)
9432 eltscnt = 2;
9433 if (count != eltscnt)
9434 goto cnt_mismatch;
9435 eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
9436 for (unsigned int i = 0; i < count; i++)
9438 TREE_TYPE (v[i]) = eltype;
9439 layout_decl (v[i], 0);
9440 if (processing_template_decl)
9441 continue;
9442 tree t = unshare_expr (dexp);
9443 t = build1 (i ? IMAGPART_EXPR : REALPART_EXPR, eltype, t);
9444 SET_DECL_VALUE_EXPR (v[i], t);
9445 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9448 else if (TREE_CODE (type) == VECTOR_TYPE)
9450 if (!TYPE_VECTOR_SUBPARTS (type).is_constant (&eltscnt))
9452 error_at (loc, "cannot decompose variable length vector %qT", type);
9453 goto error_out;
9455 if (count != eltscnt)
9456 goto cnt_mismatch;
9457 eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
9458 for (unsigned int i = 0; i < count; i++)
9460 TREE_TYPE (v[i]) = eltype;
9461 layout_decl (v[i], 0);
9462 if (processing_template_decl)
9463 continue;
9464 tree t = unshare_expr (dexp);
9465 convert_vector_to_array_for_subscript (DECL_SOURCE_LOCATION (v[i]),
9466 &t, size_int (i));
9467 t = build4 (ARRAY_REF, eltype, t, size_int (i), NULL_TREE, NULL_TREE);
9468 SET_DECL_VALUE_EXPR (v[i], t);
9469 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9472 else if (tree tsize = get_tuple_size (type))
9474 if (tsize == error_mark_node)
9476 error_at (loc, "%<std::tuple_size<%T>::value%> is not an integral "
9477 "constant expression", type);
9478 goto error_out;
9480 if (!tree_fits_uhwi_p (tsize))
9482 error_n (loc, count,
9483 "%u name provided for structured binding",
9484 "%u names provided for structured binding", count);
9485 inform (loc, "while %qT decomposes into %E elements",
9486 type, tsize);
9487 goto error_out;
9489 eltscnt = tree_to_uhwi (tsize);
9490 if (count != eltscnt)
9491 goto cnt_mismatch;
9492 int save_read = DECL_READ_P (decl);
9493 for (unsigned i = 0; i < count; ++i)
9495 location_t sloc = input_location;
9496 location_t dloc = DECL_SOURCE_LOCATION (v[i]);
9498 input_location = dloc;
9499 tree init = get_tuple_decomp_init (decl, i);
9500 tree eltype = (init == error_mark_node ? error_mark_node
9501 : get_tuple_element_type (type, i));
9502 input_location = sloc;
9504 if (VOID_TYPE_P (eltype))
9506 error ("%<std::tuple_element<%u, %T>::type%> is %<void%>",
9507 i, type);
9508 eltype = error_mark_node;
9510 if (init == error_mark_node || eltype == error_mark_node)
9512 inform (dloc, "in initialization of structured binding "
9513 "variable %qD", v[i]);
9514 goto error_out;
9516 /* Save the decltype away before reference collapse. */
9517 hash_map_safe_put<hm_ggc> (decomp_type_table, v[i], eltype);
9518 eltype = cp_build_reference_type (eltype, !lvalue_p (init));
9519 TREE_TYPE (v[i]) = eltype;
9520 layout_decl (v[i], 0);
9521 if (DECL_HAS_VALUE_EXPR_P (v[i]))
9523 /* In this case the names are variables, not just proxies. */
9524 SET_DECL_VALUE_EXPR (v[i], NULL_TREE);
9525 DECL_HAS_VALUE_EXPR_P (v[i]) = 0;
9527 if (!processing_template_decl)
9529 copy_linkage (v[i], decl);
9530 cp_finish_decl (v[i], init, /*constexpr*/false,
9531 /*asm*/NULL_TREE, LOOKUP_NORMAL);
9534 /* Ignore reads from the underlying decl performed during initialization
9535 of the individual variables. If those will be read, we'll mark
9536 the underlying decl as read at that point. */
9537 DECL_READ_P (decl) = save_read;
9539 else if (TREE_CODE (type) == UNION_TYPE)
9541 error_at (loc, "cannot decompose union type %qT", type);
9542 goto error_out;
9544 else if (!CLASS_TYPE_P (type))
9546 error_at (loc, "cannot decompose non-array non-class type %qT", type);
9547 goto error_out;
9549 else if (LAMBDA_TYPE_P (type))
9551 error_at (loc, "cannot decompose lambda closure type %qT", type);
9552 goto error_out;
9554 else if (processing_template_decl && complete_type (type) == error_mark_node)
9555 goto error_out;
9556 else if (processing_template_decl && !COMPLETE_TYPE_P (type))
9557 pedwarn (loc, 0, "structured binding refers to incomplete class type %qT",
9558 type);
9559 else
9561 tree btype = find_decomp_class_base (loc, type, NULL_TREE);
9562 if (btype == error_mark_node)
9563 goto error_out;
9564 else if (btype == NULL_TREE)
9566 error_at (loc, "cannot decompose class type %qT without non-static "
9567 "data members", type);
9568 goto error_out;
9570 for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
9571 if (TREE_CODE (field) != FIELD_DECL
9572 || DECL_ARTIFICIAL (field)
9573 || DECL_UNNAMED_BIT_FIELD (field))
9574 continue;
9575 else
9576 eltscnt++;
9577 if (count != eltscnt)
9578 goto cnt_mismatch;
9579 tree t = dexp;
9580 if (type != btype)
9582 t = convert_to_base (t, btype, /*check_access*/true,
9583 /*nonnull*/false, tf_warning_or_error);
9584 type = btype;
9586 unsigned int i = 0;
9587 for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
9588 if (TREE_CODE (field) != FIELD_DECL
9589 || DECL_ARTIFICIAL (field)
9590 || DECL_UNNAMED_BIT_FIELD (field))
9591 continue;
9592 else
9594 tree tt = finish_non_static_data_member (field, unshare_expr (t),
9595 NULL_TREE);
9596 if (REFERENCE_REF_P (tt))
9597 tt = TREE_OPERAND (tt, 0);
9598 TREE_TYPE (v[i]) = TREE_TYPE (tt);
9599 layout_decl (v[i], 0);
9600 if (!processing_template_decl)
9602 SET_DECL_VALUE_EXPR (v[i], tt);
9603 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9605 i++;
9608 if (processing_template_decl)
9610 for (unsigned int i = 0; i < count; i++)
9611 if (!DECL_HAS_VALUE_EXPR_P (v[i]))
9613 tree a = build_nt (ARRAY_REF, decl, size_int (i),
9614 NULL_TREE, NULL_TREE);
9615 SET_DECL_VALUE_EXPR (v[i], a);
9616 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9621 /* Returns a declaration for a VAR_DECL as if:
9623 extern "C" TYPE NAME;
9625 had been seen. Used to create compiler-generated global
9626 variables. */
9628 static tree
9629 declare_global_var (tree name, tree type)
9631 auto cookie = push_abi_namespace (global_namespace);
9632 tree decl = build_decl (input_location, VAR_DECL, name, type);
9633 TREE_PUBLIC (decl) = 1;
9634 DECL_EXTERNAL (decl) = 1;
9635 DECL_ARTIFICIAL (decl) = 1;
9636 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
9637 /* If the user has explicitly declared this variable (perhaps
9638 because the code we are compiling is part of a low-level runtime
9639 library), then it is possible that our declaration will be merged
9640 with theirs by pushdecl. */
9641 decl = pushdecl (decl);
9642 cp_finish_decl (decl, NULL_TREE, false, NULL_TREE, 0);
9643 pop_abi_namespace (cookie, global_namespace);
9645 return decl;
9648 /* Returns the type for the argument to "__cxa_atexit" (or "atexit",
9649 if "__cxa_atexit" is not being used) corresponding to the function
9650 to be called when the program exits. */
9652 static tree
9653 get_atexit_fn_ptr_type (void)
9655 tree fn_type;
9657 if (!atexit_fn_ptr_type_node)
9659 tree arg_type;
9660 if (flag_use_cxa_atexit
9661 && !targetm.cxx.use_atexit_for_cxa_atexit ())
9662 /* The parameter to "__cxa_atexit" is "void (*)(void *)". */
9663 arg_type = ptr_type_node;
9664 else
9665 /* The parameter to "atexit" is "void (*)(void)". */
9666 arg_type = NULL_TREE;
9668 fn_type = build_function_type_list (void_type_node,
9669 arg_type, NULL_TREE);
9670 atexit_fn_ptr_type_node = build_pointer_type (fn_type);
9673 return atexit_fn_ptr_type_node;
9676 /* Returns a pointer to the `atexit' function. Note that if
9677 FLAG_USE_CXA_ATEXIT is nonzero, then this will actually be the new
9678 `__cxa_atexit' function specified in the IA64 C++ ABI. */
9680 static tree
9681 get_atexit_node (void)
9683 tree atexit_fndecl;
9684 tree fn_type;
9685 tree fn_ptr_type;
9686 const char *name;
9687 bool use_aeabi_atexit;
9688 tree ctx = global_namespace;
9690 if (atexit_node)
9691 return atexit_node;
9693 if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
9695 /* The declaration for `__cxa_atexit' is:
9697 int __cxa_atexit (void (*)(void *), void *, void *)
9699 We build up the argument types and then the function type
9700 itself. */
9701 tree argtype0, argtype1, argtype2;
9703 use_aeabi_atexit = targetm.cxx.use_aeabi_atexit ();
9704 /* First, build the pointer-to-function type for the first
9705 argument. */
9706 fn_ptr_type = get_atexit_fn_ptr_type ();
9707 /* Then, build the rest of the argument types. */
9708 argtype2 = ptr_type_node;
9709 if (use_aeabi_atexit)
9711 argtype1 = fn_ptr_type;
9712 argtype0 = ptr_type_node;
9714 else
9716 argtype1 = ptr_type_node;
9717 argtype0 = fn_ptr_type;
9719 /* And the final __cxa_atexit type. */
9720 fn_type = build_function_type_list (integer_type_node,
9721 argtype0, argtype1, argtype2,
9722 NULL_TREE);
9723 /* ... which needs noexcept. */
9724 fn_type = build_exception_variant (fn_type, noexcept_true_spec);
9725 if (use_aeabi_atexit)
9727 name = "__aeabi_atexit";
9728 push_to_top_level ();
9729 int n = push_namespace (get_identifier ("__aeabiv1"), false);
9730 ctx = current_namespace;
9731 while (n--)
9732 pop_namespace ();
9733 pop_from_top_level ();
9735 else
9737 name = "__cxa_atexit";
9738 ctx = abi_node;
9741 else
9743 /* The declaration for `atexit' is:
9745 int atexit (void (*)());
9747 We build up the argument types and then the function type
9748 itself. */
9749 fn_ptr_type = get_atexit_fn_ptr_type ();
9750 /* Build the final atexit type. */
9751 fn_type = build_function_type_list (integer_type_node,
9752 fn_ptr_type, NULL_TREE);
9753 /* ... which needs noexcept. */
9754 fn_type = build_exception_variant (fn_type, noexcept_true_spec);
9755 name = "atexit";
9758 /* Now, build the function declaration. */
9759 push_lang_context (lang_name_c);
9760 auto cookie = push_abi_namespace (ctx);
9761 atexit_fndecl = build_library_fn_ptr (name, fn_type, ECF_LEAF | ECF_NOTHROW);
9762 DECL_CONTEXT (atexit_fndecl) = FROB_CONTEXT (current_namespace);
9763 /* Install as hidden builtin so we're (a) more relaxed about
9764 exception spec matching and (b) will not give a confusing location
9765 in diagnostic and (c) won't magically appear in user-visible name
9766 lookups. */
9767 DECL_SOURCE_LOCATION (atexit_fndecl) = BUILTINS_LOCATION;
9768 atexit_fndecl = pushdecl (atexit_fndecl, /*hiding=*/true);
9769 pop_abi_namespace (cookie, ctx);
9770 mark_used (atexit_fndecl);
9771 pop_lang_context ();
9772 atexit_node = decay_conversion (atexit_fndecl, tf_warning_or_error);
9774 return atexit_node;
9777 /* Like get_atexit_node, but for thread-local cleanups. */
9779 static tree
9780 get_thread_atexit_node (void)
9782 if (thread_atexit_node)
9783 return thread_atexit_node;
9785 /* The declaration for `__cxa_thread_atexit' is:
9787 int __cxa_thread_atexit (void (*)(void *), void *, void *) */
9788 tree fn_type = build_function_type_list (integer_type_node,
9789 get_atexit_fn_ptr_type (),
9790 ptr_type_node, ptr_type_node,
9791 NULL_TREE);
9793 /* Now, build the function declaration, as with __cxa_atexit. */
9794 unsigned flags = push_abi_namespace ();
9795 tree atexit_fndecl = build_library_fn_ptr ("__cxa_thread_atexit", fn_type,
9796 ECF_LEAF | ECF_NOTHROW);
9797 DECL_CONTEXT (atexit_fndecl) = FROB_CONTEXT (current_namespace);
9798 DECL_SOURCE_LOCATION (atexit_fndecl) = BUILTINS_LOCATION;
9799 atexit_fndecl = pushdecl (atexit_fndecl, /*hiding=*/true);
9800 pop_abi_namespace (flags);
9801 mark_used (atexit_fndecl);
9802 thread_atexit_node = decay_conversion (atexit_fndecl, tf_warning_or_error);
9804 return thread_atexit_node;
9807 /* Returns the __dso_handle VAR_DECL. */
9809 static tree
9810 get_dso_handle_node (void)
9812 if (dso_handle_node)
9813 return dso_handle_node;
9815 /* Declare the variable. */
9816 dso_handle_node = declare_global_var (get_identifier ("__dso_handle"),
9817 ptr_type_node);
9819 #ifdef HAVE_GAS_HIDDEN
9820 if (dso_handle_node != error_mark_node)
9822 DECL_VISIBILITY (dso_handle_node) = VISIBILITY_HIDDEN;
9823 DECL_VISIBILITY_SPECIFIED (dso_handle_node) = 1;
9825 #endif
9827 return dso_handle_node;
9830 /* Begin a new function with internal linkage whose job will be simply
9831 to destroy some particular variable. */
9833 static GTY(()) int start_cleanup_cnt;
9835 static tree
9836 start_cleanup_fn (void)
9838 char name[32];
9840 push_to_top_level ();
9842 /* No need to mangle this. */
9843 push_lang_context (lang_name_c);
9845 /* Build the name of the function. */
9846 sprintf (name, "__tcf_%d", start_cleanup_cnt++);
9847 /* Build the function declaration. */
9848 tree fntype = TREE_TYPE (get_atexit_fn_ptr_type ());
9849 tree fndecl = build_lang_decl (FUNCTION_DECL, get_identifier (name), fntype);
9850 DECL_CONTEXT (fndecl) = FROB_CONTEXT (current_namespace);
9851 /* It's a function with internal linkage, generated by the
9852 compiler. */
9853 TREE_PUBLIC (fndecl) = 0;
9854 DECL_ARTIFICIAL (fndecl) = 1;
9855 /* Make the function `inline' so that it is only emitted if it is
9856 actually needed. It is unlikely that it will be inlined, since
9857 it is only called via a function pointer, but we avoid unnecessary
9858 emissions this way. */
9859 DECL_DECLARED_INLINE_P (fndecl) = 1;
9860 DECL_INTERFACE_KNOWN (fndecl) = 1;
9861 if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
9863 /* Build the parameter. */
9864 tree parmdecl = cp_build_parm_decl (fndecl, NULL_TREE, ptr_type_node);
9865 TREE_USED (parmdecl) = 1;
9866 DECL_READ_P (parmdecl) = 1;
9867 DECL_ARGUMENTS (fndecl) = parmdecl;
9870 fndecl = pushdecl (fndecl, /*hidden=*/true);
9871 start_preparsed_function (fndecl, NULL_TREE, SF_PRE_PARSED);
9873 pop_lang_context ();
9875 return current_function_decl;
9878 /* Finish the cleanup function begun by start_cleanup_fn. */
9880 static void
9881 end_cleanup_fn (void)
9883 expand_or_defer_fn (finish_function (/*inline_p=*/false));
9885 pop_from_top_level ();
9888 /* Generate code to handle the destruction of DECL, an object with
9889 static storage duration. */
9891 tree
9892 register_dtor_fn (tree decl)
9894 tree cleanup;
9895 tree addr;
9896 tree compound_stmt;
9897 tree fcall;
9898 tree type;
9899 bool ob_parm, dso_parm, use_dtor;
9900 tree arg0, arg1, arg2;
9901 tree atex_node;
9903 type = TREE_TYPE (decl);
9904 if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
9905 return void_node;
9907 if (decl_maybe_constant_destruction (decl, type)
9908 && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
9910 cxx_maybe_build_cleanup (decl, tf_warning_or_error);
9911 return void_node;
9914 /* If we're using "__cxa_atexit" (or "__cxa_thread_atexit" or
9915 "__aeabi_atexit"), and DECL is a class object, we can just pass the
9916 destructor to "__cxa_atexit"; we don't have to build a temporary
9917 function to do the cleanup. */
9918 dso_parm = (flag_use_cxa_atexit
9919 && !targetm.cxx.use_atexit_for_cxa_atexit ());
9920 ob_parm = (CP_DECL_THREAD_LOCAL_P (decl) || dso_parm);
9921 use_dtor = ob_parm && CLASS_TYPE_P (type);
9922 if (use_dtor)
9924 cleanup = get_class_binding (type, complete_dtor_identifier);
9926 /* Make sure it is accessible. */
9927 perform_or_defer_access_check (TYPE_BINFO (type), cleanup, cleanup,
9928 tf_warning_or_error);
9930 else
9932 /* Call build_cleanup before we enter the anonymous function so
9933 that any access checks will be done relative to the current
9934 scope, rather than the scope of the anonymous function. */
9935 build_cleanup (decl);
9937 /* Now start the function. */
9938 cleanup = start_cleanup_fn ();
9940 /* Now, recompute the cleanup. It may contain SAVE_EXPRs that refer
9941 to the original function, rather than the anonymous one. That
9942 will make the back end think that nested functions are in use,
9943 which causes confusion. */
9944 push_deferring_access_checks (dk_no_check);
9945 fcall = build_cleanup (decl);
9946 pop_deferring_access_checks ();
9948 /* Create the body of the anonymous function. */
9949 compound_stmt = begin_compound_stmt (BCS_FN_BODY);
9950 finish_expr_stmt (fcall);
9951 finish_compound_stmt (compound_stmt);
9952 end_cleanup_fn ();
9955 /* Call atexit with the cleanup function. */
9956 mark_used (cleanup);
9957 cleanup = build_address (cleanup);
9959 if (CP_DECL_THREAD_LOCAL_P (decl))
9960 atex_node = get_thread_atexit_node ();
9961 else
9962 atex_node = get_atexit_node ();
9964 if (use_dtor)
9966 /* We must convert CLEANUP to the type that "__cxa_atexit"
9967 expects. */
9968 cleanup = build_nop (get_atexit_fn_ptr_type (), cleanup);
9969 /* "__cxa_atexit" will pass the address of DECL to the
9970 cleanup function. */
9971 mark_used (decl);
9972 addr = build_address (decl);
9973 /* The declared type of the parameter to "__cxa_atexit" is
9974 "void *". For plain "T*", we could just let the
9975 machinery in cp_build_function_call convert it -- but if the
9976 type is "cv-qualified T *", then we need to convert it
9977 before passing it in, to avoid spurious errors. */
9978 addr = build_nop (ptr_type_node, addr);
9980 else
9981 /* Since the cleanup functions we build ignore the address
9982 they're given, there's no reason to pass the actual address
9983 in, and, in general, it's cheaper to pass NULL than any
9984 other value. */
9985 addr = null_pointer_node;
9987 if (dso_parm)
9988 arg2 = cp_build_addr_expr (get_dso_handle_node (),
9989 tf_warning_or_error);
9990 else if (ob_parm)
9991 /* Just pass NULL to the dso handle parm if we don't actually
9992 have a DSO handle on this target. */
9993 arg2 = null_pointer_node;
9994 else
9995 arg2 = NULL_TREE;
9997 if (ob_parm)
9999 if (!CP_DECL_THREAD_LOCAL_P (decl)
10000 && targetm.cxx.use_aeabi_atexit ())
10002 arg1 = cleanup;
10003 arg0 = addr;
10005 else
10007 arg1 = addr;
10008 arg0 = cleanup;
10011 else
10013 arg0 = cleanup;
10014 arg1 = NULL_TREE;
10016 return cp_build_function_call_nary (atex_node, tf_warning_or_error,
10017 arg0, arg1, arg2, NULL_TREE);
10020 /* DECL is a VAR_DECL with static storage duration. INIT, if present,
10021 is its initializer. Generate code to handle the construction
10022 and destruction of DECL. */
10024 static void
10025 expand_static_init (tree decl, tree init)
10027 gcc_assert (VAR_P (decl));
10028 gcc_assert (TREE_STATIC (decl));
10030 /* Some variables require no dynamic initialization. */
10031 if (decl_maybe_constant_destruction (decl, TREE_TYPE (decl)))
10033 /* Make sure the destructor is callable. */
10034 cxx_maybe_build_cleanup (decl, tf_warning_or_error);
10035 if (!init)
10036 return;
10039 if (CP_DECL_THREAD_LOCAL_P (decl) && DECL_GNU_TLS_P (decl)
10040 && !DECL_FUNCTION_SCOPE_P (decl))
10042 location_t dloc = DECL_SOURCE_LOCATION (decl);
10043 if (init)
10044 error_at (dloc, "non-local variable %qD declared %<__thread%> "
10045 "needs dynamic initialization", decl);
10046 else
10047 error_at (dloc, "non-local variable %qD declared %<__thread%> "
10048 "has a non-trivial destructor", decl);
10049 static bool informed;
10050 if (!informed)
10052 inform (dloc, "C++11 %<thread_local%> allows dynamic "
10053 "initialization and destruction");
10054 informed = true;
10056 return;
10059 if (DECL_FUNCTION_SCOPE_P (decl))
10061 /* Emit code to perform this initialization but once. */
10062 tree if_stmt = NULL_TREE, inner_if_stmt = NULL_TREE;
10063 tree then_clause = NULL_TREE, inner_then_clause = NULL_TREE;
10064 tree guard, guard_addr;
10065 tree flag, begin;
10066 /* We don't need thread-safety code for thread-local vars. */
10067 bool thread_guard = (flag_threadsafe_statics
10068 && !CP_DECL_THREAD_LOCAL_P (decl));
10070 /* Emit code to perform this initialization but once. This code
10071 looks like:
10073 static <type> guard;
10074 if (!__atomic_load (guard.first_byte)) {
10075 if (__cxa_guard_acquire (&guard)) {
10076 bool flag = false;
10077 try {
10078 // Do initialization.
10079 flag = true; __cxa_guard_release (&guard);
10080 // Register variable for destruction at end of program.
10081 } catch {
10082 if (!flag) __cxa_guard_abort (&guard);
10087 Note that the `flag' variable is only set to 1 *after* the
10088 initialization is complete. This ensures that an exception,
10089 thrown during the construction, will cause the variable to
10090 reinitialized when we pass through this code again, as per:
10092 [stmt.dcl]
10094 If the initialization exits by throwing an exception, the
10095 initialization is not complete, so it will be tried again
10096 the next time control enters the declaration.
10098 This process should be thread-safe, too; multiple threads
10099 should not be able to initialize the variable more than
10100 once. */
10102 /* Create the guard variable. */
10103 guard = get_guard (decl);
10105 /* Begin the conditional initialization. */
10106 if_stmt = begin_if_stmt ();
10108 finish_if_stmt_cond (get_guard_cond (guard, thread_guard), if_stmt);
10109 then_clause = begin_compound_stmt (BCS_NO_SCOPE);
10111 if (thread_guard)
10113 tree vfntype = NULL_TREE;
10114 tree acquire_name, release_name, abort_name;
10115 tree acquire_fn, release_fn, abort_fn;
10116 guard_addr = build_address (guard);
10118 acquire_name = get_identifier ("__cxa_guard_acquire");
10119 release_name = get_identifier ("__cxa_guard_release");
10120 abort_name = get_identifier ("__cxa_guard_abort");
10121 acquire_fn = get_global_binding (acquire_name);
10122 release_fn = get_global_binding (release_name);
10123 abort_fn = get_global_binding (abort_name);
10124 if (!acquire_fn)
10125 acquire_fn = push_library_fn
10126 (acquire_name, build_function_type_list (integer_type_node,
10127 TREE_TYPE (guard_addr),
10128 NULL_TREE),
10129 NULL_TREE, ECF_NOTHROW);
10130 if (!release_fn || !abort_fn)
10131 vfntype = build_function_type_list (void_type_node,
10132 TREE_TYPE (guard_addr),
10133 NULL_TREE);
10134 if (!release_fn)
10135 release_fn = push_library_fn (release_name, vfntype, NULL_TREE,
10136 ECF_NOTHROW);
10137 if (!abort_fn)
10138 abort_fn = push_library_fn (abort_name, vfntype, NULL_TREE,
10139 ECF_NOTHROW | ECF_LEAF);
10141 inner_if_stmt = begin_if_stmt ();
10142 finish_if_stmt_cond (build_call_n (acquire_fn, 1, guard_addr),
10143 inner_if_stmt);
10145 inner_then_clause = begin_compound_stmt (BCS_NO_SCOPE);
10146 begin = get_target_expr (boolean_false_node);
10147 flag = TARGET_EXPR_SLOT (begin);
10149 TARGET_EXPR_CLEANUP (begin)
10150 = build3 (COND_EXPR, void_type_node, flag,
10151 void_node,
10152 build_call_n (abort_fn, 1, guard_addr));
10153 CLEANUP_EH_ONLY (begin) = 1;
10155 /* Do the initialization itself. */
10156 init = add_stmt_to_compound (begin, init);
10157 init = add_stmt_to_compound (init,
10158 build2 (MODIFY_EXPR, void_type_node,
10159 flag, boolean_true_node));
10161 /* Use atexit to register a function for destroying this static
10162 variable. Do this before calling __cxa_guard_release. */
10163 init = add_stmt_to_compound (init, register_dtor_fn (decl));
10165 init = add_stmt_to_compound (init, build_call_n (release_fn, 1,
10166 guard_addr));
10168 else
10170 init = add_stmt_to_compound (init, set_guard (guard));
10172 /* Use atexit to register a function for destroying this static
10173 variable. */
10174 init = add_stmt_to_compound (init, register_dtor_fn (decl));
10177 finish_expr_stmt (init);
10179 if (thread_guard)
10181 finish_compound_stmt (inner_then_clause);
10182 finish_then_clause (inner_if_stmt);
10183 finish_if_stmt (inner_if_stmt);
10186 finish_compound_stmt (then_clause);
10187 finish_then_clause (if_stmt);
10188 finish_if_stmt (if_stmt);
10190 else if (CP_DECL_THREAD_LOCAL_P (decl))
10191 tls_aggregates = tree_cons (init, decl, tls_aggregates);
10192 else
10193 static_aggregates = tree_cons (init, decl, static_aggregates);
10197 /* Make TYPE a complete type based on INITIAL_VALUE.
10198 Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
10199 2 if there was no information (in which case assume 0 if DO_DEFAULT),
10200 3 if the initializer list is empty (in pedantic mode). */
10203 cp_complete_array_type (tree *ptype, tree initial_value, bool do_default)
10205 int failure;
10206 tree type, elt_type;
10208 /* Don't get confused by a CONSTRUCTOR for some other type. */
10209 if (initial_value && TREE_CODE (initial_value) == CONSTRUCTOR
10210 && !BRACE_ENCLOSED_INITIALIZER_P (initial_value)
10211 && TREE_CODE (TREE_TYPE (initial_value)) != ARRAY_TYPE)
10212 return 1;
10214 if (initial_value)
10216 /* An array of character type can be initialized from a
10217 brace-enclosed string constant so call reshape_init to
10218 remove the optional braces from a braced string literal. */
10219 if (char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (*ptype)))
10220 && BRACE_ENCLOSED_INITIALIZER_P (initial_value))
10221 initial_value = reshape_init (*ptype, initial_value,
10222 tf_warning_or_error);
10224 /* If any of the elements are parameter packs, we can't actually
10225 complete this type now because the array size is dependent. */
10226 if (TREE_CODE (initial_value) == CONSTRUCTOR)
10227 for (auto &e: CONSTRUCTOR_ELTS (initial_value))
10228 if (PACK_EXPANSION_P (e.value))
10229 return 0;
10232 failure = complete_array_type (ptype, initial_value, do_default);
10234 /* We can create the array before the element type is complete, which
10235 means that we didn't have these two bits set in the original type
10236 either. In completing the type, we are expected to propagate these
10237 bits. See also complete_type which does the same thing for arrays
10238 of fixed size. */
10239 type = *ptype;
10240 if (type != error_mark_node && TYPE_DOMAIN (type))
10242 elt_type = TREE_TYPE (type);
10243 TYPE_NEEDS_CONSTRUCTING (type) = TYPE_NEEDS_CONSTRUCTING (elt_type);
10244 TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
10245 = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (elt_type);
10248 return failure;
10251 /* As above, but either give an error or reject zero-size arrays, depending
10252 on COMPLAIN. */
10255 cp_complete_array_type_or_error (tree *ptype, tree initial_value,
10256 bool do_default, tsubst_flags_t complain)
10258 int failure;
10259 bool sfinae = !(complain & tf_error);
10260 /* In SFINAE context we can't be lenient about zero-size arrays. */
10261 if (sfinae)
10262 ++pedantic;
10263 failure = cp_complete_array_type (ptype, initial_value, do_default);
10264 if (sfinae)
10265 --pedantic;
10266 if (failure)
10268 if (sfinae)
10269 /* Not an error. */;
10270 else if (failure == 1)
10271 error ("initializer fails to determine size of %qT", *ptype);
10272 else if (failure == 2)
10274 if (do_default)
10275 error ("array size missing in %qT", *ptype);
10277 else if (failure == 3)
10278 error ("zero-size array %qT", *ptype);
10279 *ptype = error_mark_node;
10281 return failure;
10284 /* Return zero if something is declared to be a member of type
10285 CTYPE when in the context of CUR_TYPE. STRING is the error
10286 message to print in that case. Otherwise, quietly return 1. */
10288 static int
10289 member_function_or_else (tree ctype, tree cur_type, enum overload_flags flags)
10291 if (ctype && ctype != cur_type)
10293 if (flags == DTOR_FLAG)
10294 error ("destructor for alien class %qT cannot be a member", ctype);
10295 else
10296 error ("constructor for alien class %qT cannot be a member", ctype);
10297 return 0;
10299 return 1;
10302 /* Subroutine of `grokdeclarator'. */
10304 /* Generate errors possibly applicable for a given set of specifiers.
10305 This is for ARM $7.1.2. */
10307 static void
10308 bad_specifiers (tree object,
10309 enum bad_spec_place type,
10310 int virtualp,
10311 int quals,
10312 int inlinep,
10313 int friendp,
10314 int raises,
10315 const location_t* locations)
10317 switch (type)
10319 case BSP_VAR:
10320 if (virtualp)
10321 error_at (locations[ds_virtual],
10322 "%qD declared as a %<virtual%> variable", object);
10323 if (quals)
10324 error ("%<const%> and %<volatile%> function specifiers on "
10325 "%qD invalid in variable declaration", object);
10326 break;
10327 case BSP_PARM:
10328 if (virtualp)
10329 error_at (locations[ds_virtual],
10330 "%qD declared as a %<virtual%> parameter", object);
10331 if (inlinep)
10332 error_at (locations[ds_inline],
10333 "%qD declared as an %<inline%> parameter", object);
10334 if (quals)
10335 error ("%<const%> and %<volatile%> function specifiers on "
10336 "%qD invalid in parameter declaration", object);
10337 break;
10338 case BSP_TYPE:
10339 if (virtualp)
10340 error_at (locations[ds_virtual],
10341 "%qD declared as a %<virtual%> type", object);
10342 if (inlinep)
10343 error_at (locations[ds_inline],
10344 "%qD declared as an %<inline%> type", object);
10345 if (quals)
10346 error ("%<const%> and %<volatile%> function specifiers on "
10347 "%qD invalid in type declaration", object);
10348 break;
10349 case BSP_FIELD:
10350 if (virtualp)
10351 error_at (locations[ds_virtual],
10352 "%qD declared as a %<virtual%> field", object);
10353 if (inlinep)
10354 error_at (locations[ds_inline],
10355 "%qD declared as an %<inline%> field", object);
10356 if (quals)
10357 error ("%<const%> and %<volatile%> function specifiers on "
10358 "%qD invalid in field declaration", object);
10359 break;
10360 default:
10361 gcc_unreachable();
10363 if (friendp)
10364 error ("%q+D declared as a friend", object);
10365 if (raises
10366 && !flag_noexcept_type
10367 && (TREE_CODE (object) == TYPE_DECL
10368 || (!TYPE_PTRFN_P (TREE_TYPE (object))
10369 && !TYPE_REFFN_P (TREE_TYPE (object))
10370 && !TYPE_PTRMEMFUNC_P (TREE_TYPE (object)))))
10371 error ("%q+D declared with an exception specification", object);
10374 /* DECL is a member function or static data member and is presently
10375 being defined. Check that the definition is taking place in a
10376 valid namespace. */
10378 static void
10379 check_class_member_definition_namespace (tree decl)
10381 /* These checks only apply to member functions and static data
10382 members. */
10383 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
10384 /* We check for problems with specializations in pt.cc in
10385 check_specialization_namespace, where we can issue better
10386 diagnostics. */
10387 if (processing_specialization)
10388 return;
10389 /* We check this in check_explicit_instantiation_namespace. */
10390 if (processing_explicit_instantiation)
10391 return;
10392 /* [class.mfct]
10394 A member function definition that appears outside of the
10395 class definition shall appear in a namespace scope enclosing
10396 the class definition.
10398 [class.static.data]
10400 The definition for a static data member shall appear in a
10401 namespace scope enclosing the member's class definition. */
10402 if (!is_ancestor (current_namespace, DECL_CONTEXT (decl)))
10403 permerror (input_location, "definition of %qD is not in namespace enclosing %qT",
10404 decl, DECL_CONTEXT (decl));
10407 /* Build a PARM_DECL for the "this" parameter of FN. TYPE is the
10408 METHOD_TYPE for a non-static member function; QUALS are the
10409 cv-qualifiers that apply to the function. */
10411 tree
10412 build_this_parm (tree fn, tree type, cp_cv_quals quals)
10414 tree this_type;
10415 tree qual_type;
10416 tree parm;
10417 cp_cv_quals this_quals;
10419 if (CLASS_TYPE_P (type))
10421 this_type
10422 = cp_build_qualified_type (type, quals & ~TYPE_QUAL_RESTRICT);
10423 this_type = build_pointer_type (this_type);
10425 else
10426 this_type = type_of_this_parm (type);
10427 /* The `this' parameter is implicitly `const'; it cannot be
10428 assigned to. */
10429 this_quals = (quals & TYPE_QUAL_RESTRICT) | TYPE_QUAL_CONST;
10430 qual_type = cp_build_qualified_type (this_type, this_quals);
10431 parm = build_artificial_parm (fn, this_identifier, qual_type);
10432 cp_apply_type_quals_to_decl (this_quals, parm);
10433 return parm;
10436 /* DECL is a static member function. Complain if it was declared
10437 with function-cv-quals. */
10439 static void
10440 check_static_quals (tree decl, cp_cv_quals quals)
10442 if (quals != TYPE_UNQUALIFIED)
10443 error ("static member function %q#D declared with type qualifiers",
10444 decl);
10447 // Check that FN takes no arguments and returns bool.
10448 static void
10449 check_concept_fn (tree fn)
10451 // A constraint is nullary.
10452 if (DECL_ARGUMENTS (fn))
10453 error_at (DECL_SOURCE_LOCATION (fn),
10454 "concept %q#D declared with function parameters", fn);
10456 // The declared return type of the concept shall be bool, and
10457 // it shall not be deduced from it definition.
10458 tree type = TREE_TYPE (TREE_TYPE (fn));
10459 if (is_auto (type))
10460 error_at (DECL_SOURCE_LOCATION (fn),
10461 "concept %q#D declared with a deduced return type", fn);
10462 else if (type != boolean_type_node)
10463 error_at (DECL_SOURCE_LOCATION (fn),
10464 "concept %q#D with non-%<bool%> return type %qT", fn, type);
10467 /* Helper function. Replace the temporary this parameter injected
10468 during cp_finish_omp_declare_simd with the real this parameter. */
10470 static tree
10471 declare_simd_adjust_this (tree *tp, int *walk_subtrees, void *data)
10473 tree this_parm = (tree) data;
10474 if (TREE_CODE (*tp) == PARM_DECL
10475 && DECL_NAME (*tp) == this_identifier
10476 && *tp != this_parm)
10477 *tp = this_parm;
10478 else if (TYPE_P (*tp))
10479 *walk_subtrees = 0;
10480 return NULL_TREE;
10483 /* CTYPE is class type, or null if non-class.
10484 TYPE is type this FUNCTION_DECL should have, either FUNCTION_TYPE
10485 or METHOD_TYPE.
10486 DECLARATOR is the function's name.
10487 PARMS is a chain of PARM_DECLs for the function.
10488 VIRTUALP is truthvalue of whether the function is virtual or not.
10489 FLAGS are to be passed through to `grokclassfn'.
10490 QUALS are qualifiers indicating whether the function is `const'
10491 or `volatile'.
10492 RAISES is a list of exceptions that this function can raise.
10493 CHECK is 1 if we must find this method in CTYPE, 0 if we should
10494 not look, and -1 if we should not call `grokclassfn' at all.
10496 SFK is the kind of special function (if any) for the new function.
10498 Returns `NULL_TREE' if something goes wrong, after issuing
10499 applicable error messages. */
10501 static tree
10502 grokfndecl (tree ctype,
10503 tree type,
10504 tree declarator,
10505 tree parms,
10506 tree orig_declarator,
10507 const cp_decl_specifier_seq *declspecs,
10508 tree decl_reqs,
10509 int virtualp,
10510 enum overload_flags flags,
10511 cp_cv_quals quals,
10512 cp_ref_qualifier rqual,
10513 tree raises,
10514 int check,
10515 int friendp,
10516 int publicp,
10517 int inlinep,
10518 bool deletedp,
10519 bool xobj_func_p,
10520 special_function_kind sfk,
10521 bool funcdef_flag,
10522 bool late_return_type_p,
10523 int template_count,
10524 tree in_namespace,
10525 tree* attrlist,
10526 location_t location)
10528 tree decl;
10529 tree t;
10531 if (location == UNKNOWN_LOCATION)
10532 location = input_location;
10534 /* Was the concept specifier present? */
10535 bool concept_p = inlinep & 4;
10537 /* Concept declarations must have a corresponding definition. */
10538 if (concept_p && !funcdef_flag)
10540 error_at (location, "concept %qD has no definition", declarator);
10541 return NULL_TREE;
10544 type = build_cp_fntype_variant (type, rqual, raises, late_return_type_p);
10546 decl = build_lang_decl_loc (location, FUNCTION_DECL, declarator, type);
10548 /* Set the constraints on the declaration. */
10549 if (flag_concepts)
10551 tree tmpl_reqs = NULL_TREE;
10552 tree ctx = friendp ? current_class_type : ctype;
10553 bool block_local = TREE_CODE (current_scope ()) == FUNCTION_DECL;
10554 bool memtmpl = (!block_local
10555 && (current_template_depth
10556 > template_class_depth (ctx)));
10557 if (memtmpl)
10559 if (!current_template_parms)
10560 /* If there are no template parameters, something must have
10561 gone wrong. */
10562 gcc_assert (seen_error ());
10563 else
10564 tmpl_reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
10566 tree ci = build_constraints (tmpl_reqs, decl_reqs);
10567 if (concept_p && ci)
10569 error_at (location, "a function concept cannot be constrained");
10570 ci = NULL_TREE;
10572 /* C++20 CA378: Remove non-templated constrained functions. */
10573 /* [temp.friend]/9 A non-template friend declaration with a
10574 requires-clause shall be a definition. A friend function template with
10575 a constraint that depends on a template parameter from an enclosing
10576 template shall be a definition. */
10577 if (ci
10578 && (block_local
10579 || (!flag_concepts_ts
10580 && (!processing_template_decl
10581 || (friendp && !memtmpl && !funcdef_flag)))))
10583 if (!friendp || !processing_template_decl)
10584 error_at (location, "constraints on a non-templated function");
10585 else
10586 error_at (location, "constrained non-template friend declaration"
10587 " must be a definition");
10588 ci = NULL_TREE;
10590 set_constraints (decl, ci);
10591 if (ci && friendp && memtmpl && !funcdef_flag
10592 && uses_outer_template_parms_in_constraints (decl, ctx))
10593 error_at (location, "friend function template with constraints that "
10594 "depend on outer template parameters must be a definition");
10597 if (TREE_CODE (type) == METHOD_TYPE)
10599 tree parm = build_this_parm (decl, type, quals);
10600 DECL_CHAIN (parm) = parms;
10601 parms = parm;
10603 /* Allocate space to hold the vptr bit if needed. */
10604 SET_DECL_ALIGN (decl, MINIMUM_METHOD_BOUNDARY);
10607 DECL_ARGUMENTS (decl) = parms;
10608 for (t = parms; t; t = DECL_CHAIN (t))
10609 DECL_CONTEXT (t) = decl;
10611 /* Propagate volatile out from type to decl. */
10612 if (TYPE_VOLATILE (type))
10613 TREE_THIS_VOLATILE (decl) = 1;
10615 /* Setup decl according to sfk. */
10616 switch (sfk)
10618 case sfk_constructor:
10619 case sfk_copy_constructor:
10620 case sfk_move_constructor:
10621 DECL_CXX_CONSTRUCTOR_P (decl) = 1;
10622 DECL_NAME (decl) = ctor_identifier;
10623 break;
10624 case sfk_destructor:
10625 DECL_CXX_DESTRUCTOR_P (decl) = 1;
10626 DECL_NAME (decl) = dtor_identifier;
10627 break;
10628 case sfk_deduction_guide:
10629 /* Give deduction guides a definition even though they don't really
10630 have one: the restriction that you can't repeat a deduction guide
10631 makes them more like a definition anyway. */
10632 DECL_INITIAL (decl) = void_node;
10633 break;
10634 default:
10635 break;
10638 if (friendp && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)
10640 if (funcdef_flag)
10641 error_at (location,
10642 "defining explicit specialization %qD in friend declaration",
10643 orig_declarator);
10644 else
10646 tree fns = TREE_OPERAND (orig_declarator, 0);
10647 tree args = TREE_OPERAND (orig_declarator, 1);
10649 if (PROCESSING_REAL_TEMPLATE_DECL_P ())
10651 /* Something like `template <class T> friend void f<T>()'. */
10652 error_at (location,
10653 "invalid use of template-id %qD in declaration "
10654 "of primary template",
10655 orig_declarator);
10656 return NULL_TREE;
10659 /* A friend declaration of the form friend void f<>(). Record
10660 the information in the TEMPLATE_ID_EXPR. */
10661 SET_DECL_IMPLICIT_INSTANTIATION (decl);
10663 gcc_assert (identifier_p (fns) || OVL_P (fns));
10664 DECL_TEMPLATE_INFO (decl) = build_template_info (fns, args);
10666 for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
10667 if (TREE_PURPOSE (t)
10668 && TREE_CODE (TREE_PURPOSE (t)) == DEFERRED_PARSE)
10670 error_at (defparse_location (TREE_PURPOSE (t)),
10671 "default arguments are not allowed in declaration "
10672 "of friend template specialization %qD",
10673 decl);
10674 return NULL_TREE;
10677 if (inlinep & 1)
10679 error_at (declspecs->locations[ds_inline],
10680 "%<inline%> is not allowed in declaration of friend "
10681 "template specialization %qD",
10682 decl);
10683 return NULL_TREE;
10688 /* C++17 11.3.6/4: "If a friend declaration specifies a default argument
10689 expression, that declaration shall be a definition..." */
10690 if (friendp && !funcdef_flag)
10692 for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
10693 t && t != void_list_node; t = TREE_CHAIN (t))
10694 if (TREE_PURPOSE (t))
10696 permerror (DECL_SOURCE_LOCATION (decl),
10697 "friend declaration of %qD specifies default "
10698 "arguments and isn%'t a definition", decl);
10699 break;
10703 /* If this decl has namespace scope, set that up. */
10704 if (in_namespace)
10705 set_decl_namespace (decl, in_namespace, friendp);
10706 else if (ctype)
10707 DECL_CONTEXT (decl) = ctype;
10708 else
10709 DECL_CONTEXT (decl) = FROB_CONTEXT (current_decl_namespace ());
10711 /* `main' and builtins have implicit 'C' linkage. */
10712 if (ctype == NULL_TREE
10713 && DECL_FILE_SCOPE_P (decl)
10714 && current_lang_name == lang_name_cplusplus
10715 && (MAIN_NAME_P (declarator)
10716 || (IDENTIFIER_LENGTH (declarator) > 10
10717 && IDENTIFIER_POINTER (declarator)[0] == '_'
10718 && IDENTIFIER_POINTER (declarator)[1] == '_'
10719 && startswith (IDENTIFIER_POINTER (declarator) + 2,
10720 "builtin_"))
10721 || (targetcm.cxx_implicit_extern_c
10722 && (targetcm.cxx_implicit_extern_c
10723 (IDENTIFIER_POINTER (declarator))))))
10724 SET_DECL_LANGUAGE (decl, lang_c);
10726 DECL_STATIC_FUNCTION_P (decl)
10727 = !xobj_func_p && ctype && TREE_CODE (type) == FUNCTION_TYPE;
10728 DECL_FUNCTION_XOBJ_FLAG (decl) = xobj_func_p;
10730 if (deletedp)
10731 DECL_DELETED_FN (decl) = 1;
10733 if (ctype && funcdef_flag)
10734 check_class_member_definition_namespace (decl);
10736 if (ctype == NULL_TREE && DECL_MAIN_P (decl))
10738 if (PROCESSING_REAL_TEMPLATE_DECL_P())
10739 error_at (location, "cannot declare %<::main%> to be a template");
10740 if (inlinep & 1)
10741 error_at (declspecs->locations[ds_inline],
10742 "cannot declare %<::main%> to be inline");
10743 if (inlinep & 2)
10744 error_at (declspecs->locations[ds_constexpr],
10745 "cannot declare %<::main%> to be %qs", "constexpr");
10746 if (inlinep & 8)
10747 error_at (declspecs->locations[ds_consteval],
10748 "cannot declare %<::main%> to be %qs", "consteval");
10749 if (!publicp)
10750 error_at (location, "cannot declare %<::main%> to be static");
10751 inlinep = 0;
10752 publicp = 1;
10755 /* Members of anonymous types and local classes have no linkage; make
10756 them internal. If a typedef is made later, this will be changed. */
10757 if (ctype && (!TREE_PUBLIC (TYPE_MAIN_DECL (ctype))
10758 || decl_function_context (TYPE_MAIN_DECL (ctype))))
10759 publicp = 0;
10761 if (publicp && cxx_dialect == cxx98)
10763 /* [basic.link]: A name with no linkage (notably, the name of a class
10764 or enumeration declared in a local scope) shall not be used to
10765 declare an entity with linkage.
10767 DR 757 relaxes this restriction for C++0x. */
10768 no_linkage_error (decl);
10771 TREE_PUBLIC (decl) = publicp;
10772 if (! publicp)
10774 DECL_INTERFACE_KNOWN (decl) = 1;
10775 DECL_NOT_REALLY_EXTERN (decl) = 1;
10778 /* If the declaration was declared inline, mark it as such. */
10779 if (inlinep)
10781 DECL_DECLARED_INLINE_P (decl) = 1;
10782 if (publicp)
10783 DECL_COMDAT (decl) = 1;
10785 if (inlinep & 2)
10786 DECL_DECLARED_CONSTEXPR_P (decl) = true;
10787 else if (inlinep & 8)
10789 DECL_DECLARED_CONSTEXPR_P (decl) = true;
10790 SET_DECL_IMMEDIATE_FUNCTION_P (decl);
10793 // If the concept declaration specifier was found, check
10794 // that the declaration satisfies the necessary requirements.
10795 if (concept_p)
10797 DECL_DECLARED_CONCEPT_P (decl) = true;
10798 check_concept_fn (decl);
10801 DECL_EXTERNAL (decl) = 1;
10802 if (TREE_CODE (type) == FUNCTION_TYPE)
10804 if (quals || rqual)
10805 TREE_TYPE (decl) = apply_memfn_quals (TREE_TYPE (decl),
10806 TYPE_UNQUALIFIED,
10807 REF_QUAL_NONE);
10808 auto_diagnostic_group d;
10809 if (quals)
10810 error (!ctype
10811 ? G_("non-member function %qD cannot have cv-qualifier")
10812 : !xobj_func_p
10813 ? G_("static member function %qD cannot have cv-qualifier")
10814 : G_("explicit object member function "
10815 "%qD cannot have cv-qualifier"),
10816 decl);
10817 if (rqual)
10818 error (!ctype
10819 ? G_("non-member function %qD cannot have ref-qualifier")
10820 : !xobj_func_p
10821 ? G_("static member function %qD cannot have ref-qualifier")
10822 : G_("explicit object member function "
10823 "%qD cannot have ref-qualifier"),
10824 decl);
10826 if (xobj_func_p && (quals || rqual))
10827 inform (DECL_SOURCE_LOCATION (DECL_ARGUMENTS (decl)),
10828 "explicit object parameter declared here");
10829 quals = TYPE_UNQUALIFIED;
10830 rqual = REF_QUAL_NONE;
10834 if (deduction_guide_p (decl))
10836 tree type = TREE_TYPE (DECL_NAME (decl));
10837 if (in_namespace == NULL_TREE
10838 && CP_DECL_CONTEXT (decl) != CP_TYPE_CONTEXT (type))
10840 error_at (location, "deduction guide %qD must be declared in the "
10841 "same scope as %qT", decl, type);
10842 inform (location_of (type), " declared here");
10843 return NULL_TREE;
10845 if (DECL_CLASS_SCOPE_P (decl)
10846 && current_access_specifier != declared_access (TYPE_NAME (type)))
10848 error_at (location, "deduction guide %qD must have the same access "
10849 "as %qT", decl, type);
10850 inform (location_of (type), " declared here");
10852 if (funcdef_flag)
10853 error_at (location,
10854 "deduction guide %qD must not have a function body", decl);
10856 else if (IDENTIFIER_ANY_OP_P (DECL_NAME (decl))
10857 && !grok_op_properties (decl, /*complain=*/true))
10858 return NULL_TREE;
10859 else if (UDLIT_OPER_P (DECL_NAME (decl)))
10861 bool long_long_unsigned_p;
10862 bool long_double_p;
10863 const char *suffix = NULL;
10864 /* [over.literal]/6: Literal operators shall not have C linkage. */
10865 if (DECL_LANGUAGE (decl) == lang_c)
10867 error_at (location, "literal operator with C linkage");
10868 maybe_show_extern_c_location ();
10869 return NULL_TREE;
10872 if (DECL_NAMESPACE_SCOPE_P (decl))
10874 if (!check_literal_operator_args (decl, &long_long_unsigned_p,
10875 &long_double_p))
10877 error_at (location, "%qD has invalid argument list", decl);
10878 return NULL_TREE;
10881 suffix = UDLIT_OP_SUFFIX (DECL_NAME (decl));
10882 if (long_long_unsigned_p)
10884 if (cpp_interpret_int_suffix (parse_in, suffix, strlen (suffix)))
10885 warning_at (location, 0, "integer suffix %qs"
10886 " shadowed by implementation", suffix);
10888 else if (long_double_p)
10890 if (cpp_interpret_float_suffix (parse_in, suffix, strlen (suffix)))
10891 warning_at (location, 0, "floating-point suffix %qs"
10892 " shadowed by implementation", suffix);
10894 /* 17.6.3.3.5 */
10895 if (suffix[0] != '_'
10896 && !current_function_decl && !(friendp && !funcdef_flag))
10897 warning_at (location, OPT_Wliteral_suffix,
10898 "literal operator suffixes not preceded by %<_%>"
10899 " are reserved for future standardization");
10901 else
10903 error_at (location, "%qD must be a non-member function", decl);
10904 return NULL_TREE;
10908 if (funcdef_flag)
10909 /* Make the init_value nonzero so pushdecl knows this is not
10910 tentative. error_mark_node is replaced later with the BLOCK. */
10911 DECL_INITIAL (decl) = error_mark_node;
10913 if (TYPE_NOTHROW_P (type) || nothrow_libfn_p (decl))
10914 TREE_NOTHROW (decl) = 1;
10916 if (flag_openmp || flag_openmp_simd)
10918 /* Adjust "omp declare simd" attributes. */
10919 tree ods = lookup_attribute ("omp declare simd", *attrlist);
10920 if (ods)
10922 tree attr;
10923 for (attr = ods; attr;
10924 attr = lookup_attribute ("omp declare simd", TREE_CHAIN (attr)))
10926 if (TREE_CODE (type) == METHOD_TYPE)
10927 walk_tree (&TREE_VALUE (attr), declare_simd_adjust_this,
10928 DECL_ARGUMENTS (decl), NULL);
10929 if (TREE_VALUE (attr) != NULL_TREE)
10931 tree cl = TREE_VALUE (TREE_VALUE (attr));
10932 cl = c_omp_declare_simd_clauses_to_numbers
10933 (DECL_ARGUMENTS (decl), cl);
10934 if (cl)
10935 TREE_VALUE (TREE_VALUE (attr)) = cl;
10936 else
10937 TREE_VALUE (attr) = NULL_TREE;
10943 /* Caller will do the rest of this. */
10944 if (check < 0)
10945 return decl;
10947 if (ctype != NULL_TREE)
10948 grokclassfn (ctype, decl, flags);
10950 /* 12.4/3 */
10951 if (cxx_dialect >= cxx11
10952 && DECL_DESTRUCTOR_P (decl)
10953 && !TYPE_BEING_DEFINED (DECL_CONTEXT (decl))
10954 && !processing_template_decl)
10955 deduce_noexcept_on_destructor (decl);
10957 set_originating_module (decl);
10959 decl = check_explicit_specialization (orig_declarator, decl,
10960 template_count,
10961 2 * funcdef_flag +
10962 4 * (friendp != 0) +
10963 8 * concept_p,
10964 *attrlist);
10965 if (decl == error_mark_node)
10966 return NULL_TREE;
10968 if (DECL_STATIC_FUNCTION_P (decl))
10969 check_static_quals (decl, quals);
10971 if (attrlist)
10973 cplus_decl_attributes (&decl, *attrlist, 0);
10974 *attrlist = NULL_TREE;
10977 if (DECL_HAS_CONTRACTS_P (decl))
10978 rebuild_postconditions (decl);
10980 /* Check main's type after attributes have been applied. */
10981 if (ctype == NULL_TREE && DECL_MAIN_P (decl))
10983 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
10984 integer_type_node))
10986 tree oldtypeargs = TYPE_ARG_TYPES (TREE_TYPE (decl));
10987 tree newtype;
10988 error_at (declspecs->locations[ds_type_spec],
10989 "%<::main%> must return %<int%>");
10990 newtype = build_function_type (integer_type_node, oldtypeargs);
10991 TREE_TYPE (decl) = newtype;
10993 if (warn_main)
10994 check_main_parameter_types (decl);
10997 if (ctype != NULL_TREE && check)
10999 tree old_decl = check_classfn (ctype, decl,
11000 (current_template_depth
11001 > template_class_depth (ctype))
11002 ? current_template_parms
11003 : NULL_TREE);
11005 if (old_decl == error_mark_node)
11006 return NULL_TREE;
11008 if (old_decl)
11010 tree ok;
11011 tree pushed_scope;
11013 if (TREE_CODE (old_decl) == TEMPLATE_DECL)
11014 /* Because grokfndecl is always supposed to return a
11015 FUNCTION_DECL, we pull out the DECL_TEMPLATE_RESULT
11016 here. We depend on our callers to figure out that its
11017 really a template that's being returned. */
11018 old_decl = DECL_TEMPLATE_RESULT (old_decl);
11020 if (DECL_STATIC_FUNCTION_P (old_decl)
11021 && TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
11023 /* Remove the `this' parm added by grokclassfn. */
11024 revert_static_member_fn (decl);
11025 check_static_quals (decl, quals);
11027 if (DECL_ARTIFICIAL (old_decl))
11029 error ("definition of implicitly-declared %qD", old_decl);
11030 return NULL_TREE;
11032 else if (DECL_DEFAULTED_FN (old_decl))
11034 error ("definition of explicitly-defaulted %q+D", decl);
11035 inform (DECL_SOURCE_LOCATION (old_decl),
11036 "%q#D explicitly defaulted here", old_decl);
11037 return NULL_TREE;
11040 /* Since we've smashed OLD_DECL to its
11041 DECL_TEMPLATE_RESULT, we must do the same to DECL. */
11042 if (TREE_CODE (decl) == TEMPLATE_DECL)
11043 decl = DECL_TEMPLATE_RESULT (decl);
11045 /* Attempt to merge the declarations. This can fail, in
11046 the case of some invalid specialization declarations. */
11047 pushed_scope = push_scope (ctype);
11048 ok = duplicate_decls (decl, old_decl);
11049 if (pushed_scope)
11050 pop_scope (pushed_scope);
11051 if (!ok)
11053 error ("no %q#D member function declared in class %qT",
11054 decl, ctype);
11055 return NULL_TREE;
11057 if (ok == error_mark_node)
11058 return NULL_TREE;
11059 return old_decl;
11063 if (DECL_CONSTRUCTOR_P (decl) && !grok_ctor_properties (ctype, decl))
11064 return NULL_TREE;
11066 if (ctype == NULL_TREE || check)
11067 return decl;
11069 if (virtualp)
11070 DECL_VIRTUAL_P (decl) = 1;
11072 return decl;
11075 /* decl is a FUNCTION_DECL.
11076 specifiers are the parsed virt-specifiers.
11078 Set flags to reflect the virt-specifiers.
11080 Returns decl. */
11082 static tree
11083 set_virt_specifiers (tree decl, cp_virt_specifiers specifiers)
11085 if (decl == NULL_TREE)
11086 return decl;
11087 if (specifiers & VIRT_SPEC_OVERRIDE)
11088 DECL_OVERRIDE_P (decl) = 1;
11089 if (specifiers & VIRT_SPEC_FINAL)
11090 DECL_FINAL_P (decl) = 1;
11091 return decl;
11094 /* DECL is a VAR_DECL for a static data member. Set flags to reflect
11095 the linkage that DECL will receive in the object file. */
11097 static void
11098 set_linkage_for_static_data_member (tree decl)
11100 /* A static data member always has static storage duration and
11101 external linkage. Note that static data members are forbidden in
11102 local classes -- the only situation in which a class has
11103 non-external linkage. */
11104 TREE_PUBLIC (decl) = 1;
11105 TREE_STATIC (decl) = 1;
11106 /* For non-template classes, static data members are always put
11107 out in exactly those files where they are defined, just as
11108 with ordinary namespace-scope variables. */
11109 if (!processing_template_decl)
11110 DECL_INTERFACE_KNOWN (decl) = 1;
11113 /* Create a VAR_DECL named NAME with the indicated TYPE.
11115 If SCOPE is non-NULL, it is the class type or namespace containing
11116 the variable. If SCOPE is NULL, the variable should is created in
11117 the innermost enclosing scope. */
11119 static tree
11120 grokvardecl (tree type,
11121 tree name,
11122 tree orig_declarator,
11123 const cp_decl_specifier_seq *declspecs,
11124 int initialized,
11125 int type_quals,
11126 int inlinep,
11127 bool conceptp,
11128 int template_count,
11129 tree scope,
11130 location_t location)
11132 tree decl;
11133 tree explicit_scope;
11135 gcc_assert (!name || identifier_p (name));
11137 bool constp = (type_quals & TYPE_QUAL_CONST) != 0;
11138 bool volatilep = (type_quals & TYPE_QUAL_VOLATILE) != 0;
11140 /* Compute the scope in which to place the variable, but remember
11141 whether or not that scope was explicitly specified by the user. */
11142 explicit_scope = scope;
11143 if (!scope)
11145 /* An explicit "extern" specifier indicates a namespace-scope
11146 variable. */
11147 if (declspecs->storage_class == sc_extern)
11148 scope = current_decl_namespace ();
11149 else if (!at_function_scope_p ())
11150 scope = current_scope ();
11153 if (scope
11154 && (/* If the variable is a namespace-scope variable declared in a
11155 template, we need DECL_LANG_SPECIFIC. */
11156 (TREE_CODE (scope) == NAMESPACE_DECL && processing_template_decl)
11157 /* Similarly for namespace-scope variables with language linkage
11158 other than C++. */
11159 || (TREE_CODE (scope) == NAMESPACE_DECL
11160 && current_lang_name != lang_name_cplusplus)
11161 /* Similarly for static data members. */
11162 || TYPE_P (scope)
11163 /* Similarly for explicit specializations. */
11164 || (orig_declarator
11165 && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)))
11166 decl = build_lang_decl_loc (location, VAR_DECL, name, type);
11167 else
11168 decl = build_decl (location, VAR_DECL, name, type);
11170 if (explicit_scope && TREE_CODE (explicit_scope) == NAMESPACE_DECL)
11171 set_decl_namespace (decl, explicit_scope, 0);
11172 else
11173 DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
11175 if (declspecs->storage_class == sc_extern)
11177 DECL_THIS_EXTERN (decl) = 1;
11178 DECL_EXTERNAL (decl) = !initialized;
11181 if (DECL_CLASS_SCOPE_P (decl))
11183 set_linkage_for_static_data_member (decl);
11184 /* This function is only called with out-of-class definitions. */
11185 DECL_EXTERNAL (decl) = 0;
11186 check_class_member_definition_namespace (decl);
11188 /* At top level, either `static' or no s.c. makes a definition
11189 (perhaps tentative), and absence of `static' makes it public. */
11190 else if (toplevel_bindings_p ())
11192 TREE_PUBLIC (decl) = (declspecs->storage_class != sc_static
11193 && (DECL_THIS_EXTERN (decl)
11194 || ! constp
11195 || volatilep
11196 || inlinep
11197 || module_attach_p ()));
11198 TREE_STATIC (decl) = ! DECL_EXTERNAL (decl);
11200 /* Not at top level, only `static' makes a static definition. */
11201 else
11203 TREE_STATIC (decl) = declspecs->storage_class == sc_static;
11204 TREE_PUBLIC (decl) = DECL_EXTERNAL (decl);
11207 set_originating_module (decl);
11209 if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
11211 if (DECL_EXTERNAL (decl) || TREE_STATIC (decl))
11213 CP_DECL_THREAD_LOCAL_P (decl) = true;
11214 if (!processing_template_decl)
11215 set_decl_tls_model (decl, decl_default_tls_model (decl));
11217 if (declspecs->gnu_thread_keyword_p)
11218 SET_DECL_GNU_TLS_P (decl);
11221 /* If the type of the decl has no linkage, make sure that we'll
11222 notice that in mark_used. */
11223 if (cxx_dialect > cxx98
11224 && decl_linkage (decl) != lk_none
11225 && DECL_LANG_SPECIFIC (decl) == NULL
11226 && !DECL_EXTERN_C_P (decl)
11227 && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
11228 retrofit_lang_decl (decl);
11230 if (TREE_PUBLIC (decl))
11232 /* [basic.link]: A name with no linkage (notably, the name of a class
11233 or enumeration declared in a local scope) shall not be used to
11234 declare an entity with linkage.
11236 DR 757 relaxes this restriction for C++0x. */
11237 if (cxx_dialect < cxx11)
11238 no_linkage_error (decl);
11240 else
11241 DECL_INTERFACE_KNOWN (decl) = 1;
11243 if (DECL_NAME (decl)
11244 && MAIN_NAME_P (DECL_NAME (decl))
11245 && scope == global_namespace)
11246 error_at (DECL_SOURCE_LOCATION (decl),
11247 "cannot declare %<::main%> to be a global variable");
11249 /* Check that the variable can be safely declared as a concept.
11250 Note that this also forbids explicit specializations. */
11251 if (conceptp)
11253 if (!processing_template_decl)
11255 error_at (declspecs->locations[ds_concept],
11256 "a non-template variable cannot be %<concept%>");
11257 return NULL_TREE;
11259 else if (!at_namespace_scope_p ())
11261 error_at (declspecs->locations[ds_concept],
11262 "concept must be defined at namespace scope");
11263 return NULL_TREE;
11265 else
11266 DECL_DECLARED_CONCEPT_P (decl) = true;
11267 if (!same_type_ignoring_top_level_qualifiers_p (type, boolean_type_node))
11268 error_at (declspecs->locations[ds_type_spec],
11269 "concept must have type %<bool%>");
11270 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
11272 error_at (location, "a variable concept cannot be constrained");
11273 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
11276 else if (flag_concepts
11277 && current_template_depth > template_class_depth (scope))
11279 tree ci = current_template_constraints ();
11280 set_constraints (decl, ci);
11283 // Handle explicit specializations and instantiations of variable templates.
11284 if (orig_declarator)
11285 decl = check_explicit_specialization (orig_declarator, decl,
11286 template_count, conceptp * 8);
11288 return decl != error_mark_node ? decl : NULL_TREE;
11291 /* Create and return a canonical pointer to member function type, for
11292 TYPE, which is a POINTER_TYPE to a METHOD_TYPE. */
11294 tree
11295 build_ptrmemfunc_type (tree type)
11297 tree field, fields;
11298 tree t;
11300 if (type == error_mark_node)
11301 return type;
11303 /* Make sure that we always have the unqualified pointer-to-member
11304 type first. */
11305 if (cp_cv_quals quals = cp_type_quals (type))
11307 tree unqual = build_ptrmemfunc_type (TYPE_MAIN_VARIANT (type));
11308 return cp_build_qualified_type (unqual, quals);
11311 /* If a canonical type already exists for this type, use it. We use
11312 this method instead of type_hash_canon, because it only does a
11313 simple equality check on the list of field members. */
11315 t = TYPE_PTRMEMFUNC_TYPE (type);
11316 if (t)
11317 return t;
11319 t = make_node (RECORD_TYPE);
11321 /* Let the front end know this is a pointer to member function. */
11322 TYPE_PTRMEMFUNC_FLAG (t) = 1;
11324 field = build_decl (input_location, FIELD_DECL, pfn_identifier, type);
11325 DECL_NONADDRESSABLE_P (field) = 1;
11326 fields = field;
11328 field = build_decl (input_location, FIELD_DECL, delta_identifier,
11329 delta_type_node);
11330 DECL_NONADDRESSABLE_P (field) = 1;
11331 DECL_CHAIN (field) = fields;
11332 fields = field;
11334 finish_builtin_struct (t, "__ptrmemfunc_type", fields, ptr_type_node);
11336 /* Zap out the name so that the back end will give us the debugging
11337 information for this anonymous RECORD_TYPE. */
11338 TYPE_NAME (t) = NULL_TREE;
11340 /* Cache this pointer-to-member type so that we can find it again
11341 later. */
11342 TYPE_PTRMEMFUNC_TYPE (type) = t;
11344 if (TYPE_STRUCTURAL_EQUALITY_P (type))
11345 SET_TYPE_STRUCTURAL_EQUALITY (t);
11346 else if (TYPE_CANONICAL (type) != type)
11347 TYPE_CANONICAL (t) = build_ptrmemfunc_type (TYPE_CANONICAL (type));
11349 return t;
11352 /* Create and return a pointer to data member type. */
11354 tree
11355 build_ptrmem_type (tree class_type, tree member_type)
11357 if (TREE_CODE (member_type) == METHOD_TYPE)
11359 cp_cv_quals quals = type_memfn_quals (member_type);
11360 cp_ref_qualifier rqual = type_memfn_rqual (member_type);
11361 member_type = build_memfn_type (member_type, class_type, quals, rqual);
11362 return build_ptrmemfunc_type (build_pointer_type (member_type));
11364 else
11366 gcc_assert (TREE_CODE (member_type) != FUNCTION_TYPE);
11367 return build_offset_type (class_type, member_type);
11371 /* DECL is a VAR_DECL defined in-class, whose TYPE is also given.
11372 Check to see that the definition is valid. Issue appropriate error
11373 messages. */
11375 static void
11376 check_static_variable_definition (tree decl, tree type)
11378 /* Avoid redundant diagnostics on out-of-class definitions. */
11379 if (!current_class_type || !TYPE_BEING_DEFINED (current_class_type))
11381 /* Can't check yet if we don't know the type. */
11382 else if (dependent_type_p (type))
11384 /* If DECL is declared constexpr, we'll do the appropriate checks
11385 in check_initializer. Similarly for inline static data members. */
11386 else if (DECL_P (decl)
11387 && (DECL_DECLARED_CONSTEXPR_P (decl)
11388 || DECL_VAR_DECLARED_INLINE_P (decl)))
11390 else if (cxx_dialect >= cxx11 && !INTEGRAL_OR_ENUMERATION_TYPE_P (type))
11392 if (!COMPLETE_TYPE_P (type))
11393 error_at (DECL_SOURCE_LOCATION (decl),
11394 "in-class initialization of static data member %q#D of "
11395 "incomplete type", decl);
11396 else if (literal_type_p (type))
11397 permerror (DECL_SOURCE_LOCATION (decl),
11398 "%<constexpr%> needed for in-class initialization of "
11399 "static data member %q#D of non-integral type", decl);
11400 else
11401 error_at (DECL_SOURCE_LOCATION (decl),
11402 "in-class initialization of static data member %q#D of "
11403 "non-literal type", decl);
11405 /* Motion 10 at San Diego: If a static const integral data member is
11406 initialized with an integral constant expression, the initializer
11407 may appear either in the declaration (within the class), or in
11408 the definition, but not both. If it appears in the class, the
11409 member is a member constant. The file-scope definition is always
11410 required. */
11411 else if (!ARITHMETIC_TYPE_P (type) && TREE_CODE (type) != ENUMERAL_TYPE)
11412 error_at (DECL_SOURCE_LOCATION (decl),
11413 "invalid in-class initialization of static data member "
11414 "of non-integral type %qT",
11415 type);
11416 else if (!CP_TYPE_CONST_P (type))
11417 error_at (DECL_SOURCE_LOCATION (decl),
11418 "ISO C++ forbids in-class initialization of non-const "
11419 "static member %qD",
11420 decl);
11421 else if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type))
11422 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
11423 "ISO C++ forbids initialization of member constant "
11424 "%qD of non-integral type %qT", decl, type);
11427 /* *expr_p is part of the TYPE_SIZE of a variably-sized array. If any
11428 SAVE_EXPRs in *expr_p wrap expressions with side-effects, break those
11429 expressions out into temporary variables so that walk_tree doesn't
11430 step into them (c++/15764). */
11432 static tree
11433 stabilize_save_expr_r (tree *expr_p, int *walk_subtrees, void *data)
11435 hash_set<tree> *pset = (hash_set<tree> *)data;
11436 tree expr = *expr_p;
11437 if (TREE_CODE (expr) == SAVE_EXPR)
11439 tree op = TREE_OPERAND (expr, 0);
11440 cp_walk_tree (&op, stabilize_save_expr_r, data, pset);
11441 if (TREE_SIDE_EFFECTS (op))
11442 TREE_OPERAND (expr, 0) = get_temp_regvar (TREE_TYPE (op), op);
11443 *walk_subtrees = 0;
11445 else if (!EXPR_P (expr) || !TREE_SIDE_EFFECTS (expr))
11446 *walk_subtrees = 0;
11447 return NULL;
11450 /* Entry point for the above. */
11452 static void
11453 stabilize_vla_size (tree size)
11455 hash_set<tree> pset;
11456 /* Break out any function calls into temporary variables. */
11457 cp_walk_tree (&size, stabilize_save_expr_r, &pset, &pset);
11460 /* Reduce a SIZEOF_EXPR to its value. */
11462 tree
11463 fold_sizeof_expr (tree t)
11465 tree r;
11466 if (SIZEOF_EXPR_TYPE_P (t))
11467 r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
11468 TREE_TYPE (TREE_OPERAND (t, 0)),
11469 SIZEOF_EXPR, false, false);
11470 else if (TYPE_P (TREE_OPERAND (t, 0)))
11471 r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
11472 TREE_OPERAND (t, 0), SIZEOF_EXPR,
11473 false, false);
11474 else
11475 r = cxx_sizeof_or_alignof_expr (EXPR_LOCATION (t),
11476 TREE_OPERAND (t, 0), SIZEOF_EXPR,
11477 false, false);
11478 if (r == error_mark_node)
11479 r = size_one_node;
11480 return r;
11483 /* Given the SIZE (i.e., number of elements) in an array, compute
11484 an appropriate index type for the array. If non-NULL, NAME is
11485 the name of the entity being declared. */
11487 static tree
11488 compute_array_index_type_loc (location_t name_loc, tree name, tree size,
11489 tsubst_flags_t complain)
11491 if (error_operand_p (size))
11492 return error_mark_node;
11494 /* The type of the index being computed. */
11495 tree itype;
11497 /* The original numeric size as seen in the source code before
11498 conversion to size_t. */
11499 tree origsize = size;
11501 location_t loc = cp_expr_loc_or_loc (size, name ? name_loc : input_location);
11503 if (!type_dependent_expression_p (size))
11505 origsize = size = mark_rvalue_use (size);
11507 if (cxx_dialect < cxx11 && TREE_CODE (size) == NOP_EXPR
11508 && TREE_SIDE_EFFECTS (size))
11509 /* In C++98, we mark a non-constant array bound with a magic
11510 NOP_EXPR with TREE_SIDE_EFFECTS; don't fold in that case. */;
11511 else
11513 size = build_converted_constant_expr (size_type_node, size, complain);
11514 /* Pedantically a constant expression is required here and so
11515 __builtin_is_constant_evaluated () should fold to true if it
11516 is successfully folded into a constant. */
11517 size = fold_non_dependent_expr (size, complain,
11518 /*manifestly_const_eval=*/true);
11520 if (!TREE_CONSTANT (size))
11521 size = origsize;
11524 if (error_operand_p (size))
11525 return error_mark_node;
11527 /* The array bound must be an integer type. */
11528 tree type = TREE_TYPE (size);
11529 if (!INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
11531 if (!(complain & tf_error))
11532 return error_mark_node;
11533 if (name)
11534 error_at (loc, "size of array %qD has non-integral type %qT",
11535 name, type);
11536 else
11537 error_at (loc, "size of array has non-integral type %qT", type);
11538 size = integer_one_node;
11542 /* A type is dependent if it is...an array type constructed from any
11543 dependent type or whose size is specified by a constant expression
11544 that is value-dependent. */
11545 /* We can only call value_dependent_expression_p on integral constant
11546 expressions. */
11547 if (processing_template_decl
11548 && potential_constant_expression (size)
11549 && value_dependent_expression_p (size))
11551 /* Just build the index type and mark that it requires
11552 structural equality checks. */
11553 in_template:
11554 itype = build_index_type (build_min (MINUS_EXPR, sizetype,
11555 size, size_one_node));
11556 TYPE_DEPENDENT_P (itype) = 1;
11557 TYPE_DEPENDENT_P_VALID (itype) = 1;
11558 SET_TYPE_STRUCTURAL_EQUALITY (itype);
11559 return itype;
11562 if (TREE_CODE (size) != INTEGER_CST)
11564 tree folded = cp_fully_fold (size);
11565 if (TREE_CODE (folded) == INTEGER_CST)
11567 if (name)
11568 pedwarn (loc, OPT_Wpedantic, "size of array %qD is not an "
11569 "integral constant-expression", name);
11570 else
11571 pedwarn (loc, OPT_Wpedantic,
11572 "size of array is not an integral constant-expression");
11574 if (TREE_CONSTANT (size) && !TREE_CONSTANT (folded))
11575 /* We might have lost the TREE_CONSTANT flag e.g. when we are
11576 folding a conversion from a pointer to integral type. In that
11577 case issue an error below and don't treat this as a VLA. */;
11578 else
11579 /* Use the folded result for VLAs, too; it will have resolved
11580 SIZEOF_EXPR. */
11581 size = folded;
11584 /* Normally, the array-bound will be a constant. */
11585 if (TREE_CODE (size) == INTEGER_CST)
11587 /* The size to use in diagnostics that reflects the constant
11588 size used in the source, rather than SIZE massaged above. */
11589 tree diagsize = size;
11591 /* If the original size before conversion to size_t was signed
11592 and negative, convert it to ssizetype to restore the sign. */
11593 if (!TYPE_UNSIGNED (TREE_TYPE (origsize))
11594 && TREE_CODE (size) == INTEGER_CST
11595 && tree_int_cst_sign_bit (size))
11597 diagsize = fold_convert (ssizetype, size);
11599 /* Clear the overflow bit that may have been set as a result
11600 of the conversion from the sizetype of the new size to
11601 ssizetype. */
11602 TREE_OVERFLOW (diagsize) = false;
11605 /* Verify that the array has a positive number of elements
11606 and issue the appropriate diagnostic if it doesn't. */
11607 if (!valid_array_size_p (loc, diagsize, name, (complain & tf_error)))
11609 if (!(complain & tf_error))
11610 return error_mark_node;
11611 size = integer_one_node;
11613 /* As an extension we allow zero-sized arrays. */
11614 else if (integer_zerop (size))
11616 if (!(complain & tf_error))
11617 /* We must fail if performing argument deduction (as
11618 indicated by the state of complain), so that
11619 another substitution can be found. */
11620 return error_mark_node;
11621 else if (name)
11622 pedwarn (loc, OPT_Wpedantic,
11623 "ISO C++ forbids zero-size array %qD", name);
11624 else
11625 pedwarn (loc, OPT_Wpedantic,
11626 "ISO C++ forbids zero-size array");
11629 else if (TREE_CONSTANT (size)
11630 /* We don't allow VLAs at non-function scopes, or during
11631 tentative template substitution. */
11632 || !at_function_scope_p ()
11633 || !(complain & tf_error))
11635 if (!(complain & tf_error))
11636 return error_mark_node;
11637 /* `(int) &fn' is not a valid array bound. */
11638 if (name)
11639 error_at (loc,
11640 "size of array %qD is not an integral constant-expression",
11641 name);
11642 else
11643 error_at (loc, "size of array is not an integral constant-expression");
11644 size = integer_one_node;
11646 else if (pedantic && warn_vla != 0)
11648 if (name)
11649 pedwarn (name_loc, OPT_Wvla,
11650 "ISO C++ forbids variable length array %qD", name);
11651 else
11652 pedwarn (input_location, OPT_Wvla,
11653 "ISO C++ forbids variable length array");
11655 else if (warn_vla > 0)
11657 if (name)
11658 warning_at (name_loc, OPT_Wvla,
11659 "variable length array %qD is used", name);
11660 else
11661 warning (OPT_Wvla,
11662 "variable length array is used");
11665 if (processing_template_decl && !TREE_CONSTANT (size))
11666 goto in_template;
11667 else
11669 if (!TREE_CONSTANT (size))
11671 /* A variable sized array. Arrange for the SAVE_EXPR on the inside
11672 of the MINUS_EXPR, which allows the -1 to get folded with the +1
11673 that happens when building TYPE_SIZE. */
11674 size = variable_size (size);
11675 stabilize_vla_size (size);
11678 /* Compute the index of the largest element in the array. It is
11679 one less than the number of elements in the array. We save
11680 and restore PROCESSING_TEMPLATE_DECL so that computations in
11681 cp_build_binary_op will be appropriately folded. */
11683 processing_template_decl_sentinel s;
11684 itype = cp_build_binary_op (input_location,
11685 MINUS_EXPR,
11686 cp_convert (ssizetype, size, complain),
11687 cp_convert (ssizetype, integer_one_node,
11688 complain),
11689 complain);
11690 itype = maybe_constant_value (itype, NULL_TREE, mce_true);
11693 if (!TREE_CONSTANT (itype))
11695 if (sanitize_flags_p (SANITIZE_VLA)
11696 && current_function_decl != NULL_TREE)
11698 /* We have to add 1 -- in the ubsan routine we generate
11699 LE_EXPR rather than LT_EXPR. */
11700 tree t = fold_build2 (PLUS_EXPR, TREE_TYPE (itype), itype,
11701 build_one_cst (TREE_TYPE (itype)));
11702 t = ubsan_instrument_vla (input_location, t);
11703 finish_expr_stmt (t);
11706 /* Make sure that there was no overflow when creating to a signed
11707 index type. (For example, on a 32-bit machine, an array with
11708 size 2^32 - 1 is too big.) */
11709 else if (TREE_CODE (itype) == INTEGER_CST
11710 && TREE_OVERFLOW (itype))
11712 if (!(complain & tf_error))
11713 return error_mark_node;
11714 error ("overflow in array dimension");
11715 TREE_OVERFLOW (itype) = 0;
11719 /* Create and return the appropriate index type. */
11720 itype = build_index_type (itype);
11722 /* If the index type were dependent, we would have returned early, so
11723 remember that it isn't. */
11724 TYPE_DEPENDENT_P (itype) = 0;
11725 TYPE_DEPENDENT_P_VALID (itype) = 1;
11726 return itype;
11729 tree
11730 compute_array_index_type (tree name, tree size, tsubst_flags_t complain)
11732 return compute_array_index_type_loc (input_location, name, size, complain);
11735 /* Returns the scope (if any) in which the entity declared by
11736 DECLARATOR will be located. If the entity was declared with an
11737 unqualified name, NULL_TREE is returned. */
11739 tree
11740 get_scope_of_declarator (const cp_declarator *declarator)
11742 while (declarator && declarator->kind != cdk_id)
11743 declarator = declarator->declarator;
11745 /* If the declarator-id is a SCOPE_REF, the scope in which the
11746 declaration occurs is the first operand. */
11747 if (declarator
11748 && declarator->u.id.qualifying_scope)
11749 return declarator->u.id.qualifying_scope;
11751 /* Otherwise, the declarator is not a qualified name; the entity will
11752 be declared in the current scope. */
11753 return NULL_TREE;
11756 /* Returns an ARRAY_TYPE for an array with SIZE elements of the
11757 indicated TYPE. If non-NULL, NAME is the NAME of the declaration
11758 with this type. */
11760 static tree
11761 create_array_type_for_decl (tree name, tree type, tree size, location_t loc)
11763 tree itype = NULL_TREE;
11765 /* If things have already gone awry, bail now. */
11766 if (type == error_mark_node || size == error_mark_node)
11767 return error_mark_node;
11769 /* [dcl.type.class.deduct] prohibits forming an array of placeholder
11770 for a deduced class type. */
11771 if (template_placeholder_p (type))
11773 if (name)
11774 error_at (loc, "%qD declared as array of template placeholder "
11775 "type %qT", name, type);
11776 else
11777 error ("creating array of template placeholder type %qT", type);
11778 return error_mark_node;
11781 /* If there are some types which cannot be array elements,
11782 issue an error-message and return. */
11783 switch (TREE_CODE (type))
11785 case VOID_TYPE:
11786 if (name)
11787 error_at (loc, "declaration of %qD as array of void", name);
11788 else
11789 error ("creating array of void");
11790 return error_mark_node;
11792 case FUNCTION_TYPE:
11793 if (name)
11794 error_at (loc, "declaration of %qD as array of functions", name);
11795 else
11796 error ("creating array of functions");
11797 return error_mark_node;
11799 case REFERENCE_TYPE:
11800 if (name)
11801 error_at (loc, "declaration of %qD as array of references", name);
11802 else
11803 error ("creating array of references");
11804 return error_mark_node;
11806 case METHOD_TYPE:
11807 if (name)
11808 error_at (loc, "declaration of %qD as array of function members",
11809 name);
11810 else
11811 error ("creating array of function members");
11812 return error_mark_node;
11814 default:
11815 break;
11818 if (!verify_type_context (name ? loc : input_location,
11819 TCTX_ARRAY_ELEMENT, type))
11820 return error_mark_node;
11822 /* [dcl.array]
11824 The constant expressions that specify the bounds of the arrays
11825 can be omitted only for the first member of the sequence. */
11826 if (TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type))
11828 if (name)
11829 error_at (loc, "declaration of %qD as multidimensional array must "
11830 "have bounds for all dimensions except the first",
11831 name);
11832 else
11833 error ("multidimensional array must have bounds for all "
11834 "dimensions except the first");
11836 return error_mark_node;
11839 /* Figure out the index type for the array. */
11840 if (size)
11842 itype = compute_array_index_type_loc (loc, name, size,
11843 tf_warning_or_error);
11844 if (type_uses_auto (type)
11845 && variably_modified_type_p (itype, /*fn=*/NULL_TREE))
11847 sorry_at (loc, "variable-length array of %<auto%>");
11848 return error_mark_node;
11852 return build_cplus_array_type (type, itype);
11855 /* Returns the smallest location that is not UNKNOWN_LOCATION. */
11857 static location_t
11858 min_location (location_t loca, location_t locb)
11860 if (loca == UNKNOWN_LOCATION
11861 || (locb != UNKNOWN_LOCATION
11862 && linemap_location_before_p (line_table, locb, loca)))
11863 return locb;
11864 return loca;
11867 /* Returns the smallest location != UNKNOWN_LOCATION among the
11868 three stored in LOCATIONS[ds_const], LOCATIONS[ds_volatile],
11869 and LOCATIONS[ds_restrict]. */
11871 static location_t
11872 smallest_type_quals_location (int type_quals, const location_t* locations)
11874 location_t loc = UNKNOWN_LOCATION;
11876 if (type_quals & TYPE_QUAL_CONST)
11877 loc = locations[ds_const];
11879 if (type_quals & TYPE_QUAL_VOLATILE)
11880 loc = min_location (loc, locations[ds_volatile]);
11882 if (type_quals & TYPE_QUAL_RESTRICT)
11883 loc = min_location (loc, locations[ds_restrict]);
11885 return loc;
11888 /* Returns the smallest among the latter and locations[ds_type_spec]. */
11890 static location_t
11891 smallest_type_location (int type_quals, const location_t* locations)
11893 location_t loc = smallest_type_quals_location (type_quals, locations);
11894 return min_location (loc, locations[ds_type_spec]);
11897 static location_t
11898 smallest_type_location (const cp_decl_specifier_seq *declspecs)
11900 int type_quals = get_type_quals (declspecs);
11901 return smallest_type_location (type_quals, declspecs->locations);
11904 /* Check that it's OK to declare a function with the indicated TYPE
11905 and TYPE_QUALS. SFK indicates the kind of special function (if any)
11906 that this function is. OPTYPE is the type given in a conversion
11907 operator declaration, or the class type for a constructor/destructor.
11908 Returns the actual return type of the function; that may be different
11909 than TYPE if an error occurs, or for certain special functions. */
11911 static tree
11912 check_special_function_return_type (special_function_kind sfk,
11913 tree type,
11914 tree optype,
11915 int type_quals,
11916 const location_t* locations)
11918 switch (sfk)
11920 case sfk_constructor:
11921 if (type)
11922 error_at (smallest_type_location (type_quals, locations),
11923 "return type specification for constructor invalid");
11924 else if (type_quals != TYPE_UNQUALIFIED)
11925 error_at (smallest_type_quals_location (type_quals, locations),
11926 "qualifiers are not allowed on constructor declaration");
11928 if (targetm.cxx.cdtor_returns_this ())
11929 type = build_pointer_type (optype);
11930 else
11931 type = void_type_node;
11932 break;
11934 case sfk_destructor:
11935 if (type)
11936 error_at (smallest_type_location (type_quals, locations),
11937 "return type specification for destructor invalid");
11938 else if (type_quals != TYPE_UNQUALIFIED)
11939 error_at (smallest_type_quals_location (type_quals, locations),
11940 "qualifiers are not allowed on destructor declaration");
11942 /* We can't use the proper return type here because we run into
11943 problems with ambiguous bases and covariant returns. */
11944 if (targetm.cxx.cdtor_returns_this ())
11945 type = build_pointer_type (void_type_node);
11946 else
11947 type = void_type_node;
11948 break;
11950 case sfk_conversion:
11951 if (type)
11952 error_at (smallest_type_location (type_quals, locations),
11953 "return type specified for %<operator %T%>", optype);
11954 else if (type_quals != TYPE_UNQUALIFIED)
11955 error_at (smallest_type_quals_location (type_quals, locations),
11956 "qualifiers are not allowed on declaration of "
11957 "%<operator %T%>", optype);
11959 type = optype;
11960 break;
11962 case sfk_deduction_guide:
11963 if (type)
11964 error_at (smallest_type_location (type_quals, locations),
11965 "return type specified for deduction guide");
11966 else if (type_quals != TYPE_UNQUALIFIED)
11967 error_at (smallest_type_quals_location (type_quals, locations),
11968 "qualifiers are not allowed on declaration of "
11969 "deduction guide");
11970 if (TREE_CODE (optype) == TEMPLATE_TEMPLATE_PARM)
11972 error ("template template parameter %qT in declaration of "
11973 "deduction guide", optype);
11974 type = error_mark_node;
11976 else
11977 type = make_template_placeholder (CLASSTYPE_TI_TEMPLATE (optype));
11978 for (int i = 0; i < ds_last; ++i)
11979 if (i != ds_explicit && locations[i])
11980 error_at (locations[i],
11981 "%<decl-specifier%> in declaration of deduction guide");
11982 break;
11984 default:
11985 gcc_unreachable ();
11988 return type;
11991 /* A variable or data member (whose unqualified name is IDENTIFIER)
11992 has been declared with the indicated TYPE. If the TYPE is not
11993 acceptable, issue an error message and return a type to use for
11994 error-recovery purposes. */
11996 tree
11997 check_var_type (tree identifier, tree type, location_t loc)
11999 if (VOID_TYPE_P (type))
12001 if (!identifier)
12002 error_at (loc, "unnamed variable or field declared void");
12003 else if (identifier_p (identifier))
12005 gcc_assert (!IDENTIFIER_ANY_OP_P (identifier));
12006 error_at (loc, "variable or field %qE declared void",
12007 identifier);
12009 else
12010 error_at (loc, "variable or field declared void");
12011 type = error_mark_node;
12014 return type;
12017 /* Handle declaring DECL as an inline variable. */
12019 static void
12020 mark_inline_variable (tree decl, location_t loc)
12022 bool inlinep = true;
12023 if (! toplevel_bindings_p ())
12025 error_at (loc, "%<inline%> specifier invalid for variable "
12026 "%qD declared at block scope", decl);
12027 inlinep = false;
12029 else if (cxx_dialect < cxx17)
12030 pedwarn (loc, OPT_Wc__17_extensions, "inline variables are only available "
12031 "with %<-std=c++17%> or %<-std=gnu++17%>");
12032 if (inlinep)
12034 retrofit_lang_decl (decl);
12035 SET_DECL_VAR_DECLARED_INLINE_P (decl);
12040 /* Assign a typedef-given name to a class or enumeration type declared
12041 as anonymous at first. This was split out of grokdeclarator
12042 because it is also used in libcc1. */
12044 void
12045 name_unnamed_type (tree type, tree decl)
12047 gcc_assert (TYPE_UNNAMED_P (type));
12049 /* Replace the anonymous decl with the real decl. Be careful not to
12050 rename other typedefs (such as the self-reference) of type. */
12051 tree orig = TYPE_NAME (type);
12052 for (tree t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
12053 if (TYPE_NAME (t) == orig)
12054 TYPE_NAME (t) = decl;
12056 /* If this is a typedef within a template class, the nested
12057 type is a (non-primary) template. The name for the
12058 template needs updating as well. */
12059 if (TYPE_LANG_SPECIFIC (type) && CLASSTYPE_TEMPLATE_INFO (type))
12060 DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)) = DECL_NAME (decl);
12062 /* Adjust linkage now that we aren't unnamed anymore. */
12063 reset_type_linkage (type);
12065 /* FIXME remangle member functions; member functions of a
12066 type with external linkage have external linkage. */
12068 /* Check that our job is done, and that it would fail if we
12069 attempted to do it again. */
12070 gcc_assert (!TYPE_UNNAMED_P (type));
12073 /* Check that decltype(auto) was well-formed: only plain decltype(auto)
12074 is allowed. TYPE might contain a decltype(auto). Returns true if
12075 there was a problem, false otherwise. */
12077 static bool
12078 check_decltype_auto (location_t loc, tree type)
12080 if (tree a = type_uses_auto (type))
12082 if (AUTO_IS_DECLTYPE (a))
12084 if (a != type)
12086 error_at (loc, "%qT as type rather than plain "
12087 "%<decltype(auto)%>", type);
12088 return true;
12090 else if (TYPE_QUALS (type) != TYPE_UNQUALIFIED)
12092 error_at (loc, "%<decltype(auto)%> cannot be cv-qualified");
12093 return true;
12097 return false;
12100 /* Given declspecs and a declarator (abstract or otherwise), determine
12101 the name and type of the object declared and construct a DECL node
12102 for it.
12104 DECLSPECS points to the representation of declaration-specifier
12105 sequence that precedes declarator.
12107 DECL_CONTEXT says which syntactic context this declaration is in:
12108 NORMAL for most contexts. Make a VAR_DECL or FUNCTION_DECL or TYPE_DECL.
12109 FUNCDEF for a function definition. Like NORMAL but a few different
12110 error messages in each case. Return value may be zero meaning
12111 this definition is too screwy to try to parse.
12112 MEMFUNCDEF for a function definition. Like FUNCDEF but prepares to
12113 handle member functions (which have FIELD context).
12114 Return value may be zero meaning this definition is too screwy to
12115 try to parse.
12116 PARM for a parameter declaration (either within a function prototype
12117 or before a function body). Make a PARM_DECL, or return void_type_node.
12118 TPARM for a template parameter declaration.
12119 CATCHPARM for a parameter declaration before a catch clause.
12120 TYPENAME if for a typename (in a cast or sizeof).
12121 Don't make a DECL node; just return the ..._TYPE node.
12122 FIELD for a struct or union field; make a FIELD_DECL.
12123 BITFIELD for a field with specified width.
12125 INITIALIZED is as for start_decl.
12127 ATTRLIST is a pointer to the list of attributes, which may be NULL
12128 if there are none; *ATTRLIST may be modified if attributes from inside
12129 the declarator should be applied to the declaration.
12131 When this function is called, scoping variables (such as
12132 CURRENT_CLASS_TYPE) should reflect the scope in which the
12133 declaration occurs, not the scope in which the new declaration will
12134 be placed. For example, on:
12136 void S::f() { ... }
12138 when grokdeclarator is called for `S::f', the CURRENT_CLASS_TYPE
12139 should not be `S'.
12141 Returns a DECL (if a declarator is present), a TYPE (if there is no
12142 declarator, in cases like "struct S;"), or the ERROR_MARK_NODE if an
12143 error occurs. */
12145 tree
12146 grokdeclarator (const cp_declarator *declarator,
12147 cp_decl_specifier_seq *declspecs,
12148 enum decl_context decl_context,
12149 int initialized,
12150 tree* attrlist)
12152 tree type = NULL_TREE;
12153 int longlong = 0;
12154 int explicit_intN = 0;
12155 int int_n_alt = 0;
12156 int virtualp, explicitp, friendp, inlinep, staticp;
12157 int explicit_int = 0;
12158 int explicit_char = 0;
12159 int defaulted_int = 0;
12161 tree typedef_decl = NULL_TREE;
12162 const char *name = NULL;
12163 tree typedef_type = NULL_TREE;
12164 /* True if this declarator is a function definition. */
12165 bool funcdef_flag = false;
12166 cp_declarator_kind innermost_code = cdk_error;
12167 int bitfield = 0;
12168 #if 0
12169 /* See the code below that used this. */
12170 tree decl_attr = NULL_TREE;
12171 #endif
12173 /* Keep track of what sort of function is being processed
12174 so that we can warn about default return values, or explicit
12175 return values which do not match prescribed defaults. */
12176 special_function_kind sfk = sfk_none;
12178 tree dname = NULL_TREE;
12179 tree ctor_return_type = NULL_TREE;
12180 enum overload_flags flags = NO_SPECIAL;
12181 /* cv-qualifiers that apply to the declarator, for a declaration of
12182 a member function. */
12183 cp_cv_quals memfn_quals = TYPE_UNQUALIFIED;
12184 /* virt-specifiers that apply to the declarator, for a declaration of
12185 a member function. */
12186 cp_virt_specifiers virt_specifiers = VIRT_SPEC_UNSPECIFIED;
12187 /* ref-qualifier that applies to the declarator, for a declaration of
12188 a member function. */
12189 cp_ref_qualifier rqual = REF_QUAL_NONE;
12190 /* cv-qualifiers that apply to the type specified by the DECLSPECS. */
12191 int type_quals = get_type_quals (declspecs);
12192 tree raises = NULL_TREE;
12193 int template_count = 0;
12194 tree returned_attrs = NULL_TREE;
12195 tree parms = NULL_TREE;
12196 const cp_declarator *id_declarator;
12197 /* The unqualified name of the declarator; either an
12198 IDENTIFIER_NODE, BIT_NOT_EXPR, or TEMPLATE_ID_EXPR. */
12199 tree unqualified_id;
12200 /* The class type, if any, in which this entity is located,
12201 or NULL_TREE if none. Note that this value may be different from
12202 the current class type; for example if an attempt is made to declare
12203 "A::f" inside "B", this value will be "A". */
12204 tree ctype = current_class_type;
12205 /* The NAMESPACE_DECL for the namespace in which this entity is
12206 located. If an unqualified name is used to declare the entity,
12207 this value will be NULL_TREE, even if the entity is located at
12208 namespace scope. */
12209 tree in_namespace = NULL_TREE;
12210 cp_storage_class storage_class;
12211 bool unsigned_p, signed_p, short_p, long_p, thread_p;
12212 bool type_was_error_mark_node = false;
12213 bool parameter_pack_p = declarator ? declarator->parameter_pack_p : false;
12214 bool template_type_arg = false;
12215 bool template_parm_flag = false;
12216 bool typedef_p = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
12217 bool constexpr_p = decl_spec_seq_has_spec_p (declspecs, ds_constexpr);
12218 bool constinit_p = decl_spec_seq_has_spec_p (declspecs, ds_constinit);
12219 bool consteval_p = decl_spec_seq_has_spec_p (declspecs, ds_consteval);
12220 bool late_return_type_p = false;
12221 bool array_parameter_p = false;
12222 tree reqs = NULL_TREE;
12224 signed_p = decl_spec_seq_has_spec_p (declspecs, ds_signed);
12225 unsigned_p = decl_spec_seq_has_spec_p (declspecs, ds_unsigned);
12226 short_p = decl_spec_seq_has_spec_p (declspecs, ds_short);
12227 long_p = decl_spec_seq_has_spec_p (declspecs, ds_long);
12228 longlong = decl_spec_seq_has_spec_p (declspecs, ds_long_long);
12229 explicit_intN = declspecs->explicit_intN_p;
12230 int_n_alt = declspecs->int_n_alt;
12231 thread_p = decl_spec_seq_has_spec_p (declspecs, ds_thread);
12233 // Was concept_p specified? Note that ds_concept
12234 // implies ds_constexpr!
12235 bool concept_p = decl_spec_seq_has_spec_p (declspecs, ds_concept);
12236 if (concept_p)
12237 constexpr_p = true;
12239 if (decl_context == FUNCDEF)
12240 funcdef_flag = true, decl_context = NORMAL;
12241 else if (decl_context == MEMFUNCDEF)
12242 funcdef_flag = true, decl_context = FIELD;
12243 else if (decl_context == BITFIELD)
12244 bitfield = 1, decl_context = FIELD;
12245 else if (decl_context == TEMPLATE_TYPE_ARG)
12246 template_type_arg = true, decl_context = TYPENAME;
12247 else if (decl_context == TPARM)
12248 template_parm_flag = true, decl_context = PARM;
12250 if (initialized == SD_DEFAULTED || initialized == SD_DELETED)
12251 funcdef_flag = true;
12253 location_t typespec_loc = loc_or_input_loc (smallest_type_location
12254 (type_quals,
12255 declspecs->locations));
12256 location_t id_loc;
12257 location_t init_loc;
12258 if (declarator)
12260 id_loc = loc_or_input_loc (declarator->id_loc);
12261 init_loc = loc_or_input_loc (declarator->init_loc);
12263 else
12264 init_loc = id_loc = input_location;
12266 /* Look inside a declarator for the name being declared
12267 and get it as a string, for an error message. */
12268 for (id_declarator = declarator;
12269 id_declarator;
12270 id_declarator = id_declarator->declarator)
12272 if (id_declarator->kind != cdk_id)
12273 innermost_code = id_declarator->kind;
12275 switch (id_declarator->kind)
12277 case cdk_function:
12278 if (id_declarator->declarator
12279 && id_declarator->declarator->kind == cdk_id)
12281 sfk = id_declarator->declarator->u.id.sfk;
12282 if (sfk == sfk_destructor)
12283 flags = DTOR_FLAG;
12285 break;
12287 case cdk_id:
12289 tree qualifying_scope = id_declarator->u.id.qualifying_scope;
12290 tree decl = id_declarator->u.id.unqualified_name;
12291 if (!decl)
12292 break;
12293 if (qualifying_scope)
12295 if (check_for_bare_parameter_packs (qualifying_scope,
12296 id_declarator->id_loc))
12297 return error_mark_node;
12298 if (at_function_scope_p ())
12300 /* [dcl.meaning]
12302 A declarator-id shall not be qualified except
12303 for ...
12305 None of the cases are permitted in block
12306 scope. */
12307 if (qualifying_scope == global_namespace)
12308 error ("invalid use of qualified-name %<::%D%>",
12309 decl);
12310 else if (TYPE_P (qualifying_scope))
12311 error ("invalid use of qualified-name %<%T::%D%>",
12312 qualifying_scope, decl);
12313 else
12314 error ("invalid use of qualified-name %<%D::%D%>",
12315 qualifying_scope, decl);
12316 return error_mark_node;
12318 else if (TYPE_P (qualifying_scope))
12320 ctype = qualifying_scope;
12321 if (!MAYBE_CLASS_TYPE_P (ctype))
12323 error_at (id_declarator->id_loc,
12324 "%q#T is not a class or namespace", ctype);
12325 ctype = NULL_TREE;
12327 else if (innermost_code != cdk_function
12328 && current_class_type
12329 && !uniquely_derived_from_p (ctype,
12330 current_class_type))
12332 error_at (id_declarator->id_loc,
12333 "invalid use of qualified-name %<%T::%D%>",
12334 qualifying_scope, decl);
12335 return error_mark_node;
12338 else if (TREE_CODE (qualifying_scope) == NAMESPACE_DECL)
12339 in_namespace = qualifying_scope;
12341 switch (TREE_CODE (decl))
12343 case BIT_NOT_EXPR:
12345 if (innermost_code != cdk_function)
12347 error_at (EXPR_LOCATION (decl),
12348 "declaration of %qE as non-function", decl);
12349 return error_mark_node;
12351 else if (!qualifying_scope
12352 && !(current_class_type && at_class_scope_p ()))
12354 error_at (EXPR_LOCATION (decl),
12355 "declaration of %qE as non-member", decl);
12356 return error_mark_node;
12359 tree type = TREE_OPERAND (decl, 0);
12360 if (TYPE_P (type))
12361 type = constructor_name (type);
12362 name = identifier_to_locale (IDENTIFIER_POINTER (type));
12363 dname = decl;
12365 break;
12367 case TEMPLATE_ID_EXPR:
12369 tree fns = TREE_OPERAND (decl, 0);
12371 dname = fns;
12372 if (!identifier_p (dname))
12373 dname = OVL_NAME (dname);
12375 /* Fall through. */
12377 case IDENTIFIER_NODE:
12378 if (identifier_p (decl))
12379 dname = decl;
12381 if (IDENTIFIER_KEYWORD_P (dname))
12383 error ("declarator-id missing; using reserved word %qD",
12384 dname);
12385 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
12387 else if (!IDENTIFIER_CONV_OP_P (dname))
12388 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
12389 else
12391 gcc_assert (flags == NO_SPECIAL);
12392 flags = TYPENAME_FLAG;
12393 sfk = sfk_conversion;
12394 tree glob = get_global_binding (dname);
12395 if (glob && TREE_CODE (glob) == TYPE_DECL)
12396 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
12397 else
12398 name = "<invalid operator>";
12400 break;
12402 default:
12403 gcc_unreachable ();
12405 break;
12408 case cdk_array:
12409 case cdk_pointer:
12410 case cdk_reference:
12411 case cdk_ptrmem:
12412 break;
12414 case cdk_decomp:
12415 name = "structured binding";
12416 break;
12418 case cdk_error:
12419 return error_mark_node;
12421 default:
12422 gcc_unreachable ();
12424 if (id_declarator->kind == cdk_id)
12425 break;
12428 /* [dcl.fct.edf]
12430 The declarator in a function-definition shall have the form
12431 D1 ( parameter-declaration-clause) ... */
12432 if (funcdef_flag && innermost_code != cdk_function)
12434 error_at (id_loc, "function definition does not declare parameters");
12435 return error_mark_node;
12438 if (flags == TYPENAME_FLAG
12439 && innermost_code != cdk_function
12440 && ! (ctype && !declspecs->any_specifiers_p))
12442 error_at (id_loc, "declaration of %qD as non-function", dname);
12443 return error_mark_node;
12446 if (dname && identifier_p (dname))
12448 if (UDLIT_OPER_P (dname)
12449 && innermost_code != cdk_function)
12451 error_at (id_loc, "declaration of %qD as non-function", dname);
12452 return error_mark_node;
12455 if (IDENTIFIER_ANY_OP_P (dname))
12457 if (typedef_p)
12459 error_at (id_loc, "declaration of %qD as %<typedef%>", dname);
12460 return error_mark_node;
12462 else if (decl_context == PARM || decl_context == CATCHPARM)
12464 error_at (id_loc, "declaration of %qD as parameter", dname);
12465 return error_mark_node;
12470 /* Anything declared one level down from the top level
12471 must be one of the parameters of a function
12472 (because the body is at least two levels down). */
12474 /* This heuristic cannot be applied to C++ nodes! Fixed, however,
12475 by not allowing C++ class definitions to specify their parameters
12476 with xdecls (must be spec.d in the parmlist).
12478 Since we now wait to push a class scope until we are sure that
12479 we are in a legitimate method context, we must set oldcname
12480 explicitly (since current_class_name is not yet alive).
12482 We also want to avoid calling this a PARM if it is in a namespace. */
12484 if (decl_context == NORMAL && !toplevel_bindings_p ())
12486 cp_binding_level *b = current_binding_level;
12487 current_binding_level = b->level_chain;
12488 if (current_binding_level != 0 && toplevel_bindings_p ())
12489 decl_context = PARM;
12490 current_binding_level = b;
12493 if (name == NULL)
12494 name = decl_context == PARM ? "parameter" : "type name";
12496 if (consteval_p && constexpr_p)
12498 error_at (declspecs->locations[ds_consteval],
12499 "both %qs and %qs specified", "constexpr", "consteval");
12500 return error_mark_node;
12503 if (concept_p && typedef_p)
12505 error_at (declspecs->locations[ds_concept],
12506 "%qs cannot appear in a typedef declaration", "concept");
12507 return error_mark_node;
12510 if (constexpr_p && typedef_p)
12512 error_at (declspecs->locations[ds_constexpr],
12513 "%qs cannot appear in a typedef declaration", "constexpr");
12514 return error_mark_node;
12517 if (consteval_p && typedef_p)
12519 error_at (declspecs->locations[ds_consteval],
12520 "%qs cannot appear in a typedef declaration", "consteval");
12521 return error_mark_node;
12524 if (constinit_p && typedef_p)
12526 error_at (declspecs->locations[ds_constinit],
12527 "%qs cannot appear in a typedef declaration", "constinit");
12528 return error_mark_node;
12531 /* [dcl.spec]/2 "At most one of the constexpr, consteval, and constinit
12532 keywords shall appear in a decl-specifier-seq." */
12533 if (constinit_p && constexpr_p)
12535 gcc_rich_location richloc (declspecs->locations[ds_constinit]);
12536 richloc.add_range (declspecs->locations[ds_constexpr]);
12537 error_at (&richloc,
12538 "can use at most one of the %<constinit%> and %<constexpr%> "
12539 "specifiers");
12540 return error_mark_node;
12543 /* If there were multiple types specified in the decl-specifier-seq,
12544 issue an error message. */
12545 if (declspecs->multiple_types_p)
12547 error_at (typespec_loc,
12548 "two or more data types in declaration of %qs", name);
12549 return error_mark_node;
12552 if (declspecs->conflicting_specifiers_p)
12553 return error_mark_node;
12555 /* Extract the basic type from the decl-specifier-seq. */
12556 type = declspecs->type;
12557 if (type == error_mark_node)
12559 type = NULL_TREE;
12560 type_was_error_mark_node = true;
12563 /* Ignore erroneous attributes. */
12564 if (attrlist && *attrlist == error_mark_node)
12565 *attrlist = NULL_TREE;
12567 /* An object declared as __attribute__((unavailable)) suppresses
12568 any reports of being declared with unavailable or deprecated
12569 items. An object declared as __attribute__((deprecated))
12570 suppresses warnings of uses of other deprecated items. */
12571 auto ds = make_temp_override (deprecated_state);
12572 if (attrlist && lookup_attribute ("unavailable", *attrlist))
12573 deprecated_state = UNAVAILABLE_DEPRECATED_SUPPRESS;
12574 else if (attrlist && lookup_attribute ("deprecated", *attrlist))
12575 deprecated_state = DEPRECATED_SUPPRESS;
12577 cp_handle_deprecated_or_unavailable (type);
12578 if (type && TREE_CODE (type) == TYPE_DECL)
12580 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (type));
12581 typedef_decl = type;
12582 type = TREE_TYPE (typedef_decl);
12583 if (DECL_ARTIFICIAL (typedef_decl))
12584 cp_handle_deprecated_or_unavailable (type);
12586 /* No type at all: default to `int', and set DEFAULTED_INT
12587 because it was not a user-defined typedef. */
12588 if (type == NULL_TREE)
12590 if (signed_p || unsigned_p || long_p || short_p)
12592 /* These imply 'int'. */
12593 type = integer_type_node;
12594 defaulted_int = 1;
12596 /* If we just have "complex", it is equivalent to "complex double". */
12597 else if (!longlong && !explicit_intN
12598 && decl_spec_seq_has_spec_p (declspecs, ds_complex))
12600 type = double_type_node;
12601 pedwarn (declspecs->locations[ds_complex], OPT_Wpedantic,
12602 "ISO C++ does not support plain %<complex%> meaning "
12603 "%<double complex%>");
12606 /* Gather flags. */
12607 explicit_int = declspecs->explicit_int_p;
12608 explicit_char = declspecs->explicit_char_p;
12610 #if 0
12611 /* See the code below that used this. */
12612 if (typedef_decl)
12613 decl_attr = DECL_ATTRIBUTES (typedef_decl);
12614 #endif
12615 typedef_type = type;
12617 if (sfk == sfk_conversion || sfk == sfk_deduction_guide)
12618 ctor_return_type = TREE_TYPE (dname);
12619 else
12620 ctor_return_type = ctype;
12622 if (sfk != sfk_none)
12624 type = check_special_function_return_type (sfk, type,
12625 ctor_return_type,
12626 type_quals,
12627 declspecs->locations);
12628 type_quals = TYPE_UNQUALIFIED;
12630 else if (type == NULL_TREE)
12632 int is_main;
12634 explicit_int = -1;
12636 /* We handle `main' specially here, because 'main () { }' is so
12637 common. With no options, it is allowed. With -Wreturn-type,
12638 it is a warning. It is only an error with -pedantic-errors. */
12639 is_main = (funcdef_flag
12640 && dname && identifier_p (dname)
12641 && MAIN_NAME_P (dname)
12642 && ctype == NULL_TREE
12643 && in_namespace == NULL_TREE
12644 && current_namespace == global_namespace);
12646 if (type_was_error_mark_node)
12647 /* We've already issued an error, don't complain more. */;
12648 else if (in_system_header_at (id_loc) || flag_ms_extensions)
12649 /* Allow it, sigh. */;
12650 else if (! is_main)
12651 permerror (id_loc, "ISO C++ forbids declaration of %qs with no type",
12652 name);
12653 else if (pedantic)
12654 pedwarn (id_loc, OPT_Wpedantic,
12655 "ISO C++ forbids declaration of %qs with no type", name);
12656 else
12657 warning_at (id_loc, OPT_Wreturn_type,
12658 "ISO C++ forbids declaration of %qs with no type", name);
12660 if (type_was_error_mark_node && template_parm_flag)
12661 /* FIXME we should be able to propagate the error_mark_node as is
12662 for other contexts too. */
12663 type = error_mark_node;
12664 else
12665 type = integer_type_node;
12668 ctype = NULL_TREE;
12670 if (explicit_intN)
12672 if (! int_n_enabled_p[declspecs->int_n_idx])
12674 error_at (declspecs->locations[ds_type_spec],
12675 "%<__int%d%> is not supported by this target",
12676 int_n_data[declspecs->int_n_idx].bitsize);
12677 explicit_intN = false;
12679 /* Don't pedwarn if the alternate "__intN__" form has been used instead
12680 of "__intN". */
12681 else if (!int_n_alt && pedantic)
12682 pedwarn (declspecs->locations[ds_type_spec], OPT_Wpedantic,
12683 "ISO C++ does not support %<__int%d%> for %qs",
12684 int_n_data[declspecs->int_n_idx].bitsize, name);
12687 /* Now process the modifiers that were specified
12688 and check for invalid combinations. */
12690 /* Long double is a special combination. */
12691 if (long_p && !longlong && TYPE_MAIN_VARIANT (type) == double_type_node)
12693 long_p = false;
12694 type = cp_build_qualified_type (long_double_type_node,
12695 cp_type_quals (type));
12698 /* Check all other uses of type modifiers. */
12700 if (unsigned_p || signed_p || long_p || short_p)
12702 location_t loc;
12703 const char *key;
12704 if (unsigned_p)
12706 key = "unsigned";
12707 loc = declspecs->locations[ds_unsigned];
12709 else if (signed_p)
12711 key = "signed";
12712 loc = declspecs->locations[ds_signed];
12714 else if (longlong)
12716 key = "long long";
12717 loc = declspecs->locations[ds_long_long];
12719 else if (long_p)
12721 key = "long";
12722 loc = declspecs->locations[ds_long];
12724 else /* if (short_p) */
12726 key = "short";
12727 loc = declspecs->locations[ds_short];
12730 int ok = 0;
12732 if (signed_p && unsigned_p)
12734 gcc_rich_location richloc (declspecs->locations[ds_signed]);
12735 richloc.add_range (declspecs->locations[ds_unsigned]);
12736 error_at (&richloc,
12737 "%<signed%> and %<unsigned%> specified together");
12739 else if (long_p && short_p)
12741 gcc_rich_location richloc (declspecs->locations[ds_long]);
12742 richloc.add_range (declspecs->locations[ds_short]);
12743 error_at (&richloc, "%<long%> and %<short%> specified together");
12745 else if (TREE_CODE (type) != INTEGER_TYPE
12746 || type == char8_type_node
12747 || type == char16_type_node
12748 || type == char32_type_node
12749 || ((long_p || short_p)
12750 && (explicit_char || explicit_intN)))
12751 error_at (loc, "%qs specified with %qT", key, type);
12752 else if (!explicit_int && !defaulted_int
12753 && !explicit_char && !explicit_intN)
12755 if (typedef_decl)
12757 pedwarn (loc, OPT_Wpedantic,
12758 "%qs specified with typedef-name %qD",
12759 key, typedef_decl);
12760 ok = !flag_pedantic_errors;
12761 /* PR108099: __int128_t comes from c_common_nodes_and_builtins,
12762 and is not built as a typedef. */
12763 if (is_typedef_decl (typedef_decl))
12764 type = DECL_ORIGINAL_TYPE (typedef_decl);
12766 else if (declspecs->decltype_p)
12767 error_at (loc, "%qs specified with %<decltype%>", key);
12768 else
12769 error_at (loc, "%qs specified with %<typeof%>", key);
12771 else
12772 ok = 1;
12774 /* Discard the type modifiers if they are invalid. */
12775 if (! ok)
12777 unsigned_p = false;
12778 signed_p = false;
12779 long_p = false;
12780 short_p = false;
12781 longlong = 0;
12785 /* Decide whether an integer type is signed or not.
12786 Optionally treat bitfields as signed by default. */
12787 if (unsigned_p
12788 /* [class.bit]
12790 It is implementation-defined whether a plain (neither
12791 explicitly signed or unsigned) char, short, int, or long
12792 bit-field is signed or unsigned.
12794 Naturally, we extend this to long long as well. Note that
12795 this does not include wchar_t. */
12796 || (bitfield && !flag_signed_bitfields
12797 && !signed_p
12798 /* A typedef for plain `int' without `signed' can be
12799 controlled just like plain `int', but a typedef for
12800 `signed int' cannot be so controlled. */
12801 && !(typedef_decl
12802 && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl))
12803 && TREE_CODE (type) == INTEGER_TYPE
12804 && !same_type_p (TYPE_MAIN_VARIANT (type), wchar_type_node)))
12806 if (explicit_intN)
12807 type = int_n_trees[declspecs->int_n_idx].unsigned_type;
12808 else if (longlong)
12809 type = long_long_unsigned_type_node;
12810 else if (long_p)
12811 type = long_unsigned_type_node;
12812 else if (short_p)
12813 type = short_unsigned_type_node;
12814 else if (type == char_type_node)
12815 type = unsigned_char_type_node;
12816 else if (typedef_decl)
12817 type = c_common_unsigned_type (type);
12818 else
12819 type = unsigned_type_node;
12821 else if (signed_p && type == char_type_node)
12822 type = signed_char_type_node;
12823 else if (explicit_intN)
12824 type = int_n_trees[declspecs->int_n_idx].signed_type;
12825 else if (longlong)
12826 type = long_long_integer_type_node;
12827 else if (long_p)
12828 type = long_integer_type_node;
12829 else if (short_p)
12830 type = short_integer_type_node;
12831 else if (signed_p && typedef_decl)
12832 type = c_common_signed_type (type);
12834 if (decl_spec_seq_has_spec_p (declspecs, ds_complex))
12836 if (TREE_CODE (type) != INTEGER_TYPE && TREE_CODE (type) != REAL_TYPE)
12837 error_at (declspecs->locations[ds_complex],
12838 "complex invalid for %qs", name);
12839 /* If a modifier is specified, the resulting complex is the complex
12840 form of TYPE. E.g, "complex short" is "complex short int". */
12841 else if (type == integer_type_node)
12842 type = complex_integer_type_node;
12843 else if (type == float_type_node)
12844 type = complex_float_type_node;
12845 else if (type == double_type_node)
12846 type = complex_double_type_node;
12847 else if (type == long_double_type_node)
12848 type = complex_long_double_type_node;
12849 else
12850 type = build_complex_type (type);
12853 /* If we're using the injected-class-name to form a compound type or a
12854 declaration, replace it with the underlying class so we don't get
12855 redundant typedefs in the debug output. But if we are returning the
12856 type unchanged, leave it alone so that it's available to
12857 maybe_get_template_decl_from_type_decl. */
12858 if (CLASS_TYPE_P (type)
12859 && DECL_SELF_REFERENCE_P (TYPE_NAME (type))
12860 && type == TREE_TYPE (TYPE_NAME (type))
12861 && (declarator || type_quals))
12862 type = DECL_ORIGINAL_TYPE (TYPE_NAME (type));
12864 type_quals |= cp_type_quals (type);
12865 type = cp_build_qualified_type
12866 (type, type_quals, ((((typedef_decl && !DECL_ARTIFICIAL (typedef_decl))
12867 || declspecs->decltype_p)
12868 ? tf_ignore_bad_quals : 0) | tf_warning_or_error));
12869 /* We might have ignored or rejected some of the qualifiers. */
12870 type_quals = cp_type_quals (type);
12872 if (cxx_dialect >= cxx17 && type && is_auto (type)
12873 && innermost_code != cdk_function
12874 /* Placeholder in parm gets a better error below. */
12875 && !(decl_context == PARM || decl_context == CATCHPARM)
12876 && id_declarator && declarator != id_declarator)
12877 if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (type))
12879 auto_diagnostic_group g;
12880 gcc_rich_location richloc (typespec_loc);
12881 richloc.add_fixit_insert_after ("<>");
12882 error_at (&richloc, "missing template argument list after %qE; "
12883 "for deduction, template placeholder must be followed "
12884 "by a simple declarator-id", tmpl);
12885 inform (DECL_SOURCE_LOCATION (tmpl), "%qD declared here", tmpl);
12886 type = error_mark_node;
12889 staticp = 0;
12890 inlinep = decl_spec_seq_has_spec_p (declspecs, ds_inline);
12891 virtualp = decl_spec_seq_has_spec_p (declspecs, ds_virtual);
12892 explicitp = decl_spec_seq_has_spec_p (declspecs, ds_explicit);
12894 storage_class = declspecs->storage_class;
12895 if (storage_class == sc_static)
12896 staticp = 1 + (decl_context == FIELD);
12897 else if (decl_context == FIELD && sfk == sfk_deduction_guide)
12898 /* Treat class-scope deduction guides as static member functions
12899 so that they get a FUNCTION_TYPE instead of a METHOD_TYPE. */
12900 staticp = 2;
12902 if (virtualp)
12904 if (staticp == 2)
12906 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
12907 richloc.add_range (declspecs->locations[ds_storage_class]);
12908 error_at (&richloc, "member %qD cannot be declared both %<virtual%> "
12909 "and %<static%>", dname);
12910 storage_class = sc_none;
12911 staticp = 0;
12913 if (constexpr_p && pedantic && cxx_dialect < cxx20)
12915 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
12916 richloc.add_range (declspecs->locations[ds_constexpr]);
12917 pedwarn (&richloc, OPT_Wc__20_extensions, "member %qD can be "
12918 "declared both %<virtual%> and %<constexpr%> only in "
12919 "%<-std=c++20%> or %<-std=gnu++20%>", dname);
12922 friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
12924 /* Issue errors about use of storage classes for parameters. */
12925 if (decl_context == PARM)
12927 if (typedef_p)
12929 error_at (declspecs->locations[ds_typedef],
12930 "typedef declaration invalid in parameter declaration");
12931 return error_mark_node;
12933 else if (template_parm_flag && storage_class != sc_none)
12935 error_at (min_location (declspecs->locations[ds_thread],
12936 declspecs->locations[ds_storage_class]),
12937 "storage class specified for template parameter %qs",
12938 name);
12939 return error_mark_node;
12941 else if (storage_class == sc_static
12942 || storage_class == sc_extern
12943 || thread_p)
12945 error_at (min_location (declspecs->locations[ds_thread],
12946 declspecs->locations[ds_storage_class]),
12947 "storage class specified for parameter %qs", name);
12948 return error_mark_node;
12951 /* Function parameters cannot be concept. */
12952 if (concept_p)
12954 error_at (declspecs->locations[ds_concept],
12955 "a parameter cannot be declared %qs", "concept");
12956 concept_p = 0;
12957 constexpr_p = 0;
12959 /* Function parameters cannot be constexpr. If we saw one, moan
12960 and pretend it wasn't there. */
12961 else if (constexpr_p)
12963 error_at (declspecs->locations[ds_constexpr],
12964 "a parameter cannot be declared %qs", "constexpr");
12965 constexpr_p = 0;
12967 if (constinit_p)
12969 error_at (declspecs->locations[ds_constinit],
12970 "a parameter cannot be declared %qs", "constinit");
12971 constinit_p = 0;
12973 if (consteval_p)
12975 error_at (declspecs->locations[ds_consteval],
12976 "a parameter cannot be declared %qs", "consteval");
12977 consteval_p = 0;
12981 /* Give error if `virtual' is used outside of class declaration. */
12982 if (virtualp
12983 && (current_class_name == NULL_TREE || decl_context != FIELD))
12985 error_at (declspecs->locations[ds_virtual],
12986 "%<virtual%> outside class declaration");
12987 virtualp = 0;
12990 if (innermost_code == cdk_decomp)
12992 location_t loc = (declarator->kind == cdk_reference
12993 ? declarator->declarator->id_loc : declarator->id_loc);
12994 if (inlinep)
12995 error_at (declspecs->locations[ds_inline],
12996 "structured binding declaration cannot be %qs", "inline");
12997 if (typedef_p)
12998 error_at (declspecs->locations[ds_typedef],
12999 "structured binding declaration cannot be %qs", "typedef");
13000 if (constexpr_p && !concept_p)
13001 error_at (declspecs->locations[ds_constexpr], "structured "
13002 "binding declaration cannot be %qs", "constexpr");
13003 if (consteval_p)
13004 error_at (declspecs->locations[ds_consteval], "structured "
13005 "binding declaration cannot be %qs", "consteval");
13006 if (thread_p && cxx_dialect < cxx20)
13007 pedwarn (declspecs->locations[ds_thread], OPT_Wc__20_extensions,
13008 "structured binding declaration can be %qs only in "
13009 "%<-std=c++20%> or %<-std=gnu++20%>",
13010 declspecs->gnu_thread_keyword_p
13011 ? "__thread" : "thread_local");
13012 if (concept_p)
13013 error_at (declspecs->locations[ds_concept],
13014 "structured binding declaration cannot be %qs", "concept");
13015 /* [dcl.struct.bind] "A cv that includes volatile is deprecated." */
13016 if (type_quals & TYPE_QUAL_VOLATILE)
13017 warning_at (declspecs->locations[ds_volatile], OPT_Wvolatile,
13018 "%<volatile%>-qualified structured binding is deprecated");
13019 switch (storage_class)
13021 case sc_none:
13022 break;
13023 case sc_register:
13024 error_at (loc, "structured binding declaration cannot be %qs",
13025 "register");
13026 break;
13027 case sc_static:
13028 if (cxx_dialect < cxx20)
13029 pedwarn (loc, OPT_Wc__20_extensions,
13030 "structured binding declaration can be %qs only in "
13031 "%<-std=c++20%> or %<-std=gnu++20%>", "static");
13032 break;
13033 case sc_extern:
13034 error_at (loc, "structured binding declaration cannot be %qs",
13035 "extern");
13036 break;
13037 case sc_mutable:
13038 error_at (loc, "structured binding declaration cannot be %qs",
13039 "mutable");
13040 break;
13041 case sc_auto:
13042 error_at (loc, "structured binding declaration cannot be "
13043 "C++98 %<auto%>");
13044 break;
13045 default:
13046 gcc_unreachable ();
13048 if (TREE_CODE (type) != TEMPLATE_TYPE_PARM
13049 || TYPE_IDENTIFIER (type) != auto_identifier)
13051 if (type != error_mark_node)
13053 auto_diagnostic_group d;
13054 error_at (loc, "structured binding declaration cannot have "
13055 "type %qT", type);
13056 inform (loc,
13057 "type must be cv-qualified %<auto%> or reference to "
13058 "cv-qualified %<auto%>");
13060 type = build_qualified_type (make_auto (), type_quals);
13061 declspecs->type = type;
13063 else if (PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type))
13064 pedwarn (loc, OPT_Wpedantic,
13065 "structured binding declaration cannot have constrained "
13066 "%<auto%> type %qT", type);
13067 inlinep = 0;
13068 typedef_p = 0;
13069 constexpr_p = 0;
13070 consteval_p = 0;
13071 concept_p = 0;
13072 if (storage_class != sc_static)
13074 storage_class = sc_none;
13075 declspecs->storage_class = sc_none;
13079 /* Static anonymous unions are dealt with here. */
13080 if (staticp && decl_context == TYPENAME
13081 && declspecs->type
13082 && ANON_AGGR_TYPE_P (declspecs->type))
13083 decl_context = FIELD;
13085 /* Warn about storage classes that are invalid for certain
13086 kinds of declarations (parameters, typenames, etc.). */
13087 if (thread_p
13088 && ((storage_class
13089 && storage_class != sc_extern
13090 && storage_class != sc_static)
13091 || typedef_p))
13093 location_t loc
13094 = min_location (declspecs->locations[ds_thread],
13095 declspecs->locations[ds_storage_class]);
13096 error_at (loc, "multiple storage classes in declaration of %qs", name);
13097 thread_p = false;
13099 if (decl_context != NORMAL
13100 && ((storage_class != sc_none
13101 && storage_class != sc_mutable)
13102 || thread_p))
13104 if ((decl_context == PARM || decl_context == CATCHPARM)
13105 && (storage_class == sc_register
13106 || storage_class == sc_auto))
13108 else if (typedef_p)
13110 else if (decl_context == FIELD
13111 /* C++ allows static class elements. */
13112 && storage_class == sc_static)
13113 /* C++ also allows inlines and signed and unsigned elements,
13114 but in those cases we don't come in here. */
13116 else
13118 location_t loc
13119 = min_location (declspecs->locations[ds_thread],
13120 declspecs->locations[ds_storage_class]);
13121 if (decl_context == FIELD)
13122 error_at (loc, "storage class specified for %qs", name);
13123 else if (decl_context == PARM || decl_context == CATCHPARM)
13124 error_at (loc, "storage class specified for parameter %qs", name);
13125 else
13126 error_at (loc, "storage class specified for typename");
13127 if (storage_class == sc_register
13128 || storage_class == sc_auto
13129 || storage_class == sc_extern
13130 || thread_p)
13131 storage_class = sc_none;
13134 else if (storage_class == sc_extern && funcdef_flag
13135 && ! toplevel_bindings_p ())
13136 error ("nested function %qs declared %<extern%>", name);
13137 else if (toplevel_bindings_p ())
13139 if (storage_class == sc_auto)
13140 error_at (declspecs->locations[ds_storage_class],
13141 "top-level declaration of %qs specifies %<auto%>", name);
13143 else if (thread_p
13144 && storage_class != sc_extern
13145 && storage_class != sc_static)
13147 if (declspecs->gnu_thread_keyword_p)
13148 pedwarn (declspecs->locations[ds_thread],
13149 0, "function-scope %qs implicitly auto and "
13150 "declared %<__thread%>", name);
13152 /* When thread_local is applied to a variable of block scope the
13153 storage-class-specifier static is implied if it does not appear
13154 explicitly. */
13155 storage_class = declspecs->storage_class = sc_static;
13156 staticp = 1;
13159 if (storage_class && friendp)
13161 error_at (min_location (declspecs->locations[ds_thread],
13162 declspecs->locations[ds_storage_class]),
13163 "storage class specifiers invalid in friend function "
13164 "declarations");
13165 storage_class = sc_none;
13166 staticp = 0;
13169 if (!id_declarator)
13170 unqualified_id = NULL_TREE;
13171 else
13173 unqualified_id = id_declarator->u.id.unqualified_name;
13174 switch (TREE_CODE (unqualified_id))
13176 case BIT_NOT_EXPR:
13177 unqualified_id = TREE_OPERAND (unqualified_id, 0);
13178 if (TYPE_P (unqualified_id))
13179 unqualified_id = constructor_name (unqualified_id);
13180 break;
13182 case IDENTIFIER_NODE:
13183 case TEMPLATE_ID_EXPR:
13184 break;
13186 default:
13187 gcc_unreachable ();
13191 if (declspecs->std_attributes
13192 && !diagnose_misapplied_contracts (declspecs->std_attributes))
13194 location_t attr_loc = declspecs->locations[ds_std_attribute];
13195 if (any_nonignored_attribute_p (declspecs->std_attributes)
13196 && warning_at (attr_loc, OPT_Wattributes, "attribute ignored"))
13197 inform (attr_loc, "an attribute that appertains to a type-specifier "
13198 "is ignored");
13201 if (attrlist)
13202 diagnose_misapplied_contracts (*attrlist);
13204 /* Skip over build_memfn_type when a FUNCTION_DECL is an xobj memfn. */
13205 bool is_xobj_member_function = false;
13206 /* Determine the type of the entity declared by recurring on the
13207 declarator. */
13208 for (; declarator; declarator = declarator->declarator)
13210 const cp_declarator *inner_declarator;
13211 tree attrs;
13213 if (type == error_mark_node)
13214 return error_mark_node;
13216 attrs = declarator->attributes;
13217 if (attrs)
13219 int attr_flags;
13221 attr_flags = 0;
13222 if (declarator->kind == cdk_id)
13223 attr_flags |= (int) ATTR_FLAG_DECL_NEXT;
13224 if (declarator->kind == cdk_function)
13225 attr_flags |= (int) ATTR_FLAG_FUNCTION_NEXT;
13226 if (declarator->kind == cdk_array)
13227 attr_flags |= (int) ATTR_FLAG_ARRAY_NEXT;
13228 tree late_attrs = NULL_TREE;
13229 if (decl_context != PARM && decl_context != TYPENAME)
13230 /* Assume that any attributes that get applied late to
13231 templates will DTRT when applied to the declaration
13232 as a whole. */
13233 late_attrs = splice_template_attributes (&attrs, type);
13234 returned_attrs = decl_attributes (&type,
13235 attr_chainon (returned_attrs,
13236 attrs),
13237 attr_flags);
13238 returned_attrs = attr_chainon (late_attrs, returned_attrs);
13241 inner_declarator = declarator->declarator;
13243 /* Check that contracts aren't misapplied. */
13244 if (tree contract_attr = find_contract (declarator->std_attributes))
13245 if (declarator->kind != cdk_function
13246 || innermost_code != cdk_function)
13247 diagnose_misapplied_contracts (contract_attr);
13249 /* We don't want to warn in parameter context because we don't
13250 yet know if the parse will succeed, and this might turn out
13251 to be a constructor call. */
13252 if (decl_context != PARM
13253 && decl_context != TYPENAME
13254 && !typedef_p
13255 && declarator->parenthesized != UNKNOWN_LOCATION
13256 /* If the type is class-like and the inner name used a
13257 global namespace qualifier, we need the parens.
13258 Unfortunately all we can tell is whether a qualified name
13259 was used or not. */
13260 && !(inner_declarator
13261 && inner_declarator->kind == cdk_id
13262 && inner_declarator->u.id.qualifying_scope
13263 && (MAYBE_CLASS_TYPE_P (type)
13264 || TREE_CODE (type) == ENUMERAL_TYPE)))
13266 if (warning_at (declarator->parenthesized, OPT_Wparentheses,
13267 "unnecessary parentheses in declaration of %qs",
13268 name))
13270 gcc_rich_location iloc (declarator->parenthesized);
13271 iloc.add_fixit_remove (get_start (declarator->parenthesized));
13272 iloc.add_fixit_remove (get_finish (declarator->parenthesized));
13273 inform (&iloc, "remove parentheses");
13276 if (declarator->kind == cdk_id || declarator->kind == cdk_decomp)
13277 break;
13279 switch (declarator->kind)
13281 case cdk_array:
13282 type = create_array_type_for_decl (dname, type,
13283 declarator->u.array.bounds,
13284 declarator->id_loc);
13285 if (!valid_array_size_p (dname
13286 ? declarator->id_loc : input_location,
13287 type, dname))
13288 type = error_mark_node;
13290 if (declarator->std_attributes)
13291 /* [dcl.array]/1:
13293 The optional attribute-specifier-seq appertains to the
13294 array. */
13295 returned_attrs = attr_chainon (returned_attrs,
13296 declarator->std_attributes);
13297 break;
13299 case cdk_function:
13301 tree arg_types;
13302 int funcdecl_p;
13304 /* Declaring a function type. */
13306 /* Pick up type qualifiers which should be applied to `this'. */
13307 memfn_quals = declarator->u.function.qualifiers;
13308 /* Pick up virt-specifiers. */
13309 virt_specifiers = declarator->u.function.virt_specifiers;
13310 /* And ref-qualifier, too */
13311 rqual = declarator->u.function.ref_qualifier;
13312 /* And tx-qualifier. */
13313 tree tx_qual = declarator->u.function.tx_qualifier;
13314 /* Pick up the exception specifications. */
13315 raises = declarator->u.function.exception_specification;
13316 /* If the exception-specification is ill-formed, let's pretend
13317 there wasn't one. */
13318 if (raises == error_mark_node)
13319 raises = NULL_TREE;
13321 auto find_xobj_parm = [](tree parm_list)
13323 /* There is no need to iterate over the list,
13324 only the first parm can be a valid xobj parm. */
13325 if (!parm_list || TREE_PURPOSE (parm_list) != this_identifier)
13326 return NULL_TREE;
13327 /* If we make it here, we are looking at an xobj parm.
13329 Non-null 'purpose' usually means the parm has a default
13330 argument, we don't want to violate this assumption. */
13331 TREE_PURPOSE (parm_list) = NULL_TREE;
13332 return TREE_VALUE (parm_list);
13335 tree xobj_parm
13336 = find_xobj_parm (declarator->u.function.parameters);
13337 is_xobj_member_function = xobj_parm;
13339 if (xobj_parm && cxx_dialect < cxx23)
13340 pedwarn (DECL_SOURCE_LOCATION (xobj_parm), OPT_Wc__23_extensions,
13341 "explicit object member function only available "
13342 "with %<-std=c++23%> or %<-std=gnu++23%>");
13344 if (xobj_parm && decl_context == TYPENAME)
13346 /* We inform in every case, just differently depending on what
13347 case it is. */
13348 auto_diagnostic_group d;
13349 bool ptr_type = true;
13350 /* If declarator->kind is cdk_function and we are at the end of
13351 the declarator chain, we are looking at a function type. */
13352 if (!declarator->declarator)
13354 error_at (DECL_SOURCE_LOCATION (xobj_parm),
13355 "a function type cannot "
13356 "have an explicit object parameter");
13357 ptr_type = false;
13359 else if (declarator->declarator->kind == cdk_pointer)
13360 error_at (DECL_SOURCE_LOCATION (xobj_parm),
13361 "a pointer to function type cannot "
13362 "have an explicit object parameter");
13363 else if (declarator->declarator->kind == cdk_ptrmem)
13364 error_at (DECL_SOURCE_LOCATION (xobj_parm),
13365 "a pointer to member function type "
13366 "cannot have an explicit object parameter");
13367 else
13368 gcc_unreachable ();
13370 /* The locations being used here are probably not correct. */
13371 if (ptr_type)
13372 inform (DECL_SOURCE_LOCATION (xobj_parm),
13373 "the type of a pointer to explicit object member "
13374 "function is a regular pointer to function type");
13375 else
13376 inform (DECL_SOURCE_LOCATION (xobj_parm),
13377 "the type of an explicit object "
13378 "member function is a regular function type");
13379 /* Ideally we should synthesize the correct syntax
13380 for the user, perhaps this could be added later. */
13382 /* Since a valid xobj parm has its purpose cleared in find_xobj_parm
13383 the first parm node will never erroneously be detected here. */
13385 auto_diagnostic_group d;
13386 bool bad_xobj_parm_encountered = false;
13387 for (tree parm = declarator->u.function.parameters;
13388 parm && parm != void_list_node;
13389 parm = TREE_CHAIN (parm))
13391 if (TREE_PURPOSE (parm) != this_identifier)
13392 continue;
13393 bad_xobj_parm_encountered = true;
13394 TREE_PURPOSE (parm) = NULL_TREE;
13395 gcc_rich_location bad_xobj_parm
13396 (DECL_SOURCE_LOCATION (TREE_VALUE (parm)));
13397 error_at (&bad_xobj_parm,
13398 "only the first parameter of a member function "
13399 "can be declared as an explicit object parameter");
13401 if (bad_xobj_parm_encountered && xobj_parm)
13402 inform (DECL_SOURCE_LOCATION (xobj_parm),
13403 "valid explicit object parameter declared here");
13406 if (reqs)
13407 error_at (location_of (reqs), "requires-clause on return type");
13408 reqs = declarator->u.function.requires_clause;
13410 /* Say it's a definition only for the CALL_EXPR
13411 closest to the identifier. */
13412 funcdecl_p = inner_declarator && inner_declarator->kind == cdk_id;
13414 /* Handle a late-specified return type. */
13415 tree late_return_type = declarator->u.function.late_return_type;
13416 if (tree auto_node = type_uses_auto (type))
13418 if (!late_return_type)
13420 if (!funcdecl_p)
13421 /* auto (*fp)() = f; is OK. */;
13422 else if (current_class_type
13423 && LAMBDA_TYPE_P (current_class_type))
13424 /* OK for C++11 lambdas. */;
13425 else if (cxx_dialect < cxx14)
13427 error_at (typespec_loc, "%qs function uses "
13428 "%<auto%> type specifier without "
13429 "trailing return type", name);
13430 inform (typespec_loc,
13431 "deduced return type only available "
13432 "with %<-std=c++14%> or %<-std=gnu++14%>");
13434 else if (virtualp)
13436 error_at (typespec_loc, "virtual function "
13437 "cannot have deduced return type");
13438 virtualp = false;
13441 else if (!is_auto (type) && sfk != sfk_conversion)
13443 error_at (typespec_loc, "%qs function with trailing "
13444 "return type has %qT as its type rather "
13445 "than plain %<auto%>", name, type);
13446 return error_mark_node;
13448 else if (is_auto (type) && AUTO_IS_DECLTYPE (type))
13450 if (funcdecl_p)
13451 error_at (typespec_loc,
13452 "%qs function with trailing return type "
13453 "has %<decltype(auto)%> as its type "
13454 "rather than plain %<auto%>", name);
13455 else
13456 error_at (typespec_loc,
13457 "invalid use of %<decltype(auto)%>");
13458 return error_mark_node;
13460 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node);
13461 if (!tmpl)
13462 if (tree late_auto = type_uses_auto (late_return_type))
13463 tmpl = CLASS_PLACEHOLDER_TEMPLATE (late_auto);
13464 if (tmpl)
13466 if (!funcdecl_p || !dguide_name_p (unqualified_id))
13468 auto_diagnostic_group g;
13469 error_at (typespec_loc, "deduced class "
13470 "type %qD in function return type",
13471 DECL_NAME (tmpl));
13472 inform (DECL_SOURCE_LOCATION (tmpl),
13473 "%qD declared here", tmpl);
13474 return error_mark_node;
13476 else if (!late_return_type)
13478 error_at (declarator->id_loc, "deduction guide "
13479 "for %qT must have trailing return "
13480 "type", TREE_TYPE (tmpl));
13481 inform (DECL_SOURCE_LOCATION (tmpl),
13482 "%qD declared here", tmpl);
13483 return error_mark_node;
13485 else if (CLASS_TYPE_P (late_return_type)
13486 && CLASSTYPE_TEMPLATE_INFO (late_return_type)
13487 && (CLASSTYPE_TI_TEMPLATE (late_return_type)
13488 == tmpl))
13489 /* OK */;
13490 else
13491 error ("trailing return type %qT of deduction guide "
13492 "is not a specialization of %qT",
13493 late_return_type, TREE_TYPE (tmpl));
13496 else if (late_return_type
13497 && sfk != sfk_conversion)
13499 if (late_return_type == error_mark_node)
13500 return error_mark_node;
13501 if (cxx_dialect < cxx11)
13502 /* Not using maybe_warn_cpp0x because this should
13503 always be an error. */
13504 error_at (typespec_loc,
13505 "trailing return type only available "
13506 "with %<-std=c++11%> or %<-std=gnu++11%>");
13507 else
13508 error_at (typespec_loc, "%qs function with trailing "
13509 "return type not declared with %<auto%> "
13510 "type specifier", name);
13511 return error_mark_node;
13513 if (late_return_type && sfk == sfk_conversion)
13515 error ("a conversion function cannot have a trailing return type");
13516 return error_mark_node;
13518 type = splice_late_return_type (type, late_return_type);
13519 if (type == error_mark_node)
13520 return error_mark_node;
13522 if (late_return_type)
13524 late_return_type_p = true;
13525 type_quals = cp_type_quals (type);
13528 if (type_quals != TYPE_UNQUALIFIED)
13530 /* It's wrong, for instance, to issue a -Wignored-qualifiers
13531 warning for
13532 static_assert(!is_same_v<void(*)(), const void(*)()>);
13533 because there the qualifier matters. */
13534 if (funcdecl_p && (SCALAR_TYPE_P (type) || VOID_TYPE_P (type)))
13535 warning_at (typespec_loc, OPT_Wignored_qualifiers, "type "
13536 "qualifiers ignored on function return type");
13537 /* [dcl.fct] "A volatile-qualified return type is
13538 deprecated." */
13539 if (type_quals & TYPE_QUAL_VOLATILE)
13540 warning_at (typespec_loc, OPT_Wvolatile,
13541 "%<volatile%>-qualified return type is "
13542 "deprecated");
13544 /* We now know that the TYPE_QUALS don't apply to the
13545 decl, but to its return type. */
13546 type_quals = TYPE_UNQUALIFIED;
13549 /* Error about some types functions can't return. */
13551 if (TREE_CODE (type) == FUNCTION_TYPE)
13553 error_at (typespec_loc, "%qs declared as function returning "
13554 "a function", name);
13555 return error_mark_node;
13557 if (TREE_CODE (type) == ARRAY_TYPE)
13559 error_at (typespec_loc, "%qs declared as function returning "
13560 "an array", name);
13561 return error_mark_node;
13563 if (constinit_p && funcdecl_p)
13565 error_at (declspecs->locations[ds_constinit],
13566 "%<constinit%> on function return type is not "
13567 "allowed");
13568 return error_mark_node;
13571 if (check_decltype_auto (typespec_loc, type))
13572 return error_mark_node;
13574 if (ctype == NULL_TREE
13575 && decl_context == FIELD
13576 && funcdecl_p
13577 && friendp == 0)
13578 ctype = current_class_type;
13580 if (ctype && (sfk == sfk_constructor
13581 || sfk == sfk_destructor))
13583 /* We are within a class's scope. If our declarator name
13584 is the same as the class name, and we are defining
13585 a function, then it is a constructor/destructor, and
13586 therefore returns a void type. */
13588 /* ISO C++ 12.4/2. A destructor may not be declared
13589 const or volatile. A destructor may not be static.
13590 A destructor may not be declared with ref-qualifier.
13592 ISO C++ 12.1. A constructor may not be declared
13593 const or volatile. A constructor may not be
13594 virtual. A constructor may not be static.
13595 A constructor may not be declared with ref-qualifier. */
13596 if (staticp == 2)
13597 error_at (declspecs->locations[ds_storage_class],
13598 (flags == DTOR_FLAG)
13599 ? G_("destructor cannot be static member "
13600 "function")
13601 : G_("constructor cannot be static member "
13602 "function"));
13603 if (memfn_quals)
13605 error ((flags == DTOR_FLAG)
13606 ? G_("destructors may not be cv-qualified")
13607 : G_("constructors may not be cv-qualified"));
13608 memfn_quals = TYPE_UNQUALIFIED;
13611 if (rqual)
13613 maybe_warn_cpp0x (CPP0X_REF_QUALIFIER);
13614 error ((flags == DTOR_FLAG)
13615 ? G_("destructors may not be ref-qualified")
13616 : G_("constructors may not be ref-qualified"));
13617 rqual = REF_QUAL_NONE;
13620 if (decl_context == FIELD
13621 && !member_function_or_else (ctype,
13622 current_class_type,
13623 flags))
13624 return error_mark_node;
13626 if (flags != DTOR_FLAG)
13628 /* It's a constructor. */
13629 if (explicitp == 1)
13630 explicitp = 2;
13631 if (virtualp)
13633 permerror (declspecs->locations[ds_virtual],
13634 "constructors cannot be declared %<virtual%>");
13635 virtualp = 0;
13637 if (decl_context == FIELD
13638 && sfk != sfk_constructor)
13639 return error_mark_node;
13641 if (decl_context == FIELD)
13642 staticp = 0;
13644 else if (friendp)
13646 if (virtualp)
13648 /* Cannot be both friend and virtual. */
13649 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
13650 richloc.add_range (declspecs->locations[ds_friend]);
13651 error_at (&richloc, "virtual functions cannot be friends");
13652 friendp = 0;
13654 if (decl_context == NORMAL)
13655 error_at (declarator->id_loc,
13656 "friend declaration not in class definition");
13657 if (current_function_decl && funcdef_flag)
13659 error_at (declarator->id_loc,
13660 "cannot define friend function %qs in a local "
13661 "class definition", name);
13662 friendp = 0;
13664 /* [class.friend]/6: A function can be defined in a friend
13665 declaration if the function name is unqualified. */
13666 if (funcdef_flag && in_namespace)
13668 if (in_namespace == global_namespace)
13669 error_at (declarator->id_loc,
13670 "friend function definition %qs cannot have "
13671 "a name qualified with %<::%>", name);
13672 else
13673 error_at (declarator->id_loc,
13674 "friend function definition %qs cannot have "
13675 "a name qualified with %<%D::%>", name,
13676 in_namespace);
13679 else if (ctype && sfk == sfk_conversion)
13681 if (explicitp == 1)
13683 maybe_warn_cpp0x (CPP0X_EXPLICIT_CONVERSION);
13684 explicitp = 2;
13687 else if (sfk == sfk_deduction_guide)
13689 if (explicitp == 1)
13690 explicitp = 2;
13693 if (xobj_parm)
13695 if (!ctype
13696 && decl_context == NORMAL
13697 && (in_namespace
13698 || !declarator->declarator->u.id.qualifying_scope))
13699 error_at (DECL_SOURCE_LOCATION (xobj_parm),
13700 "a non-member function cannot have "
13701 "an explicit object parameter");
13702 else
13704 if (virtualp)
13706 auto_diagnostic_group d;
13707 error_at (declspecs->locations[ds_virtual],
13708 "an explicit object member function cannot "
13709 "be %<virtual%>");
13710 inform (DECL_SOURCE_LOCATION (xobj_parm),
13711 "explicit object parameter declared here");
13712 virtualp = false;
13714 if (staticp >= 2)
13716 auto_diagnostic_group d;
13717 error_at (declspecs->locations[ds_storage_class],
13718 "an explicit object member function cannot "
13719 "be %<static%>");
13720 inform (DECL_SOURCE_LOCATION (xobj_parm),
13721 "explicit object parameter declared here");
13725 tree pushed_scope = NULL_TREE;
13726 if (funcdecl_p
13727 && decl_context != FIELD
13728 && inner_declarator->u.id.qualifying_scope
13729 && CLASS_TYPE_P (inner_declarator->u.id.qualifying_scope))
13730 pushed_scope
13731 = push_scope (inner_declarator->u.id.qualifying_scope);
13733 arg_types = grokparms (declarator->u.function.parameters, &parms);
13735 if (pushed_scope)
13736 pop_scope (pushed_scope);
13738 if (inner_declarator
13739 && inner_declarator->kind == cdk_id
13740 && inner_declarator->u.id.sfk == sfk_destructor
13741 && arg_types != void_list_node)
13743 error_at (declarator->id_loc,
13744 "destructors may not have parameters");
13745 arg_types = void_list_node;
13746 parms = NULL_TREE;
13747 is_xobj_member_function = false;
13750 type = build_function_type (type, arg_types);
13752 tree attrs = declarator->std_attributes;
13753 if (tx_qual)
13755 tree att = build_tree_list (tx_qual, NULL_TREE);
13756 /* transaction_safe applies to the type, but
13757 transaction_safe_dynamic applies to the function. */
13758 if (is_attribute_p ("transaction_safe", tx_qual))
13759 attrs = attr_chainon (attrs, att);
13760 else
13761 returned_attrs = attr_chainon (returned_attrs, att);
13764 /* Actually apply the contract attributes to the declaration. */
13765 for (tree *p = &attrs; *p;)
13767 tree l = *p;
13768 if (cxx_contract_attribute_p (l))
13770 *p = TREE_CHAIN (l);
13771 /* Intentionally reverse order of contracts so they're
13772 reversed back into their lexical order. */
13773 TREE_CHAIN (l) = NULL_TREE;
13774 returned_attrs = chainon (l, returned_attrs);
13776 else
13777 p = &TREE_CHAIN (l);
13780 if (attrs)
13781 /* [dcl.fct]/2:
13783 The optional attribute-specifier-seq appertains to
13784 the function type. */
13785 cplus_decl_attributes (&type, attrs, 0);
13787 if (raises)
13788 type = build_exception_variant (type, raises);
13790 break;
13792 case cdk_pointer:
13793 case cdk_reference:
13794 case cdk_ptrmem:
13795 /* Filter out pointers-to-references and references-to-references.
13796 We can get these if a TYPE_DECL is used. */
13798 if (TYPE_REF_P (type))
13800 if (declarator->kind != cdk_reference)
13802 error ("cannot declare pointer to %q#T", type);
13803 type = TREE_TYPE (type);
13806 /* In C++0x, we allow reference to reference declarations
13807 that occur indirectly through typedefs [7.1.3/8 dcl.typedef]
13808 and template type arguments [14.3.1/4 temp.arg.type]. The
13809 check for direct reference to reference declarations, which
13810 are still forbidden, occurs below. Reasoning behind the change
13811 can be found in DR106, DR540, and the rvalue reference
13812 proposals. */
13813 else if (cxx_dialect == cxx98)
13815 error ("cannot declare reference to %q#T", type);
13816 type = TREE_TYPE (type);
13819 else if (VOID_TYPE_P (type))
13821 if (declarator->kind == cdk_reference)
13822 error ("cannot declare reference to %q#T", type);
13823 else if (declarator->kind == cdk_ptrmem)
13824 error ("cannot declare pointer to %q#T member", type);
13827 /* We now know that the TYPE_QUALS don't apply to the decl,
13828 but to the target of the pointer. */
13829 type_quals = TYPE_UNQUALIFIED;
13831 /* This code used to handle METHOD_TYPE, but I don't think it's
13832 possible to get it here anymore. */
13833 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
13834 if (declarator->kind == cdk_ptrmem
13835 && TREE_CODE (type) == FUNCTION_TYPE)
13837 memfn_quals |= type_memfn_quals (type);
13838 type = build_memfn_type (type,
13839 declarator->u.pointer.class_type,
13840 memfn_quals,
13841 rqual);
13842 if (type == error_mark_node)
13843 return error_mark_node;
13845 rqual = REF_QUAL_NONE;
13846 memfn_quals = TYPE_UNQUALIFIED;
13849 if (TREE_CODE (type) == FUNCTION_TYPE
13850 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
13851 || type_memfn_rqual (type) != REF_QUAL_NONE))
13852 error (declarator->kind == cdk_reference
13853 ? G_("cannot declare reference to qualified function type %qT")
13854 : G_("cannot declare pointer to qualified function type %qT"),
13855 type);
13857 /* When the pointed-to type involves components of variable size,
13858 care must be taken to ensure that the size evaluation code is
13859 emitted early enough to dominate all the possible later uses
13860 and late enough for the variables on which it depends to have
13861 been assigned.
13863 This is expected to happen automatically when the pointed-to
13864 type has a name/declaration of it's own, but special attention
13865 is required if the type is anonymous.
13867 We handle the NORMAL and FIELD contexts here by inserting a
13868 dummy statement that just evaluates the size at a safe point
13869 and ensures it is not deferred until e.g. within a deeper
13870 conditional context (c++/43555).
13872 We expect nothing to be needed here for PARM or TYPENAME.
13873 Evaluating the size at this point for TYPENAME would
13874 actually be incorrect, as we might be in the middle of an
13875 expression with side effects on the pointed-to type size
13876 "arguments" prior to the pointer declaration point and the
13877 size evaluation could end up prior to the side effects. */
13879 if (!TYPE_NAME (type)
13880 && (decl_context == NORMAL || decl_context == FIELD)
13881 && at_function_scope_p ()
13882 && variably_modified_type_p (type, NULL_TREE))
13884 TYPE_NAME (type) = build_decl (UNKNOWN_LOCATION, TYPE_DECL,
13885 NULL_TREE, type);
13886 add_decl_expr (TYPE_NAME (type));
13889 if (declarator->kind == cdk_reference)
13891 /* In C++0x, the type we are creating a reference to might be
13892 a typedef which is itself a reference type. In that case,
13893 we follow the reference collapsing rules in
13894 [7.1.3/8 dcl.typedef] to create the final reference type:
13896 "If a typedef TD names a type that is a reference to a type
13897 T, an attempt to create the type 'lvalue reference to cv TD'
13898 creates the type 'lvalue reference to T,' while an attempt
13899 to create the type "rvalue reference to cv TD' creates the
13900 type TD."
13902 if (VOID_TYPE_P (type))
13903 /* We already gave an error. */;
13904 else if (TYPE_REF_P (type))
13906 if (declarator->u.reference.rvalue_ref)
13907 /* Leave type alone. */;
13908 else
13909 type = cp_build_reference_type (TREE_TYPE (type), false);
13911 else
13912 type = cp_build_reference_type
13913 (type, declarator->u.reference.rvalue_ref);
13915 /* In C++0x, we need this check for direct reference to
13916 reference declarations, which are forbidden by
13917 [8.3.2/5 dcl.ref]. Reference to reference declarations
13918 are only allowed indirectly through typedefs and template
13919 type arguments. Example:
13921 void foo(int & &); // invalid ref-to-ref decl
13923 typedef int & int_ref;
13924 void foo(int_ref &); // valid ref-to-ref decl
13926 if (inner_declarator && inner_declarator->kind == cdk_reference)
13927 error ("cannot declare reference to %q#T, which is not "
13928 "a typedef or a template type argument", type);
13930 else if (TREE_CODE (type) == METHOD_TYPE)
13931 type = build_ptrmemfunc_type (build_pointer_type (type));
13932 else if (declarator->kind == cdk_ptrmem)
13934 gcc_assert (TREE_CODE (declarator->u.pointer.class_type)
13935 != NAMESPACE_DECL);
13936 if (declarator->u.pointer.class_type == error_mark_node)
13937 /* We will already have complained. */
13938 type = error_mark_node;
13939 else
13940 type = build_ptrmem_type (declarator->u.pointer.class_type,
13941 type);
13943 else
13944 type = build_pointer_type (type);
13946 /* Process a list of type modifier keywords (such as
13947 const or volatile) that were given inside the `*' or `&'. */
13949 if (declarator->u.pointer.qualifiers)
13951 type
13952 = cp_build_qualified_type (type,
13953 declarator->u.pointer.qualifiers);
13954 type_quals = cp_type_quals (type);
13957 /* Apply C++11 attributes to the pointer, and not to the
13958 type pointed to. This is unlike what is done for GNU
13959 attributes above. It is to comply with [dcl.ptr]/1:
13961 [the optional attribute-specifier-seq (7.6.1) appertains
13962 to the pointer and not to the object pointed to]. */
13963 if (declarator->std_attributes)
13964 decl_attributes (&type, declarator->std_attributes,
13967 ctype = NULL_TREE;
13968 break;
13970 case cdk_error:
13971 break;
13973 default:
13974 gcc_unreachable ();
13978 id_loc = declarator ? declarator->id_loc : input_location;
13980 if (innermost_code != cdk_function
13981 /* Don't check this if it can be the artifical decltype(auto)
13982 we created when building a constraint in a compound-requirement:
13983 that the type-constraint is plain is going to be checked in
13984 cp_parser_compound_requirement. */
13985 && decl_context != TYPENAME
13986 && check_decltype_auto (id_loc, type))
13987 return error_mark_node;
13989 /* A `constexpr' specifier used in an object declaration declares
13990 the object as `const'. */
13991 if (constexpr_p && innermost_code != cdk_function)
13993 /* DR1688 says that a `constexpr' specifier in combination with
13994 `volatile' is valid. */
13996 if (!TYPE_REF_P (type))
13998 type_quals |= TYPE_QUAL_CONST;
13999 type = cp_build_qualified_type (type, type_quals);
14003 if (unqualified_id && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR
14004 && !FUNC_OR_METHOD_TYPE_P (type)
14005 && !variable_template_p (TREE_OPERAND (unqualified_id, 0)))
14007 error ("template-id %qD used as a declarator",
14008 unqualified_id);
14009 unqualified_id = dname;
14012 /* If TYPE is a FUNCTION_TYPE, but the function name was explicitly
14013 qualified with a class-name, turn it into a METHOD_TYPE, unless
14014 we know that the function is static. We take advantage of this
14015 opportunity to do other processing that pertains to entities
14016 explicitly declared to be class members. Note that if DECLARATOR
14017 is non-NULL, we know it is a cdk_id declarator; otherwise, we
14018 would not have exited the loop above. */
14019 if (declarator
14020 && declarator->kind == cdk_id
14021 && declarator->u.id.qualifying_scope
14022 && MAYBE_CLASS_TYPE_P (declarator->u.id.qualifying_scope))
14024 ctype = declarator->u.id.qualifying_scope;
14025 ctype = TYPE_MAIN_VARIANT (ctype);
14026 template_count = num_template_headers_for_class (ctype);
14028 if (ctype == current_class_type)
14030 if (friendp)
14032 permerror (declspecs->locations[ds_friend],
14033 "member functions are implicitly "
14034 "friends of their class");
14035 friendp = 0;
14037 else
14038 permerror (id_loc, "extra qualification %<%T::%> on member %qs",
14039 ctype, name);
14041 else if (/* If the qualifying type is already complete, then we
14042 can skip the following checks. */
14043 !COMPLETE_TYPE_P (ctype)
14044 && (/* If the function is being defined, then
14045 qualifying type must certainly be complete. */
14046 funcdef_flag
14047 /* A friend declaration of "T::f" is OK, even if
14048 "T" is a template parameter. But, if this
14049 function is not a friend, the qualifying type
14050 must be a class. */
14051 || (!friendp && !CLASS_TYPE_P (ctype))
14052 /* For a declaration, the type need not be
14053 complete, if either it is dependent (since there
14054 is no meaningful definition of complete in that
14055 case) or the qualifying class is currently being
14056 defined. */
14057 || !(dependent_type_p (ctype)
14058 || currently_open_class (ctype)))
14059 /* Check that the qualifying type is complete. */
14060 && !complete_type_or_else (ctype, NULL_TREE))
14061 return error_mark_node;
14062 else if (TREE_CODE (type) == FUNCTION_TYPE)
14064 if (current_class_type
14065 && (!friendp || funcdef_flag || initialized))
14067 error_at (id_loc, funcdef_flag || initialized
14068 ? G_("cannot define member function %<%T::%s%> "
14069 "within %qT")
14070 : G_("cannot declare member function %<%T::%s%> "
14071 "within %qT"),
14072 ctype, name, current_class_type);
14073 return error_mark_node;
14076 else if (typedef_p && current_class_type)
14078 error_at (id_loc, "cannot declare member %<%T::%s%> within %qT",
14079 ctype, name, current_class_type);
14080 return error_mark_node;
14084 if (ctype == NULL_TREE && decl_context == FIELD && friendp == 0)
14085 ctype = current_class_type;
14087 /* Now TYPE has the actual type. */
14089 if (returned_attrs)
14091 if (attrlist)
14092 *attrlist = attr_chainon (returned_attrs, *attrlist);
14093 else
14094 attrlist = &returned_attrs;
14097 if (declarator
14098 && declarator->kind == cdk_id
14099 && declarator->std_attributes
14100 && attrlist != NULL)
14102 /* [dcl.meaning]/1: The optional attribute-specifier-seq following
14103 a declarator-id appertains to the entity that is declared. */
14104 if (declarator->std_attributes != error_mark_node)
14105 *attrlist = attr_chainon (declarator->std_attributes, *attrlist);
14106 else
14107 /* We should have already diagnosed the issue (c++/78344). */
14108 gcc_assert (seen_error ());
14111 /* Handle parameter packs. */
14112 if (parameter_pack_p)
14114 if (decl_context == PARM)
14115 /* Turn the type into a pack expansion.*/
14116 type = make_pack_expansion (type);
14117 else
14118 error ("non-parameter %qs cannot be a parameter pack", name);
14121 if ((decl_context == FIELD || decl_context == PARM)
14122 && !processing_template_decl
14123 && variably_modified_type_p (type, NULL_TREE))
14125 if (decl_context == FIELD)
14126 error_at (id_loc,
14127 "data member may not have variably modified type %qT", type);
14128 else
14129 error_at (id_loc,
14130 "parameter may not have variably modified type %qT", type);
14131 type = error_mark_node;
14134 if (explicitp == 1 || (explicitp && friendp))
14136 /* [dcl.fct.spec] (C++11) The explicit specifier shall be used only
14137 in the declaration of a constructor or conversion function within
14138 a class definition. */
14139 if (!current_class_type)
14140 error_at (declspecs->locations[ds_explicit],
14141 "%<explicit%> outside class declaration");
14142 else if (friendp)
14143 error_at (declspecs->locations[ds_explicit],
14144 "%<explicit%> in friend declaration");
14145 else
14146 error_at (declspecs->locations[ds_explicit],
14147 "only declarations of constructors and conversion operators "
14148 "can be %<explicit%>");
14149 explicitp = 0;
14152 if (storage_class == sc_mutable)
14154 location_t sloc = declspecs->locations[ds_storage_class];
14155 if (decl_context != FIELD || friendp)
14157 error_at (sloc, "non-member %qs cannot be declared %<mutable%>",
14158 name);
14159 storage_class = sc_none;
14161 else if (decl_context == TYPENAME || typedef_p)
14163 error_at (sloc,
14164 "non-object member %qs cannot be declared %<mutable%>",
14165 name);
14166 storage_class = sc_none;
14168 else if (FUNC_OR_METHOD_TYPE_P (type))
14170 error_at (sloc, "function %qs cannot be declared %<mutable%>",
14171 name);
14172 storage_class = sc_none;
14174 else if (staticp)
14176 error_at (sloc, "%<static%> %qs cannot be declared %<mutable%>",
14177 name);
14178 storage_class = sc_none;
14180 else if (type_quals & TYPE_QUAL_CONST)
14182 error_at (sloc, "%<const%> %qs cannot be declared %<mutable%>",
14183 name);
14184 storage_class = sc_none;
14186 else if (TYPE_REF_P (type))
14188 permerror (sloc, "reference %qs cannot be declared %<mutable%>",
14189 name);
14190 storage_class = sc_none;
14194 /* If this is declaring a typedef name, return a TYPE_DECL. */
14195 if (typedef_p && decl_context != TYPENAME)
14197 bool alias_p = decl_spec_seq_has_spec_p (declspecs, ds_alias);
14198 tree decl;
14200 if (funcdef_flag)
14202 if (decl_context == NORMAL)
14203 error_at (id_loc,
14204 "typedef may not be a function definition");
14205 else
14206 error_at (id_loc,
14207 "typedef may not be a member function definition");
14208 return error_mark_node;
14211 /* This declaration:
14213 typedef void f(int) const;
14215 declares a function type which is not a member of any
14216 particular class, but which is cv-qualified; for
14217 example "f S::*" declares a pointer to a const-qualified
14218 member function of S. We record the cv-qualification in the
14219 function type. */
14220 if ((rqual || memfn_quals) && TREE_CODE (type) == FUNCTION_TYPE)
14222 type = apply_memfn_quals (type, memfn_quals, rqual);
14224 /* We have now dealt with these qualifiers. */
14225 memfn_quals = TYPE_UNQUALIFIED;
14226 rqual = REF_QUAL_NONE;
14229 if (type_uses_auto (type))
14231 if (alias_p)
14232 error_at (declspecs->locations[ds_type_spec],
14233 "%<auto%> not allowed in alias declaration");
14234 else
14235 error_at (declspecs->locations[ds_type_spec],
14236 "typedef declared %<auto%>");
14237 type = error_mark_node;
14240 if (reqs)
14241 error_at (location_of (reqs), "requires-clause on typedef");
14243 if (id_declarator && declarator->u.id.qualifying_scope)
14245 error_at (id_loc, "typedef name may not be a nested-name-specifier");
14246 type = error_mark_node;
14249 if (decl_context == FIELD)
14250 decl = build_lang_decl_loc (id_loc, TYPE_DECL, unqualified_id, type);
14251 else
14252 decl = build_decl (id_loc, TYPE_DECL, unqualified_id, type);
14254 if (decl_context != FIELD)
14256 if (!current_function_decl)
14257 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
14258 else if (DECL_MAYBE_IN_CHARGE_CDTOR_P (current_function_decl))
14259 /* The TYPE_DECL is "abstract" because there will be
14260 clones of this constructor/destructor, and there will
14261 be copies of this TYPE_DECL generated in those
14262 clones. The decloning optimization (for space) may
14263 revert this subsequently if it determines that
14264 the clones should share a common implementation. */
14265 DECL_ABSTRACT_P (decl) = true;
14267 set_originating_module (decl);
14269 else if (current_class_type
14270 && constructor_name_p (unqualified_id, current_class_type))
14271 permerror (id_loc, "ISO C++ forbids nested type %qD with same name "
14272 "as enclosing class",
14273 unqualified_id);
14275 /* If the user declares "typedef struct {...} foo" then the
14276 struct will have an anonymous name. Fill that name in now.
14277 Nothing can refer to it, so nothing needs know about the name
14278 change. */
14279 if (type != error_mark_node
14280 && unqualified_id
14281 && TYPE_NAME (type)
14282 && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL
14283 && TYPE_UNNAMED_P (type)
14284 && declspecs->type_definition_p
14285 && attributes_naming_typedef_ok (*attrlist)
14286 && cp_type_quals (type) == TYPE_UNQUALIFIED)
14287 name_unnamed_type (type, decl);
14289 if (signed_p
14290 || (typedef_decl && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl)))
14291 C_TYPEDEF_EXPLICITLY_SIGNED (decl) = 1;
14293 bad_specifiers (decl, BSP_TYPE, virtualp,
14294 memfn_quals != TYPE_UNQUALIFIED,
14295 inlinep, friendp, raises != NULL_TREE,
14296 declspecs->locations);
14298 if (alias_p)
14299 /* Acknowledge that this was written:
14300 `using analias = atype;'. */
14301 TYPE_DECL_ALIAS_P (decl) = 1;
14303 return decl;
14306 /* Detect the case of an array type of unspecified size
14307 which came, as such, direct from a typedef name.
14308 We must copy the type, so that the array's domain can be
14309 individually set by the object's initializer. */
14311 if (type && typedef_type
14312 && TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type)
14313 && TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (typedef_type))
14314 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
14316 /* Detect where we're using a typedef of function type to declare a
14317 function. PARMS will not be set, so we must create it now. */
14319 if (type == typedef_type && TREE_CODE (type) == FUNCTION_TYPE)
14321 tree decls = NULL_TREE;
14322 tree args;
14324 for (args = TYPE_ARG_TYPES (type);
14325 args && args != void_list_node;
14326 args = TREE_CHAIN (args))
14328 tree decl = cp_build_parm_decl (NULL_TREE, NULL_TREE,
14329 TREE_VALUE (args));
14331 DECL_CHAIN (decl) = decls;
14332 decls = decl;
14335 parms = nreverse (decls);
14337 if (decl_context != TYPENAME)
14339 /* The qualifiers on the function type become the qualifiers on
14340 the non-static member function. */
14341 memfn_quals |= type_memfn_quals (type);
14342 rqual = type_memfn_rqual (type);
14343 type_quals = TYPE_UNQUALIFIED;
14344 raises = TYPE_RAISES_EXCEPTIONS (type);
14348 /* If this is a type name (such as, in a cast or sizeof),
14349 compute the type and return it now. */
14351 if (decl_context == TYPENAME)
14353 /* Note that here we don't care about type_quals. */
14355 /* Special case: "friend class foo" looks like a TYPENAME context. */
14356 if (friendp)
14358 if (inlinep)
14360 error ("%<inline%> specified for friend class declaration");
14361 inlinep = 0;
14364 if (!current_aggr)
14366 /* Don't allow friend declaration without a class-key. */
14367 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
14368 permerror (input_location, "template parameters cannot be friends");
14369 else if (TREE_CODE (type) == TYPENAME_TYPE)
14370 permerror (input_location, "friend declaration requires class-key, "
14371 "i.e. %<friend class %T::%D%>",
14372 TYPE_CONTEXT (type), TYPENAME_TYPE_FULLNAME (type));
14373 else
14374 permerror (input_location, "friend declaration requires class-key, "
14375 "i.e. %<friend %#T%>",
14376 type);
14379 /* Only try to do this stuff if we didn't already give up. */
14380 if (type != integer_type_node)
14382 /* A friendly class? */
14383 if (current_class_type)
14384 make_friend_class (current_class_type, TYPE_MAIN_VARIANT (type),
14385 /*complain=*/true);
14386 else
14387 error ("trying to make class %qT a friend of global scope",
14388 type);
14390 type = void_type_node;
14393 else if (memfn_quals || rqual)
14395 if (ctype == NULL_TREE
14396 && TREE_CODE (type) == METHOD_TYPE)
14397 ctype = TYPE_METHOD_BASETYPE (type);
14399 if (ctype)
14400 type = build_memfn_type (type, ctype, memfn_quals, rqual);
14401 /* Core issue #547: need to allow this in template type args.
14402 Allow it in general in C++11 for alias-declarations. */
14403 else if ((template_type_arg || cxx_dialect >= cxx11)
14404 && TREE_CODE (type) == FUNCTION_TYPE)
14405 type = apply_memfn_quals (type, memfn_quals, rqual);
14406 else
14407 error ("invalid qualifiers on non-member function type");
14410 if (reqs)
14411 error_at (location_of (reqs), "requires-clause on type-id");
14413 return type;
14415 else if (unqualified_id == NULL_TREE && decl_context != PARM
14416 && decl_context != CATCHPARM
14417 && TREE_CODE (type) != UNION_TYPE
14418 && ! bitfield
14419 && innermost_code != cdk_decomp)
14421 error ("abstract declarator %qT used as declaration", type);
14422 return error_mark_node;
14425 if (!FUNC_OR_METHOD_TYPE_P (type))
14427 /* Only functions may be declared using an operator-function-id. */
14428 if (dname && IDENTIFIER_ANY_OP_P (dname))
14430 error_at (id_loc, "declaration of %qD as non-function", dname);
14431 return error_mark_node;
14434 if (reqs)
14435 error_at (location_of (reqs),
14436 "requires-clause on declaration of non-function type %qT",
14437 type);
14440 /* We don't check parameter types here because we can emit a better
14441 error message later. */
14442 if (decl_context != PARM)
14444 type = check_var_type (unqualified_id, type, id_loc);
14445 if (type == error_mark_node)
14446 return error_mark_node;
14449 /* Now create the decl, which may be a VAR_DECL, a PARM_DECL
14450 or a FUNCTION_DECL, depending on DECL_CONTEXT and TYPE. */
14452 if (decl_context == PARM || decl_context == CATCHPARM)
14454 if (ctype || in_namespace)
14455 error ("cannot use %<::%> in parameter declaration");
14457 tree auto_node = type_uses_auto (type);
14458 if (auto_node && !(cxx_dialect >= cxx17 && template_parm_flag))
14460 bool err_p = true;
14461 if (cxx_dialect >= cxx14)
14463 if (decl_context == PARM && AUTO_IS_DECLTYPE (auto_node))
14464 error_at (typespec_loc,
14465 "cannot declare a parameter with %<decltype(auto)%>");
14466 else if (tree c = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14468 auto_diagnostic_group g;
14469 gcc_rich_location richloc (typespec_loc);
14470 richloc.add_fixit_insert_after ("<>");
14471 error_at (&richloc,
14472 "missing template argument list after %qE; template "
14473 "placeholder not permitted in parameter", c);
14474 if (decl_context == PARM && cxx_dialect >= cxx20)
14475 inform (typespec_loc, "or use %<auto%> for an "
14476 "abbreviated function template");
14477 inform (DECL_SOURCE_LOCATION (c), "%qD declared here", c);
14479 else if (decl_context == CATCHPARM || template_parm_flag)
14480 error_at (typespec_loc,
14481 "%<auto%> parameter not permitted in this context");
14482 else
14483 /* Do not issue an error while tentatively parsing a function
14484 parameter: for T t(auto(a), 42);, when we just saw the 1st
14485 parameter, we don't know yet that this construct won't be
14486 a function declaration. Defer the checking to
14487 cp_parser_parameter_declaration_clause. */
14488 err_p = false;
14490 else
14491 error_at (typespec_loc, "parameter declared %<auto%>");
14492 if (err_p)
14493 type = error_mark_node;
14496 /* A parameter declared as an array of T is really a pointer to T.
14497 One declared as a function is really a pointer to a function.
14498 One declared as a member is really a pointer to member. */
14500 if (TREE_CODE (type) == ARRAY_TYPE)
14502 /* Transfer const-ness of array into that of type pointed to. */
14503 type = build_pointer_type (TREE_TYPE (type));
14504 type_quals = TYPE_UNQUALIFIED;
14505 array_parameter_p = true;
14507 else if (TREE_CODE (type) == FUNCTION_TYPE)
14508 type = build_pointer_type (type);
14511 if (ctype && TREE_CODE (type) == FUNCTION_TYPE && staticp < 2
14512 /* Don't convert xobj member functions to METHOD_TYPE. */
14513 && !is_xobj_member_function
14514 && !(unqualified_id
14515 && identifier_p (unqualified_id)
14516 && IDENTIFIER_NEWDEL_OP_P (unqualified_id)))
14518 cp_cv_quals real_quals = memfn_quals;
14519 if (cxx_dialect < cxx14 && constexpr_p
14520 && sfk != sfk_constructor && sfk != sfk_destructor)
14521 real_quals |= TYPE_QUAL_CONST;
14522 type = build_memfn_type (type, ctype, real_quals, rqual);
14526 tree decl = NULL_TREE;
14528 if (decl_context == PARM)
14530 decl = cp_build_parm_decl (NULL_TREE, unqualified_id, type);
14531 DECL_ARRAY_PARAMETER_P (decl) = array_parameter_p;
14533 bad_specifiers (decl, BSP_PARM, virtualp,
14534 memfn_quals != TYPE_UNQUALIFIED,
14535 inlinep, friendp, raises != NULL_TREE,
14536 declspecs->locations);
14538 else if (decl_context == FIELD)
14540 if (!staticp && !friendp && !FUNC_OR_METHOD_TYPE_P (type))
14541 if (tree auto_node = type_uses_auto (type))
14543 location_t tloc = declspecs->locations[ds_type_spec];
14544 if (CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14545 error_at (tloc, "invalid use of template-name %qE without an "
14546 "argument list",
14547 CLASS_PLACEHOLDER_TEMPLATE (auto_node));
14548 else
14549 error_at (tloc, "non-static data member declared with "
14550 "placeholder %qT", auto_node);
14551 type = error_mark_node;
14554 /* The C99 flexible array extension. */
14555 if (!staticp && TREE_CODE (type) == ARRAY_TYPE
14556 && TYPE_DOMAIN (type) == NULL_TREE)
14558 if (ctype
14559 && (TREE_CODE (ctype) == UNION_TYPE
14560 || TREE_CODE (ctype) == QUAL_UNION_TYPE))
14562 error_at (id_loc, "flexible array member in union");
14563 type = error_mark_node;
14565 else
14567 /* Array is a flexible member. */
14568 if (name)
14569 pedwarn (id_loc, OPT_Wpedantic,
14570 "ISO C++ forbids flexible array member %qs", name);
14571 else
14572 pedwarn (input_location, OPT_Wpedantic,
14573 "ISO C++ forbids flexible array members");
14575 /* Flexible array member has a null domain. */
14576 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
14580 if (type == error_mark_node)
14582 /* Happens when declaring arrays of sizes which
14583 are error_mark_node, for example. */
14584 decl = NULL_TREE;
14586 else if (in_namespace && !friendp)
14588 /* Something like struct S { int N::j; }; */
14589 error_at (id_loc, "invalid use of %<::%>");
14590 return error_mark_node;
14592 else if (FUNC_OR_METHOD_TYPE_P (type) && unqualified_id)
14594 int publicp = 0;
14595 tree function_context;
14597 if (friendp == 0)
14599 /* This should never happen in pure C++ (the check
14600 could be an assert). It could happen in
14601 Objective-C++ if someone writes invalid code that
14602 uses a function declaration for an instance
14603 variable or property (instance variables and
14604 properties are parsed as FIELD_DECLs, but they are
14605 part of an Objective-C class, not a C++ class).
14606 That code is invalid and is caught by this
14607 check. */
14608 if (!ctype)
14610 error ("declaration of function %qD in invalid context",
14611 unqualified_id);
14612 return error_mark_node;
14615 /* ``A union may [ ... ] not [ have ] virtual functions.''
14616 ARM 9.5 */
14617 if (virtualp && TREE_CODE (ctype) == UNION_TYPE)
14619 error_at (declspecs->locations[ds_virtual],
14620 "function %qD declared %<virtual%> inside a union",
14621 unqualified_id);
14622 return error_mark_node;
14625 if (virtualp
14626 && identifier_p (unqualified_id)
14627 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14629 error_at (declspecs->locations[ds_virtual],
14630 "%qD cannot be declared %<virtual%>, since it "
14631 "is always static", unqualified_id);
14632 virtualp = 0;
14636 /* Check that the name used for a destructor makes sense. */
14637 if (sfk == sfk_destructor)
14639 tree uqname = id_declarator->u.id.unqualified_name;
14641 if (!ctype)
14643 gcc_assert (friendp);
14644 error_at (id_loc, "expected qualified name in friend "
14645 "declaration for destructor %qD", uqname);
14646 return error_mark_node;
14649 if (!check_dtor_name (ctype, TREE_OPERAND (uqname, 0)))
14651 error_at (id_loc, "declaration of %qD as member of %qT",
14652 uqname, ctype);
14653 return error_mark_node;
14655 if (concept_p)
14657 error_at (declspecs->locations[ds_concept],
14658 "a destructor cannot be %qs", "concept");
14659 return error_mark_node;
14661 if (constexpr_p && cxx_dialect < cxx20)
14663 error_at (declspecs->locations[ds_constexpr],
14664 "%<constexpr%> destructors only available"
14665 " with %<-std=c++20%> or %<-std=gnu++20%>");
14666 return error_mark_node;
14668 if (consteval_p)
14670 error_at (declspecs->locations[ds_consteval],
14671 "a destructor cannot be %qs", "consteval");
14672 return error_mark_node;
14675 else if (sfk == sfk_constructor && friendp && !ctype)
14677 error ("expected qualified name in friend declaration "
14678 "for constructor %qD",
14679 id_declarator->u.id.unqualified_name);
14680 return error_mark_node;
14682 if (sfk == sfk_constructor)
14683 if (concept_p)
14685 error_at (declspecs->locations[ds_concept],
14686 "a constructor cannot be %<concept%>");
14687 return error_mark_node;
14689 if (concept_p)
14691 error_at (declspecs->locations[ds_concept],
14692 "a concept cannot be a member function");
14693 concept_p = false;
14695 else if (consteval_p
14696 && identifier_p (unqualified_id)
14697 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14699 error_at (declspecs->locations[ds_consteval],
14700 "%qD cannot be %qs", unqualified_id, "consteval");
14701 consteval_p = false;
14704 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14706 tree tmpl = TREE_OPERAND (unqualified_id, 0);
14707 if (variable_template_p (tmpl))
14709 error_at (id_loc, "specialization of variable template "
14710 "%qD declared as function", tmpl);
14711 inform (DECL_SOURCE_LOCATION (tmpl),
14712 "variable template declared here");
14713 return error_mark_node;
14717 /* Tell grokfndecl if it needs to set TREE_PUBLIC on the node. */
14718 function_context
14719 = (ctype != NULL_TREE
14720 ? decl_function_context (TYPE_MAIN_DECL (ctype)) : NULL_TREE);
14721 publicp = ((! friendp || ! staticp)
14722 && function_context == NULL_TREE);
14724 decl = grokfndecl (ctype, type,
14725 TREE_CODE (unqualified_id) != TEMPLATE_ID_EXPR
14726 ? unqualified_id : dname,
14727 parms,
14728 unqualified_id,
14729 declspecs,
14730 reqs,
14731 virtualp, flags, memfn_quals, rqual, raises,
14732 friendp ? -1 : 0, friendp, publicp,
14733 inlinep | (2 * constexpr_p) | (4 * concept_p)
14734 | (8 * consteval_p),
14735 initialized == SD_DELETED,
14736 is_xobj_member_function, sfk,
14737 funcdef_flag, late_return_type_p,
14738 template_count, in_namespace,
14739 attrlist, id_loc);
14740 decl = set_virt_specifiers (decl, virt_specifiers);
14741 if (decl == NULL_TREE)
14742 return error_mark_node;
14743 #if 0
14744 /* This clobbers the attrs stored in `decl' from `attrlist'. */
14745 /* The decl and setting of decl_attr is also turned off. */
14746 decl = build_decl_attribute_variant (decl, decl_attr);
14747 #endif
14749 /* [class.conv.ctor]
14751 A constructor declared without the function-specifier
14752 explicit that can be called with a single parameter
14753 specifies a conversion from the type of its first
14754 parameter to the type of its class. Such a constructor
14755 is called a converting constructor. */
14756 if (explicitp == 2)
14757 DECL_NONCONVERTING_P (decl) = 1;
14759 if (declspecs->explicit_specifier)
14760 store_explicit_specifier (decl, declspecs->explicit_specifier);
14762 else if (!staticp
14763 && ((current_class_type
14764 && same_type_p (type, current_class_type))
14765 || (!dependent_type_p (type)
14766 && !COMPLETE_TYPE_P (complete_type (type))
14767 && (!complete_or_array_type_p (type)
14768 || initialized == SD_UNINITIALIZED))))
14770 if (TREE_CODE (type) != ARRAY_TYPE
14771 || !COMPLETE_TYPE_P (TREE_TYPE (type)))
14773 if (unqualified_id)
14775 error_at (id_loc, "field %qD has incomplete type %qT",
14776 unqualified_id, type);
14777 cxx_incomplete_type_inform (strip_array_types (type));
14779 else
14780 error ("name %qT has incomplete type", type);
14782 type = error_mark_node;
14783 decl = NULL_TREE;
14786 else if (!verify_type_context (input_location,
14787 staticp
14788 ? TCTX_STATIC_STORAGE
14789 : TCTX_FIELD, type))
14791 type = error_mark_node;
14792 decl = NULL_TREE;
14794 else
14796 if (friendp)
14798 if (unqualified_id)
14799 error_at (id_loc,
14800 "%qE is neither function nor member function; "
14801 "cannot be declared friend", unqualified_id);
14802 else
14803 error ("unnamed field is neither function nor member "
14804 "function; cannot be declared friend");
14805 return error_mark_node;
14807 decl = NULL_TREE;
14810 if (friendp)
14812 /* Packages tend to use GNU attributes on friends, so we only
14813 warn for standard attributes. */
14814 if (attrlist
14815 && !funcdef_flag
14816 && cxx11_attribute_p (*attrlist)
14817 && !all_attributes_are_contracts_p (*attrlist))
14819 *attrlist = NULL_TREE;
14820 if (warning_at (id_loc, OPT_Wattributes, "attribute ignored"))
14821 inform (id_loc, "an attribute that appertains to a friend "
14822 "declaration that is not a definition is ignored");
14824 /* Friends are treated specially. */
14825 if (ctype == current_class_type)
14826 ; /* We already issued a permerror. */
14827 else if (decl && DECL_NAME (decl))
14829 set_originating_module (decl, true);
14831 if (initialized)
14832 /* Kludge: We need funcdef_flag to be true in do_friend for
14833 in-class defaulted functions, but that breaks grokfndecl.
14834 So set it here. */
14835 funcdef_flag = true;
14837 cplus_decl_attributes (&decl, *attrlist, 0);
14838 *attrlist = NULL_TREE;
14840 tree scope = ctype ? ctype : in_namespace;
14841 decl = do_friend (scope, unqualified_id, decl,
14842 flags, funcdef_flag);
14843 return decl;
14845 else
14846 return error_mark_node;
14849 /* Structure field. It may not be a function, except for C++. */
14851 if (decl == NULL_TREE)
14853 if (staticp)
14855 /* C++ allows static class members. All other work
14856 for this is done by grokfield. */
14857 decl = build_lang_decl_loc (id_loc, VAR_DECL,
14858 dname, type);
14859 if (unqualified_id
14860 && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14862 decl = check_explicit_specialization (unqualified_id, decl,
14863 template_count,
14864 concept_p * 8);
14865 if (decl == error_mark_node)
14866 return error_mark_node;
14868 set_linkage_for_static_data_member (decl);
14869 if (concept_p)
14870 error_at (declspecs->locations[ds_concept],
14871 "static data member %qE declared %qs",
14872 unqualified_id, "concept");
14873 else if (constexpr_p && !initialized)
14875 error_at (DECL_SOURCE_LOCATION (decl),
14876 "%<constexpr%> static data member %qD must "
14877 "have an initializer", decl);
14878 constexpr_p = false;
14880 if (consteval_p)
14881 error_at (declspecs->locations[ds_consteval],
14882 "static data member %qE declared %qs",
14883 unqualified_id, "consteval");
14885 if (inlinep)
14886 mark_inline_variable (decl, declspecs->locations[ds_inline]);
14888 if (!DECL_VAR_DECLARED_INLINE_P (decl)
14889 && !(cxx_dialect >= cxx17 && constexpr_p))
14890 /* Even if there is an in-class initialization, DECL
14891 is considered undefined until an out-of-class
14892 definition is provided, unless this is an inline
14893 variable. */
14894 DECL_EXTERNAL (decl) = 1;
14896 if (thread_p)
14898 CP_DECL_THREAD_LOCAL_P (decl) = true;
14899 if (!processing_template_decl)
14900 set_decl_tls_model (decl, decl_default_tls_model (decl));
14901 if (declspecs->gnu_thread_keyword_p)
14902 SET_DECL_GNU_TLS_P (decl);
14905 /* Set the constraints on the declaration. */
14906 bool memtmpl = (current_template_depth
14907 > template_class_depth (current_class_type));
14908 if (memtmpl)
14910 tree ci = current_template_constraints ();
14911 set_constraints (decl, ci);
14914 else
14916 if (concept_p)
14918 error_at (declspecs->locations[ds_concept],
14919 "non-static data member %qE declared %qs",
14920 unqualified_id, "concept");
14921 concept_p = false;
14922 constexpr_p = false;
14924 else if (constexpr_p)
14926 error_at (declspecs->locations[ds_constexpr],
14927 "non-static data member %qE declared %qs",
14928 unqualified_id, "constexpr");
14929 constexpr_p = false;
14931 if (constinit_p)
14933 error_at (declspecs->locations[ds_constinit],
14934 "non-static data member %qE declared %qs",
14935 unqualified_id, "constinit");
14936 constinit_p = false;
14938 if (consteval_p)
14940 error_at (declspecs->locations[ds_consteval],
14941 "non-static data member %qE declared %qs",
14942 unqualified_id, "consteval");
14943 consteval_p = false;
14945 decl = build_decl (id_loc, FIELD_DECL, unqualified_id, type);
14946 DECL_NONADDRESSABLE_P (decl) = bitfield;
14947 if (bitfield && !unqualified_id)
14948 DECL_PADDING_P (decl) = 1;
14950 if (storage_class == sc_mutable)
14952 DECL_MUTABLE_P (decl) = 1;
14953 storage_class = sc_none;
14956 if (initialized)
14958 /* An attempt is being made to initialize a non-static
14959 member. This is new in C++11. */
14960 maybe_warn_cpp0x (CPP0X_NSDMI, init_loc);
14962 /* If this has been parsed with static storage class, but
14963 errors forced staticp to be cleared, ensure NSDMI is
14964 not present. */
14965 if (declspecs->storage_class == sc_static)
14966 DECL_INITIAL (decl) = error_mark_node;
14970 bad_specifiers (decl, BSP_FIELD, virtualp,
14971 memfn_quals != TYPE_UNQUALIFIED,
14972 staticp ? false : inlinep, friendp,
14973 raises != NULL_TREE,
14974 declspecs->locations);
14977 else if (FUNC_OR_METHOD_TYPE_P (type))
14979 tree original_name;
14980 int publicp = 0;
14982 if (!unqualified_id)
14983 return error_mark_node;
14985 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14986 original_name = dname;
14987 else
14988 original_name = unqualified_id;
14989 // FIXME:gcc_assert (original_name == dname);
14991 if (storage_class == sc_auto)
14992 error_at (declspecs->locations[ds_storage_class],
14993 "storage class %<auto%> invalid for function %qs", name);
14994 else if (storage_class == sc_register)
14995 error_at (declspecs->locations[ds_storage_class],
14996 "storage class %<register%> invalid for function %qs",
14997 name);
14998 else if (thread_p)
15000 if (declspecs->gnu_thread_keyword_p)
15001 error_at (declspecs->locations[ds_thread],
15002 "storage class %<__thread%> invalid for function %qs",
15003 name);
15004 else
15005 error_at (declspecs->locations[ds_thread],
15006 "storage class %<thread_local%> invalid for "
15007 "function %qs", name);
15009 else if (constinit_p)
15010 error_at (declspecs->locations[ds_constinit],
15011 "%<constinit%> specifier invalid for function %qs", name);
15013 if (virt_specifiers)
15014 error ("virt-specifiers in %qs not allowed outside a class "
15015 "definition", name);
15016 /* Function declaration not at top level.
15017 Storage classes other than `extern' are not allowed
15018 and `extern' makes no difference. */
15019 if (! toplevel_bindings_p ()
15020 && (storage_class == sc_static
15021 || decl_spec_seq_has_spec_p (declspecs, ds_inline))
15022 && pedantic)
15024 if (storage_class == sc_static)
15025 pedwarn (declspecs->locations[ds_storage_class], OPT_Wpedantic,
15026 "%<static%> specifier invalid for function %qs "
15027 "declared out of global scope", name);
15028 else
15029 pedwarn (declspecs->locations[ds_inline], OPT_Wpedantic,
15030 "%<inline%> specifier invalid for function %qs "
15031 "declared out of global scope", name);
15034 if (ctype == NULL_TREE)
15036 if (virtualp)
15038 error ("virtual non-class function %qs", name);
15039 virtualp = 0;
15041 else if (sfk == sfk_constructor
15042 || sfk == sfk_destructor)
15044 error (funcdef_flag
15045 ? G_("%qs defined in a non-class scope")
15046 : G_("%qs declared in a non-class scope"), name);
15047 sfk = sfk_none;
15050 if (consteval_p
15051 && identifier_p (unqualified_id)
15052 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
15054 error_at (declspecs->locations[ds_consteval],
15055 "%qD cannot be %qs", unqualified_id, "consteval");
15056 consteval_p = false;
15059 /* Record whether the function is public. */
15060 publicp = (ctype != NULL_TREE
15061 || storage_class != sc_static);
15063 decl = grokfndecl (ctype, type, original_name, parms, unqualified_id,
15064 declspecs,
15065 reqs, virtualp, flags, memfn_quals, rqual, raises,
15066 1, friendp,
15067 publicp,
15068 inlinep | (2 * constexpr_p) | (4 * concept_p)
15069 | (8 * consteval_p),
15070 initialized == SD_DELETED,
15071 is_xobj_member_function, sfk,
15072 funcdef_flag,
15073 late_return_type_p,
15074 template_count, in_namespace, attrlist,
15075 id_loc);
15076 if (decl == NULL_TREE)
15077 return error_mark_node;
15079 if (explicitp == 2)
15080 DECL_NONCONVERTING_P (decl) = 1;
15081 if (staticp == 1)
15083 int invalid_static = 0;
15085 /* Don't allow a static member function in a class, and forbid
15086 declaring main to be static. */
15087 if (TREE_CODE (type) == METHOD_TYPE)
15089 permerror (input_location, "cannot declare member function %qD to have "
15090 "static linkage", decl);
15091 invalid_static = 1;
15093 else if (current_function_decl)
15095 /* 7.1.1: There can be no static function declarations within a
15096 block. */
15097 error_at (declspecs->locations[ds_storage_class],
15098 "cannot declare static function inside another function");
15099 invalid_static = 1;
15102 if (invalid_static)
15104 staticp = 0;
15105 storage_class = sc_none;
15108 if (declspecs->explicit_specifier)
15109 store_explicit_specifier (decl, declspecs->explicit_specifier);
15111 else
15113 /* It's a variable. */
15115 /* An uninitialized decl with `extern' is a reference. */
15116 decl = grokvardecl (type, dname, unqualified_id,
15117 declspecs,
15118 initialized,
15119 type_quals,
15120 inlinep,
15121 concept_p,
15122 template_count,
15123 ctype ? ctype : in_namespace,
15124 id_loc);
15125 if (decl == NULL_TREE)
15126 return error_mark_node;
15128 bad_specifiers (decl, BSP_VAR, virtualp,
15129 memfn_quals != TYPE_UNQUALIFIED,
15130 inlinep, friendp, raises != NULL_TREE,
15131 declspecs->locations);
15133 if (ctype)
15135 DECL_CONTEXT (decl) = ctype;
15136 if (staticp == 1)
15138 permerror (declspecs->locations[ds_storage_class],
15139 "%<static%> may not be used when defining "
15140 "(as opposed to declaring) a static data member");
15141 staticp = 0;
15142 storage_class = sc_none;
15144 if (storage_class == sc_register && TREE_STATIC (decl))
15146 error ("static member %qD declared %<register%>", decl);
15147 storage_class = sc_none;
15149 if (storage_class == sc_extern && pedantic)
15151 pedwarn (input_location, OPT_Wpedantic,
15152 "cannot explicitly declare member %q#D to have "
15153 "extern linkage", decl);
15154 storage_class = sc_none;
15157 else if (constexpr_p && DECL_EXTERNAL (decl))
15159 error_at (DECL_SOURCE_LOCATION (decl),
15160 "declaration of %<constexpr%> variable %qD "
15161 "is not a definition", decl);
15162 constexpr_p = false;
15164 if (consteval_p)
15166 error_at (DECL_SOURCE_LOCATION (decl),
15167 "a variable cannot be declared %<consteval%>");
15168 consteval_p = false;
15171 if (inlinep)
15172 mark_inline_variable (decl, declspecs->locations[ds_inline]);
15173 if (innermost_code == cdk_decomp)
15175 gcc_assert (declarator && declarator->kind == cdk_decomp);
15176 DECL_SOURCE_LOCATION (decl) = id_loc;
15177 DECL_ARTIFICIAL (decl) = 1;
15178 fit_decomposition_lang_decl (decl, NULL_TREE);
15182 if (VAR_P (decl) && !initialized)
15183 if (tree auto_node = type_uses_auto (type))
15184 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
15186 location_t loc = declspecs->locations[ds_type_spec];
15187 error_at (loc, "declaration of %q#D has no initializer", decl);
15188 TREE_TYPE (decl) = error_mark_node;
15191 if (storage_class == sc_extern && initialized && !funcdef_flag)
15193 if (toplevel_bindings_p ())
15195 /* It's common practice (and completely valid) to have a const
15196 be initialized and declared extern. */
15197 if (!(type_quals & TYPE_QUAL_CONST))
15198 warning_at (DECL_SOURCE_LOCATION (decl), 0,
15199 "%qs initialized and declared %<extern%>", name);
15201 else
15203 error_at (DECL_SOURCE_LOCATION (decl),
15204 "%qs has both %<extern%> and initializer", name);
15205 return error_mark_node;
15209 /* Record `register' declaration for warnings on &
15210 and in case doing stupid register allocation. */
15212 if (storage_class == sc_register)
15214 DECL_REGISTER (decl) = 1;
15215 /* Warn about register storage specifiers on PARM_DECLs. */
15216 if (TREE_CODE (decl) == PARM_DECL)
15218 if (cxx_dialect >= cxx17)
15219 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
15220 "ISO C++17 does not allow %<register%> storage "
15221 "class specifier");
15222 else
15223 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
15224 "%<register%> storage class specifier used");
15227 else if (storage_class == sc_extern)
15228 DECL_THIS_EXTERN (decl) = 1;
15229 else if (storage_class == sc_static)
15230 DECL_THIS_STATIC (decl) = 1;
15232 if (VAR_P (decl))
15234 /* Set constexpr flag on vars (functions got it in grokfndecl). */
15235 if (constexpr_p)
15236 DECL_DECLARED_CONSTEXPR_P (decl) = true;
15237 /* And the constinit flag (which only applies to variables). */
15238 else if (constinit_p)
15239 DECL_DECLARED_CONSTINIT_P (decl) = true;
15241 else if (TREE_CODE (decl) == FUNCTION_DECL)
15243 /* If we saw a return type, record its location. */
15244 location_t loc = declspecs->locations[ds_type_spec];
15245 if (loc == UNKNOWN_LOCATION)
15246 /* Build DECL_RESULT in start_preparsed_function. */;
15247 else if (!DECL_RESULT (decl))
15249 tree restype = TREE_TYPE (TREE_TYPE (decl));
15250 tree resdecl = build_decl (loc, RESULT_DECL, 0, restype);
15251 DECL_ARTIFICIAL (resdecl) = 1;
15252 DECL_IGNORED_P (resdecl) = 1;
15253 DECL_RESULT (decl) = resdecl;
15255 else if (funcdef_flag)
15256 DECL_SOURCE_LOCATION (DECL_RESULT (decl)) = loc;
15259 /* Record constancy and volatility on the DECL itself . There's
15260 no need to do this when processing a template; we'll do this
15261 for the instantiated declaration based on the type of DECL. */
15262 if (!processing_template_decl)
15263 cp_apply_type_quals_to_decl (type_quals, decl);
15265 return decl;
15269 /* Subroutine of start_function. Ensure that each of the parameter
15270 types (as listed in PARMS) is complete, as is required for a
15271 function definition. */
15273 static void
15274 require_complete_types_for_parms (tree parms)
15276 for (; parms; parms = DECL_CHAIN (parms))
15278 if (dependent_type_p (TREE_TYPE (parms)))
15279 continue;
15280 if (!VOID_TYPE_P (TREE_TYPE (parms))
15281 && complete_type_or_else (TREE_TYPE (parms), parms))
15283 relayout_decl (parms);
15284 DECL_ARG_TYPE (parms) = type_passed_as (TREE_TYPE (parms));
15286 abstract_virtuals_error (parms, TREE_TYPE (parms));
15287 maybe_warn_parm_abi (TREE_TYPE (parms),
15288 DECL_SOURCE_LOCATION (parms));
15290 else
15291 /* grokparms or complete_type_or_else will have already issued
15292 an error. */
15293 TREE_TYPE (parms) = error_mark_node;
15297 /* Returns nonzero if T is a local variable. */
15300 local_variable_p (const_tree t)
15302 if ((VAR_P (t)
15303 && (DECL_LOCAL_DECL_P (t)
15304 || !DECL_CONTEXT (t)
15305 || TREE_CODE (DECL_CONTEXT (t)) == FUNCTION_DECL))
15306 || (TREE_CODE (t) == PARM_DECL))
15307 return 1;
15309 return 0;
15312 /* Like local_variable_p, but suitable for use as a tree-walking
15313 function. */
15315 static tree
15316 local_variable_p_walkfn (tree *tp, int *walk_subtrees,
15317 void * /*data*/)
15319 if (unevaluated_p (TREE_CODE (*tp)))
15321 /* DR 2082 permits local variables in unevaluated contexts
15322 within a default argument. */
15323 *walk_subtrees = 0;
15324 return NULL_TREE;
15327 if (local_variable_p (*tp)
15328 && (!DECL_ARTIFICIAL (*tp) || DECL_NAME (*tp) == this_identifier))
15329 return *tp;
15330 else if (TYPE_P (*tp))
15331 *walk_subtrees = 0;
15333 return NULL_TREE;
15336 /* Check that ARG, which is a default-argument expression for a
15337 parameter DECL, is valid. Returns ARG, or ERROR_MARK_NODE, if
15338 something goes wrong. DECL may also be a _TYPE node, rather than a
15339 DECL, if there is no DECL available. */
15341 tree
15342 check_default_argument (tree decl, tree arg, tsubst_flags_t complain)
15344 tree var;
15345 tree decl_type;
15347 if (TREE_CODE (arg) == DEFERRED_PARSE)
15348 /* We get a DEFERRED_PARSE when looking at an in-class declaration
15349 with a default argument. Ignore the argument for now; we'll
15350 deal with it after the class is complete. */
15351 return arg;
15353 if (TYPE_P (decl))
15355 decl_type = decl;
15356 decl = NULL_TREE;
15358 else
15359 decl_type = TREE_TYPE (decl);
15361 if (arg == error_mark_node
15362 || decl == error_mark_node
15363 || TREE_TYPE (arg) == error_mark_node
15364 || decl_type == error_mark_node)
15365 /* Something already went wrong. There's no need to check
15366 further. */
15367 return error_mark_node;
15369 /* [dcl.fct.default]
15371 A default argument expression is implicitly converted to the
15372 parameter type. */
15373 ++cp_unevaluated_operand;
15374 /* Avoid digest_init clobbering the initializer. */
15375 tree carg = BRACE_ENCLOSED_INITIALIZER_P (arg) ? unshare_expr (arg): arg;
15376 perform_implicit_conversion_flags (decl_type, carg, complain,
15377 LOOKUP_IMPLICIT);
15378 --cp_unevaluated_operand;
15380 /* Avoid redundant -Wzero-as-null-pointer-constant warnings at
15381 the call sites. */
15382 if (TYPE_PTR_OR_PTRMEM_P (decl_type)
15383 && null_ptr_cst_p (arg)
15384 /* Don't lose side-effects as in PR90473. */
15385 && !TREE_SIDE_EFFECTS (arg))
15386 return nullptr_node;
15388 /* [dcl.fct.default]
15390 Local variables shall not be used in default argument
15391 expressions.
15393 The keyword `this' shall not be used in a default argument of a
15394 member function. */
15395 var = cp_walk_tree_without_duplicates (&arg, local_variable_p_walkfn, NULL);
15396 if (var)
15398 if (complain & tf_warning_or_error)
15400 if (DECL_NAME (var) == this_identifier)
15401 permerror (input_location, "default argument %qE uses %qD",
15402 arg, var);
15403 else
15404 error ("default argument %qE uses local variable %qD", arg, var);
15406 return error_mark_node;
15409 /* All is well. */
15410 return arg;
15413 /* Returns a deprecated type used within TYPE, or NULL_TREE if none. */
15415 static tree
15416 type_is_deprecated (tree type)
15418 enum tree_code code;
15419 if (TREE_DEPRECATED (type))
15420 return type;
15421 if (TYPE_NAME (type))
15423 if (TREE_DEPRECATED (TYPE_NAME (type)))
15424 return type;
15425 else
15427 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
15428 return NULL_TREE;
15432 /* Do warn about using typedefs to a deprecated class. */
15433 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
15434 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
15436 code = TREE_CODE (type);
15438 if (code == POINTER_TYPE || code == REFERENCE_TYPE
15439 || code == OFFSET_TYPE || code == FUNCTION_TYPE
15440 || code == METHOD_TYPE || code == ARRAY_TYPE)
15441 return type_is_deprecated (TREE_TYPE (type));
15443 if (TYPE_PTRMEMFUNC_P (type))
15444 return type_is_deprecated
15445 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
15447 return NULL_TREE;
15450 /* Returns an unavailable type used within TYPE, or NULL_TREE if none. */
15452 static tree
15453 type_is_unavailable (tree type)
15455 enum tree_code code;
15456 if (TREE_UNAVAILABLE (type))
15457 return type;
15458 if (TYPE_NAME (type))
15460 if (TREE_UNAVAILABLE (TYPE_NAME (type)))
15461 return type;
15462 else
15464 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
15465 return NULL_TREE;
15469 /* Do warn about using typedefs to a deprecated class. */
15470 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
15471 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
15473 code = TREE_CODE (type);
15475 if (code == POINTER_TYPE || code == REFERENCE_TYPE
15476 || code == OFFSET_TYPE || code == FUNCTION_TYPE
15477 || code == METHOD_TYPE || code == ARRAY_TYPE)
15478 return type_is_unavailable (TREE_TYPE (type));
15480 if (TYPE_PTRMEMFUNC_P (type))
15481 return type_is_unavailable
15482 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
15484 return NULL_TREE;
15487 /* Decode the list of parameter types for a function type.
15488 Given the list of things declared inside the parens,
15489 return a list of types.
15491 If this parameter does not end with an ellipsis, we append
15492 void_list_node.
15494 *PARMS is set to the chain of PARM_DECLs created. */
15496 tree
15497 grokparms (tree parmlist, tree *parms)
15499 tree result = NULL_TREE;
15500 tree decls = NULL_TREE;
15501 tree parm;
15502 int any_error = 0;
15504 for (parm = parmlist; parm != NULL_TREE; parm = TREE_CHAIN (parm))
15506 tree type = NULL_TREE;
15507 tree init = TREE_PURPOSE (parm);
15508 tree decl = TREE_VALUE (parm);
15510 if (parm == void_list_node || parm == explicit_void_list_node)
15511 break;
15513 if (! decl || TREE_TYPE (decl) == error_mark_node)
15515 any_error = 1;
15516 continue;
15519 type = TREE_TYPE (decl);
15520 if (VOID_TYPE_P (type))
15522 if (same_type_p (type, void_type_node)
15523 && !init
15524 && !DECL_NAME (decl) && !result
15525 && TREE_CHAIN (parm) == void_list_node)
15526 /* DR 577: A parameter list consisting of a single
15527 unnamed parameter of non-dependent type 'void'. */
15528 break;
15529 else if (cv_qualified_p (type))
15530 error_at (DECL_SOURCE_LOCATION (decl),
15531 "invalid use of cv-qualified type %qT in "
15532 "parameter declaration", type);
15533 else
15534 error_at (DECL_SOURCE_LOCATION (decl),
15535 "invalid use of type %<void%> in parameter "
15536 "declaration");
15537 /* It's not a good idea to actually create parameters of
15538 type `void'; other parts of the compiler assume that a
15539 void type terminates the parameter list. */
15540 type = error_mark_node;
15541 TREE_TYPE (decl) = error_mark_node;
15544 if (type != error_mark_node)
15546 if (deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
15548 tree unavailtype = type_is_unavailable (type);
15549 if (unavailtype)
15550 cp_handle_deprecated_or_unavailable (unavailtype);
15552 if (deprecated_state != DEPRECATED_SUPPRESS
15553 && deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
15555 tree deptype = type_is_deprecated (type);
15556 if (deptype)
15557 cp_handle_deprecated_or_unavailable (deptype);
15560 /* [dcl.fct] "A parameter with volatile-qualified type is
15561 deprecated." */
15562 if (CP_TYPE_VOLATILE_P (type))
15563 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wvolatile,
15564 "%<volatile%>-qualified parameter is "
15565 "deprecated");
15567 /* Top-level qualifiers on the parameters are
15568 ignored for function types. */
15569 type = cp_build_qualified_type (type, 0);
15570 if (TREE_CODE (type) == METHOD_TYPE)
15572 error ("parameter %qD invalidly declared method type", decl);
15573 type = build_pointer_type (type);
15574 TREE_TYPE (decl) = type;
15576 else if (cxx_dialect < cxx17 && INDIRECT_TYPE_P (type))
15578 /* Before C++17 DR 393:
15579 [dcl.fct]/6, parameter types cannot contain pointers
15580 (references) to arrays of unknown bound. */
15581 tree t = TREE_TYPE (type);
15582 int ptr = TYPE_PTR_P (type);
15584 while (1)
15586 if (TYPE_PTR_P (t))
15587 ptr = 1;
15588 else if (TREE_CODE (t) != ARRAY_TYPE)
15589 break;
15590 else if (!TYPE_DOMAIN (t))
15591 break;
15592 t = TREE_TYPE (t);
15594 if (TREE_CODE (t) == ARRAY_TYPE)
15595 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
15597 ? G_("parameter %qD includes pointer to array of "
15598 "unknown bound %qT")
15599 : G_("parameter %qD includes reference to array of "
15600 "unknown bound %qT"),
15601 decl, t);
15604 if (init && !processing_template_decl)
15605 init = check_default_argument (decl, init, tf_warning_or_error);
15608 DECL_CHAIN (decl) = decls;
15609 decls = decl;
15610 result = tree_cons (init, type, result);
15612 decls = nreverse (decls);
15613 result = nreverse (result);
15614 if (parm)
15615 result = chainon (result, void_list_node);
15616 *parms = decls;
15617 if (any_error)
15618 result = NULL_TREE;
15620 if (any_error)
15621 /* We had parm errors, recover by giving the function (...) type. */
15622 result = NULL_TREE;
15624 return result;
15628 /* D is a constructor or overloaded `operator='.
15630 Let T be the class in which D is declared. Then, this function
15631 returns:
15633 -1 if D's is an ill-formed constructor or copy assignment operator
15634 whose first parameter is of type `T'.
15635 0 if D is not a copy constructor or copy assignment
15636 operator.
15637 1 if D is a copy constructor or copy assignment operator whose
15638 first parameter is a reference to non-const qualified T.
15639 2 if D is a copy constructor or copy assignment operator whose
15640 first parameter is a reference to const qualified T.
15642 This function can be used as a predicate. Positive values indicate
15643 a copy constructor and nonzero values indicate a copy assignment
15644 operator. */
15647 copy_fn_p (const_tree d)
15649 tree args;
15650 tree arg_type;
15651 int result = 1;
15653 gcc_assert (DECL_FUNCTION_MEMBER_P (d));
15655 if (TREE_CODE (d) == TEMPLATE_DECL
15656 || (DECL_TEMPLATE_INFO (d)
15657 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
15658 /* Instantiations of template member functions are never copy
15659 functions. Note that member functions of templated classes are
15660 represented as template functions internally, and we must
15661 accept those as copy functions. */
15662 return 0;
15664 if (!DECL_CONSTRUCTOR_P (d)
15665 && DECL_NAME (d) != assign_op_identifier)
15666 return 0;
15668 if (DECL_XOBJ_MEMBER_FUNCTION_P (d))
15670 tree object_param = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (d)));
15671 if (!TYPE_REF_P (object_param)
15672 || TYPE_REF_IS_RVALUE (object_param)
15673 /* Reject unrelated object parameters. */
15674 || TYPE_MAIN_VARIANT (TREE_TYPE (object_param)) != DECL_CONTEXT (d)
15675 || CP_TYPE_CONST_P (TREE_TYPE (object_param)))
15676 return 0;
15677 args = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (d)));
15679 else
15680 args = FUNCTION_FIRST_USER_PARMTYPE (d);
15681 if (!args)
15682 return 0;
15684 arg_type = TREE_VALUE (args);
15685 if (arg_type == error_mark_node)
15686 return 0;
15688 if (TYPE_MAIN_VARIANT (arg_type) == DECL_CONTEXT (d))
15690 /* Pass by value copy assignment operator. */
15691 result = -1;
15693 else if (TYPE_REF_P (arg_type)
15694 && !TYPE_REF_IS_RVALUE (arg_type)
15695 && TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)) == DECL_CONTEXT (d))
15697 if (CP_TYPE_CONST_P (TREE_TYPE (arg_type)))
15698 result = 2;
15700 else
15701 return 0;
15703 args = TREE_CHAIN (args);
15705 if (args && args != void_list_node && !TREE_PURPOSE (args))
15706 /* There are more non-optional args. */
15707 return 0;
15709 return result;
15712 /* D is a constructor or overloaded `operator='.
15714 Let T be the class in which D is declared. Then, this function
15715 returns true when D is a move constructor or move assignment
15716 operator, false otherwise. */
15718 bool
15719 move_fn_p (const_tree d)
15721 if (cxx_dialect == cxx98)
15722 /* There are no move constructors if we are in C++98 mode. */
15723 return false;
15725 if (TREE_CODE (d) == TEMPLATE_DECL
15726 || (DECL_TEMPLATE_INFO (d)
15727 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
15728 /* Instantiations of template member functions are never move
15729 functions. Note that member functions of templated classes are
15730 represented as template functions internally, and we must
15731 accept those as move functions. */
15732 return 0;
15734 return move_signature_fn_p (d);
15737 /* D is a constructor or overloaded `operator='.
15739 Then, this function returns true when D has the same signature as a move
15740 constructor or move assignment operator (because either it is such a
15741 ctor/op= or it is a template specialization with the same signature),
15742 false otherwise. */
15744 bool
15745 move_signature_fn_p (const_tree d)
15747 tree args;
15748 tree arg_type;
15749 bool result = false;
15751 if (!DECL_CONSTRUCTOR_P (d)
15752 && DECL_NAME (d) != assign_op_identifier)
15753 return 0;
15755 if (DECL_XOBJ_MEMBER_FUNCTION_P (d))
15757 tree object_param = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (d)));
15758 if (!TYPE_REF_P (object_param)
15759 || TYPE_REF_IS_RVALUE (object_param)
15760 /* Reject unrelated object parameters. */
15761 || TYPE_MAIN_VARIANT (TREE_TYPE (object_param)) != DECL_CONTEXT (d)
15762 || CP_TYPE_CONST_P (TREE_TYPE (object_param)))
15763 return 0;
15764 args = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (d)));
15766 else
15767 args = FUNCTION_FIRST_USER_PARMTYPE (d);
15768 if (!args)
15769 return 0;
15771 arg_type = TREE_VALUE (args);
15772 if (arg_type == error_mark_node)
15773 return 0;
15775 if (TYPE_REF_P (arg_type)
15776 && TYPE_REF_IS_RVALUE (arg_type)
15777 && same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)),
15778 DECL_CONTEXT (d)))
15779 result = true;
15781 args = TREE_CHAIN (args);
15783 if (args && args != void_list_node && !TREE_PURPOSE (args))
15784 /* There are more non-optional args. */
15785 return false;
15787 return result;
15790 /* Remember any special properties of member function DECL. */
15792 void
15793 grok_special_member_properties (tree decl)
15795 tree class_type;
15797 if (TREE_CODE (decl) == USING_DECL
15798 || !DECL_OBJECT_MEMBER_FUNCTION_P (decl))
15799 return;
15801 class_type = DECL_CONTEXT (decl);
15802 if (IDENTIFIER_CTOR_P (DECL_NAME (decl)))
15804 int ctor = copy_fn_p (decl);
15806 if (!DECL_ARTIFICIAL (decl))
15807 TYPE_HAS_USER_CONSTRUCTOR (class_type) = 1;
15809 if (ctor > 0)
15811 /* [class.copy]
15813 A non-template constructor for class X is a copy
15814 constructor if its first parameter is of type X&, const
15815 X&, volatile X& or const volatile X&, and either there
15816 are no other parameters or else all other parameters have
15817 default arguments. */
15818 TYPE_HAS_COPY_CTOR (class_type) = 1;
15819 if (ctor > 1)
15820 TYPE_HAS_CONST_COPY_CTOR (class_type) = 1;
15823 if (sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (decl)))
15824 TYPE_HAS_DEFAULT_CONSTRUCTOR (class_type) = 1;
15826 if (is_list_ctor (decl))
15827 TYPE_HAS_LIST_CTOR (class_type) = 1;
15829 if (maybe_constexpr_fn (decl)
15830 && !ctor && !move_fn_p (decl))
15831 TYPE_HAS_CONSTEXPR_CTOR (class_type) = 1;
15833 else if (DECL_NAME (decl) == assign_op_identifier)
15835 /* [class.copy]
15837 A non-template assignment operator for class X is a copy
15838 assignment operator if its parameter is of type X, X&, const
15839 X&, volatile X& or const volatile X&. */
15841 int assop = copy_fn_p (decl);
15843 if (assop)
15845 TYPE_HAS_COPY_ASSIGN (class_type) = 1;
15846 if (assop != 1)
15847 TYPE_HAS_CONST_COPY_ASSIGN (class_type) = 1;
15850 else if (IDENTIFIER_CONV_OP_P (DECL_NAME (decl)))
15851 TYPE_HAS_CONVERSION (class_type) = true;
15853 /* Destructors are handled in check_methods. */
15856 /* Check a constructor DECL has the correct form. Complains
15857 if the class has a constructor of the form X(X). */
15859 bool
15860 grok_ctor_properties (const_tree ctype, const_tree decl)
15862 int ctor_parm = copy_fn_p (decl);
15864 if (ctor_parm < 0)
15866 /* [class.copy]
15868 A declaration of a constructor for a class X is ill-formed if
15869 its first parameter is of type (optionally cv-qualified) X
15870 and either there are no other parameters or else all other
15871 parameters have default arguments.
15873 We *don't* complain about member template instantiations that
15874 have this form, though; they can occur as we try to decide
15875 what constructor to use during overload resolution. Since
15876 overload resolution will never prefer such a constructor to
15877 the non-template copy constructor (which is either explicitly
15878 or implicitly defined), there's no need to worry about their
15879 existence. Theoretically, they should never even be
15880 instantiated, but that's hard to forestall. */
15881 error_at (DECL_SOURCE_LOCATION (decl),
15882 "invalid constructor; you probably meant %<%T (const %T&)%>",
15883 ctype, ctype);
15884 return false;
15887 return true;
15890 /* DECL is a declaration for an overloaded or conversion operator. If
15891 COMPLAIN is true, errors are issued for invalid declarations. */
15893 bool
15894 grok_op_properties (tree decl, bool complain)
15896 tree argtypes = TYPE_ARG_TYPES (TREE_TYPE (decl));
15897 bool const methodp = DECL_IOBJ_MEMBER_FUNCTION_P (decl);
15898 tree name = DECL_NAME (decl);
15899 location_t loc = DECL_SOURCE_LOCATION (decl);
15901 tree class_type = DECL_CONTEXT (decl);
15902 if (class_type && !CLASS_TYPE_P (class_type))
15903 class_type = NULL_TREE;
15905 tree_code operator_code;
15906 unsigned op_flags;
15907 if (IDENTIFIER_CONV_OP_P (name))
15909 /* Conversion operators are TYPE_EXPR for the purposes of this
15910 function. */
15911 operator_code = TYPE_EXPR;
15912 op_flags = OVL_OP_FLAG_UNARY;
15914 else
15916 const ovl_op_info_t *ovl_op = IDENTIFIER_OVL_OP_INFO (name);
15918 operator_code = ovl_op->tree_code;
15919 op_flags = ovl_op->flags;
15920 gcc_checking_assert (operator_code != ERROR_MARK);
15921 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
15924 if (op_flags & OVL_OP_FLAG_ALLOC)
15926 /* operator new and operator delete are quite special. */
15927 if (class_type)
15928 switch (op_flags)
15930 case OVL_OP_FLAG_ALLOC:
15931 TYPE_HAS_NEW_OPERATOR (class_type) = 1;
15932 break;
15934 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE:
15935 TYPE_GETS_DELETE (class_type) |= 1;
15936 break;
15938 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_VEC:
15939 TYPE_HAS_ARRAY_NEW_OPERATOR (class_type) = 1;
15940 break;
15942 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE | OVL_OP_FLAG_VEC:
15943 TYPE_GETS_DELETE (class_type) |= 2;
15944 break;
15946 default:
15947 gcc_unreachable ();
15950 /* [basic.std.dynamic.allocation]/1:
15952 A program is ill-formed if an allocation function is declared
15953 in a namespace scope other than global scope or declared
15954 static in global scope.
15956 The same also holds true for deallocation functions. */
15957 if (DECL_NAMESPACE_SCOPE_P (decl))
15959 if (CP_DECL_CONTEXT (decl) != global_namespace)
15961 error_at (loc, "%qD may not be declared within a namespace",
15962 decl);
15963 return false;
15966 if (!TREE_PUBLIC (decl))
15968 error_at (loc, "%qD may not be declared as static", decl);
15969 return false;
15973 if (op_flags & OVL_OP_FLAG_DELETE)
15975 DECL_SET_IS_OPERATOR_DELETE (decl, true);
15976 coerce_delete_type (decl, loc);
15978 else
15980 DECL_SET_IS_OPERATOR_NEW (decl, true);
15981 TREE_TYPE (decl) = coerce_new_type (TREE_TYPE (decl), loc);
15984 return true;
15987 /* An operator function must either be a non-static member function
15988 or have at least one parameter of a class, a reference to a class,
15989 an enumeration, or a reference to an enumeration. 13.4.0.6 */
15990 if (!DECL_OBJECT_MEMBER_FUNCTION_P (decl))
15992 if (operator_code == TYPE_EXPR
15993 || operator_code == COMPONENT_REF
15994 || operator_code == NOP_EXPR)
15996 error_at (loc, "%qD must be a non-static member function", decl);
15997 return false;
16000 if (operator_code == CALL_EXPR || operator_code == ARRAY_REF)
16002 if (! DECL_STATIC_FUNCTION_P (decl))
16004 error_at (loc, "%qD must be a member function", decl);
16005 return false;
16007 if (cxx_dialect < cxx23
16008 /* For lambdas we diagnose static lambda specifier elsewhere. */
16009 && (operator_code == ARRAY_REF || ! LAMBDA_FUNCTION_P (decl))
16010 /* For instantiations, we have diagnosed this already. */
16011 && ! DECL_USE_TEMPLATE (decl))
16012 pedwarn (loc, OPT_Wc__23_extensions, "%qD may be a static member "
16013 "function only with %<-std=c++23%> or %<-std=gnu++23%>",
16014 decl);
16015 if (operator_code == ARRAY_REF)
16016 /* static operator[] should have exactly one argument
16017 for C++20 and earlier, so that it isn't multidimensional. */
16018 op_flags = OVL_OP_FLAG_UNARY;
16020 else if (DECL_STATIC_FUNCTION_P (decl))
16022 error_at (loc, "%qD must be either a non-static member "
16023 "function or a non-member function", decl);
16024 return false;
16026 else
16027 for (tree arg = argtypes; ; arg = TREE_CHAIN (arg))
16029 if (!arg || arg == void_list_node)
16031 if (complain)
16032 error_at (loc, "%qD must have an argument of class or "
16033 "enumerated type", decl);
16034 return false;
16037 tree type = non_reference (TREE_VALUE (arg));
16038 if (type == error_mark_node)
16039 return false;
16041 /* MAYBE_CLASS_TYPE_P, rather than CLASS_TYPE_P, is used
16042 because these checks are performed even on template
16043 functions. */
16044 if (MAYBE_CLASS_TYPE_P (type)
16045 || TREE_CODE (type) == ENUMERAL_TYPE)
16046 break;
16050 if (operator_code == CALL_EXPR)
16051 /* There are no further restrictions on the arguments to an overloaded
16052 "operator ()". */
16053 return true;
16055 /* C++23 allows an arbitrary number of parameters and default arguments for
16056 operator[], and none of the other checks below apply. */
16057 if (operator_code == ARRAY_REF && cxx_dialect >= cxx23)
16058 return true;
16060 if (operator_code == COND_EXPR)
16062 /* 13.4.0.3 */
16063 error_at (loc, "ISO C++ prohibits overloading %<operator ?:%>");
16064 return false;
16067 /* Count the number of arguments and check for ellipsis. */
16068 int arity = 0;
16069 for (tree arg = argtypes; arg != void_list_node; arg = TREE_CHAIN (arg))
16071 if (!arg)
16073 error_at (loc, "%qD must not have variable number of arguments",
16074 decl);
16075 return false;
16077 ++arity;
16079 /* FIXME: We need tests for these errors with xobj member functions. */
16080 /* Verify correct number of arguments. */
16081 switch (op_flags)
16083 case OVL_OP_FLAG_AMBIARY:
16084 if (arity == 1)
16086 /* We have a unary instance of an ambi-ary op. Remap to the
16087 unary one. */
16088 unsigned alt = ovl_op_alternate[ovl_op_mapping [operator_code]];
16089 const ovl_op_info_t *ovl_op = &ovl_op_info[false][alt];
16090 gcc_checking_assert (ovl_op->flags == OVL_OP_FLAG_UNARY);
16091 operator_code = ovl_op->tree_code;
16092 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
16094 else if (arity != 2)
16096 /* This was an ambiguous operator but is invalid. */
16097 error_at (loc,
16098 methodp
16099 ? G_("%qD must have either zero or one argument")
16100 : G_("%qD must have either one or two arguments"), decl);
16101 return false;
16103 else if ((operator_code == POSTINCREMENT_EXPR
16104 || operator_code == POSTDECREMENT_EXPR)
16105 && ! processing_template_decl
16106 /* x++ and x--'s second argument must be an int. */
16107 && ! same_type_p (TREE_VALUE (TREE_CHAIN (argtypes)),
16108 integer_type_node))
16110 error_at (loc,
16111 methodp
16112 ? G_("postfix %qD must have %<int%> as its argument")
16113 : G_("postfix %qD must have %<int%> as its second argument"),
16114 decl);
16115 return false;
16117 break;
16119 case OVL_OP_FLAG_UNARY:
16120 if (arity != 1)
16122 error_at (loc,
16123 methodp
16124 ? G_("%qD must have no arguments")
16125 : G_("%qD must have exactly one argument"), decl);
16126 return false;
16128 break;
16130 case OVL_OP_FLAG_BINARY:
16131 if (arity != 2)
16133 error_at (loc,
16134 methodp
16135 ? G_("%qD must have exactly one argument")
16136 : G_("%qD must have exactly two arguments"), decl);
16137 return false;
16139 break;
16141 default:
16142 gcc_unreachable ();
16145 /* There can be no default arguments. */
16146 for (tree arg = argtypes; arg && arg != void_list_node;
16147 arg = TREE_CHAIN (arg))
16148 if (TREE_PURPOSE (arg))
16150 TREE_PURPOSE (arg) = NULL_TREE;
16151 error_at (loc, "%qD cannot have default arguments", decl);
16152 return false;
16155 /* At this point the declaration is well-formed. It may not be
16156 sensible though. */
16158 /* Check member function warnings only on the in-class declaration.
16159 There's no point warning on an out-of-class definition. */
16160 if (class_type && class_type != current_class_type)
16161 return true;
16163 /* Warn about conversion operators that will never be used. */
16164 if (IDENTIFIER_CONV_OP_P (name)
16165 && ! DECL_TEMPLATE_INFO (decl)
16166 && warn_class_conversion)
16168 tree t = TREE_TYPE (name);
16169 int ref = TYPE_REF_P (t);
16171 if (ref)
16172 t = TYPE_MAIN_VARIANT (TREE_TYPE (t));
16174 if (VOID_TYPE_P (t))
16175 warning_at (loc, OPT_Wclass_conversion, "converting %qT to %<void%> "
16176 "will never use a type conversion operator", class_type);
16177 else if (class_type)
16179 if (same_type_ignoring_top_level_qualifiers_p (t, class_type))
16180 warning_at (loc, OPT_Wclass_conversion,
16182 ? G_("converting %qT to a reference to the same type "
16183 "will never use a type conversion operator")
16184 : G_("converting %qT to the same type "
16185 "will never use a type conversion operator"),
16186 class_type);
16187 /* Don't force t to be complete here. */
16188 else if (MAYBE_CLASS_TYPE_P (t)
16189 && COMPLETE_TYPE_P (t)
16190 && DERIVED_FROM_P (t, class_type))
16191 warning_at (loc, OPT_Wclass_conversion,
16193 ? G_("converting %qT to a reference to a base class "
16194 "%qT will never use a type conversion operator")
16195 : G_("converting %qT to a base class %qT "
16196 "will never use a type conversion operator"),
16197 class_type, t);
16201 if (!warn_ecpp)
16202 return true;
16204 /* Effective C++ rules below. */
16206 /* More Effective C++ rule 7. */
16207 if (operator_code == TRUTH_ANDIF_EXPR
16208 || operator_code == TRUTH_ORIF_EXPR
16209 || operator_code == COMPOUND_EXPR)
16210 warning_at (loc, OPT_Weffc__,
16211 "user-defined %qD always evaluates both arguments", decl);
16213 /* More Effective C++ rule 6. */
16214 if (operator_code == POSTINCREMENT_EXPR
16215 || operator_code == POSTDECREMENT_EXPR
16216 || operator_code == PREINCREMENT_EXPR
16217 || operator_code == PREDECREMENT_EXPR)
16219 tree arg = TREE_VALUE (argtypes);
16220 tree ret = TREE_TYPE (TREE_TYPE (decl));
16221 if (methodp || TYPE_REF_P (arg))
16222 arg = TREE_TYPE (arg);
16223 arg = TYPE_MAIN_VARIANT (arg);
16225 if (operator_code == PREINCREMENT_EXPR
16226 || operator_code == PREDECREMENT_EXPR)
16228 if (!TYPE_REF_P (ret)
16229 || !same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (ret)), arg))
16230 warning_at (loc, OPT_Weffc__, "prefix %qD should return %qT", decl,
16231 build_reference_type (arg));
16233 else
16235 if (!same_type_p (TYPE_MAIN_VARIANT (ret), arg))
16236 warning_at (loc, OPT_Weffc__,
16237 "postfix %qD should return %qT", decl, arg);
16241 /* Effective C++ rule 23. */
16242 if (!DECL_ASSIGNMENT_OPERATOR_P (decl)
16243 && (operator_code == PLUS_EXPR
16244 || operator_code == MINUS_EXPR
16245 || operator_code == TRUNC_DIV_EXPR
16246 || operator_code == MULT_EXPR
16247 || operator_code == TRUNC_MOD_EXPR)
16248 && TYPE_REF_P (TREE_TYPE (TREE_TYPE (decl))))
16249 warning_at (loc, OPT_Weffc__, "%qD should return by value", decl);
16251 return true;
16254 /* Return a string giving the keyword associate with CODE. */
16256 static const char *
16257 tag_name (enum tag_types code)
16259 switch (code)
16261 case record_type:
16262 return "struct";
16263 case class_type:
16264 return "class";
16265 case union_type:
16266 return "union";
16267 case enum_type:
16268 return "enum";
16269 case typename_type:
16270 return "typename";
16271 default:
16272 gcc_unreachable ();
16276 /* Name lookup in an elaborated-type-specifier (after the keyword
16277 indicated by TAG_CODE) has found the TYPE_DECL DECL. If the
16278 elaborated-type-specifier is invalid, issue a diagnostic and return
16279 error_mark_node; otherwise, return the *_TYPE to which it referred.
16280 If ALLOW_TEMPLATE_P is true, TYPE may be a class template. */
16282 tree
16283 check_elaborated_type_specifier (enum tag_types tag_code,
16284 tree decl,
16285 bool allow_template_p)
16287 tree type;
16289 /* In the case of:
16291 struct S { struct S *p; };
16293 name lookup will find the TYPE_DECL for the implicit "S::S"
16294 typedef. Adjust for that here. */
16295 if (DECL_SELF_REFERENCE_P (decl))
16296 decl = TYPE_NAME (TREE_TYPE (decl));
16298 type = TREE_TYPE (decl);
16300 /* Check TEMPLATE_TYPE_PARM first because DECL_IMPLICIT_TYPEDEF_P
16301 is false for this case as well. */
16302 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16304 error ("using template type parameter %qT after %qs",
16305 type, tag_name (tag_code));
16306 return error_mark_node;
16308 /* Accept template template parameters. */
16309 else if (allow_template_p
16310 && (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
16311 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM))
16313 /* [dcl.type.elab]
16315 If the identifier resolves to a typedef-name or the
16316 simple-template-id resolves to an alias template
16317 specialization, the elaborated-type-specifier is ill-formed.
16319 In other words, the only legitimate declaration to use in the
16320 elaborated type specifier is the implicit typedef created when
16321 the type is declared. */
16322 else if (!DECL_IMPLICIT_TYPEDEF_P (decl)
16323 && !DECL_SELF_REFERENCE_P (decl)
16324 && tag_code != typename_type)
16326 if (alias_template_specialization_p (type, nt_opaque))
16327 error ("using alias template specialization %qT after %qs",
16328 type, tag_name (tag_code));
16329 else
16330 error ("using typedef-name %qD after %qs", decl, tag_name (tag_code));
16331 inform (DECL_SOURCE_LOCATION (decl),
16332 "%qD has a previous declaration here", decl);
16333 return error_mark_node;
16335 else if (TREE_CODE (type) != RECORD_TYPE
16336 && TREE_CODE (type) != UNION_TYPE
16337 && tag_code != enum_type
16338 && tag_code != typename_type)
16340 error ("%qT referred to as %qs", type, tag_name (tag_code));
16341 inform (location_of (type), "%qT has a previous declaration here", type);
16342 return error_mark_node;
16344 else if (TREE_CODE (type) != ENUMERAL_TYPE
16345 && tag_code == enum_type)
16347 error ("%qT referred to as enum", type);
16348 inform (location_of (type), "%qT has a previous declaration here", type);
16349 return error_mark_node;
16351 else if (!allow_template_p
16352 && TREE_CODE (type) == RECORD_TYPE
16353 && CLASSTYPE_IS_TEMPLATE (type))
16355 /* If a class template appears as elaborated type specifier
16356 without a template header such as:
16358 template <class T> class C {};
16359 void f(class C); // No template header here
16361 then the required template argument is missing. */
16362 error ("template argument required for %<%s %T%>",
16363 tag_name (tag_code),
16364 DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)));
16365 return error_mark_node;
16368 return type;
16371 /* Lookup NAME of an elaborated type specifier according to SCOPE and
16372 issue diagnostics if necessary. Return *_TYPE node upon success,
16373 NULL_TREE when the NAME is not found, and ERROR_MARK_NODE for type
16374 error. */
16376 static tree
16377 lookup_and_check_tag (enum tag_types tag_code, tree name,
16378 TAG_how how, bool template_header_p)
16380 tree decl;
16381 if (how == TAG_how::GLOBAL)
16383 /* First try ordinary name lookup, ignoring hidden class name
16384 injected via friend declaration. */
16385 decl = lookup_name (name, LOOK_want::TYPE);
16386 decl = strip_using_decl (decl);
16387 /* If that fails, the name will be placed in the smallest
16388 non-class, non-function-prototype scope according to 3.3.1/5.
16389 We may already have a hidden name declared as friend in this
16390 scope. So lookup again but not ignoring hidden names.
16391 If we find one, that name will be made visible rather than
16392 creating a new tag. */
16393 if (!decl)
16394 decl = lookup_elaborated_type (name, TAG_how::INNERMOST_NON_CLASS);
16396 else
16397 decl = lookup_elaborated_type (name, how);
16399 if (!decl)
16400 /* We found nothing. */
16401 return NULL_TREE;
16403 if (TREE_CODE (decl) == TREE_LIST)
16405 error ("reference to %qD is ambiguous", name);
16406 print_candidates (decl);
16407 return error_mark_node;
16410 if (DECL_CLASS_TEMPLATE_P (decl)
16411 && !template_header_p
16412 && how == TAG_how::CURRENT_ONLY)
16414 error ("class template %qD redeclared as non-template", name);
16415 inform (location_of (decl), "previous declaration here");
16416 CLASSTYPE_ERRONEOUS (TREE_TYPE (decl)) = true;
16417 return error_mark_node;
16420 if (DECL_CLASS_TEMPLATE_P (decl)
16421 /* If scope is TAG_how::CURRENT_ONLY we're defining a class,
16422 so ignore a template template parameter. */
16423 || (how != TAG_how::CURRENT_ONLY && DECL_TEMPLATE_TEMPLATE_PARM_P (decl)))
16424 decl = DECL_TEMPLATE_RESULT (decl);
16426 if (TREE_CODE (decl) != TYPE_DECL)
16427 /* Found not-a-type. */
16428 return NULL_TREE;
16430 /* Look for invalid nested type:
16431 class C {
16432 class C {};
16433 }; */
16434 if (how == TAG_how::CURRENT_ONLY && DECL_SELF_REFERENCE_P (decl))
16436 error ("%qD has the same name as the class in which it is "
16437 "declared", decl);
16438 return error_mark_node;
16441 /* Two cases we need to consider when deciding if a class
16442 template is allowed as an elaborated type specifier:
16443 1. It is a self reference to its own class.
16444 2. It comes with a template header.
16446 For example:
16448 template <class T> class C {
16449 class C *c1; // DECL_SELF_REFERENCE_P is true
16450 class D;
16452 template <class U> class C; // template_header_p is true
16453 template <class T> class C<T>::D {
16454 class C *c2; // DECL_SELF_REFERENCE_P is true
16455 }; */
16457 tree t = check_elaborated_type_specifier (tag_code, decl,
16458 template_header_p
16459 | DECL_SELF_REFERENCE_P (decl));
16460 if (template_header_p && t && CLASS_TYPE_P (t)
16461 && (!CLASSTYPE_TEMPLATE_INFO (t)
16462 || (!PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))))
16464 error ("%qT is not a template", t);
16465 inform (location_of (t), "previous declaration here");
16466 if (TYPE_CLASS_SCOPE_P (t)
16467 && CLASSTYPE_TEMPLATE_INFO (TYPE_CONTEXT (t)))
16468 inform (input_location,
16469 "perhaps you want to explicitly add %<%T::%>",
16470 TYPE_CONTEXT (t));
16471 return error_mark_node;
16474 return t;
16477 /* Get the struct, enum or union (TAG_CODE says which) with tag NAME.
16478 Define the tag as a forward-reference if it is not defined.
16480 If a declaration is given, process it here, and report an error if
16481 multiple declarations are not identical.
16483 SCOPE is TS_CURRENT when this is also a definition. Only look in
16484 the current frame for the name (since C++ allows new names in any
16485 scope.) It is TS_WITHIN_ENCLOSING_NON_CLASS if this is a friend
16486 declaration. Only look beginning from the current scope outward up
16487 till the nearest non-class scope. Otherwise it is TS_GLOBAL.
16489 TEMPLATE_HEADER_P is true when this declaration is preceded by
16490 a set of template parameters. */
16492 tree
16493 xref_tag (enum tag_types tag_code, tree name,
16494 TAG_how how, bool template_header_p)
16496 enum tree_code code;
16497 tree context = NULL_TREE;
16499 auto_cond_timevar tv (TV_NAME_LOOKUP);
16501 gcc_assert (identifier_p (name));
16503 switch (tag_code)
16505 case record_type:
16506 case class_type:
16507 code = RECORD_TYPE;
16508 break;
16509 case union_type:
16510 code = UNION_TYPE;
16511 break;
16512 case enum_type:
16513 code = ENUMERAL_TYPE;
16514 break;
16515 default:
16516 gcc_unreachable ();
16519 /* In case of anonymous name, xref_tag is only called to
16520 make type node and push name. Name lookup is not required. */
16521 tree t = NULL_TREE;
16522 if (!IDENTIFIER_ANON_P (name))
16523 t = lookup_and_check_tag (tag_code, name, how, template_header_p);
16525 if (t == error_mark_node)
16526 return error_mark_node;
16528 if (how != TAG_how::CURRENT_ONLY && t && current_class_type
16529 && template_class_depth (current_class_type)
16530 && template_header_p)
16532 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
16533 return t;
16535 /* Since HOW is not TAG_how::CURRENT_ONLY, we are not looking at
16536 a definition of this tag. Since, in addition, we are
16537 currently processing a (member) template declaration of a
16538 template class, we must be very careful; consider:
16540 template <class X> struct S1
16542 template <class U> struct S2
16544 template <class V> friend struct S1;
16547 Here, the S2::S1 declaration should not be confused with the
16548 outer declaration. In particular, the inner version should
16549 have a template parameter of level 2, not level 1.
16551 On the other hand, when presented with:
16553 template <class T> struct S1
16555 template <class U> struct S2 {};
16556 template <class U> friend struct S2;
16559 the friend must find S1::S2 eventually. We accomplish this
16560 by making sure that the new type we create to represent this
16561 declaration has the right TYPE_CONTEXT. */
16562 context = TYPE_CONTEXT (t);
16563 t = NULL_TREE;
16566 if (! t)
16568 /* If no such tag is yet defined, create a forward-reference node
16569 and record it as the "definition".
16570 When a real declaration of this type is found,
16571 the forward-reference will be altered into a real type. */
16572 if (code == ENUMERAL_TYPE)
16574 error ("use of enum %q#D without previous declaration", name);
16575 return error_mark_node;
16578 t = make_class_type (code);
16579 TYPE_CONTEXT (t) = context;
16580 if (IDENTIFIER_LAMBDA_P (name))
16581 /* Mark it as a lambda type right now. Our caller will
16582 correct the value. */
16583 CLASSTYPE_LAMBDA_EXPR (t) = error_mark_node;
16584 t = pushtag (name, t, how);
16586 else
16588 if (template_header_p && MAYBE_CLASS_TYPE_P (t))
16590 /* Check that we aren't trying to overload a class with different
16591 constraints. */
16592 if (!redeclare_class_template (t, current_template_parms,
16593 current_template_constraints ()))
16594 return error_mark_node;
16596 else if (!processing_template_decl
16597 && CLASS_TYPE_P (t)
16598 && CLASSTYPE_IS_TEMPLATE (t))
16600 error ("redeclaration of %qT as a non-template", t);
16601 inform (location_of (t), "previous declaration %qD", t);
16602 return error_mark_node;
16605 if (modules_p ()
16606 && how == TAG_how::CURRENT_ONLY)
16608 tree decl = TYPE_NAME (t);
16609 if (!module_may_redeclare (decl))
16611 auto_diagnostic_group d;
16612 error ("cannot declare %qD in a different module", decl);
16613 inform (DECL_SOURCE_LOCATION (decl), "previously declared here");
16614 return error_mark_node;
16617 tree not_tmpl = STRIP_TEMPLATE (decl);
16618 if (DECL_LANG_SPECIFIC (not_tmpl)
16619 && DECL_MODULE_ATTACH_P (not_tmpl)
16620 && !DECL_MODULE_EXPORT_P (not_tmpl)
16621 && module_exporting_p ())
16623 auto_diagnostic_group d;
16624 error ("conflicting exporting for declaration %qD", decl);
16625 inform (DECL_SOURCE_LOCATION (decl),
16626 "previously declared here without exporting");
16629 tree maybe_tmpl = decl;
16630 if (CLASS_TYPE_P (t) && CLASSTYPE_IS_TEMPLATE (t))
16631 maybe_tmpl = CLASSTYPE_TI_TEMPLATE (t);
16633 if (DECL_LANG_SPECIFIC (decl)
16634 && DECL_MODULE_IMPORT_P (decl)
16635 && TREE_CODE (CP_DECL_CONTEXT (decl)) == NAMESPACE_DECL)
16637 /* Push it into this TU's symbol slot. */
16638 gcc_checking_assert (current_namespace == CP_DECL_CONTEXT (decl));
16639 if (maybe_tmpl != decl)
16640 /* We're in the template parm binding level.
16641 Pushtag has logic to slide under that, but we're
16642 not pushing a *new* type. */
16643 push_nested_namespace (CP_DECL_CONTEXT (decl));
16645 pushdecl (maybe_tmpl);
16646 if (maybe_tmpl != decl)
16647 pop_nested_namespace (CP_DECL_CONTEXT (decl));
16650 set_instantiating_module (maybe_tmpl);
16654 return t;
16657 /* Create the binfo hierarchy for REF with (possibly NULL) base list
16658 BASE_LIST. For each element on BASE_LIST the TREE_PURPOSE is an
16659 access_* node, and the TREE_VALUE is the type of the base-class.
16660 Non-NULL TREE_TYPE indicates virtual inheritance. */
16662 void
16663 xref_basetypes (tree ref, tree base_list)
16665 tree *basep;
16666 tree binfo, base_binfo;
16667 unsigned max_vbases = 0; /* Maximum direct & indirect virtual bases. */
16668 unsigned max_bases = 0; /* Maximum direct bases. */
16669 unsigned max_dvbases = 0; /* Maximum direct virtual bases. */
16670 int i;
16671 tree default_access;
16672 tree igo_prev; /* Track Inheritance Graph Order. */
16674 if (ref == error_mark_node)
16675 return;
16677 /* The base of a derived class is private by default, all others are
16678 public. */
16679 default_access = (TREE_CODE (ref) == RECORD_TYPE
16680 && CLASSTYPE_DECLARED_CLASS (ref)
16681 ? access_private_node : access_public_node);
16683 /* First, make sure that any templates in base-classes are
16684 instantiated. This ensures that if we call ourselves recursively
16685 we do not get confused about which classes are marked and which
16686 are not. */
16687 basep = &base_list;
16688 while (*basep)
16690 tree basetype = TREE_VALUE (*basep);
16692 /* The dependent_type_p call below should really be dependent_scope_p
16693 so that we give a hard error about using an incomplete type as a
16694 base, but we allow it with a pedwarn for backward
16695 compatibility. */
16696 if (processing_template_decl
16697 && CLASS_TYPE_P (basetype) && TYPE_BEING_DEFINED (basetype))
16698 cxx_incomplete_type_diagnostic (NULL_TREE, basetype, DK_PEDWARN);
16699 if (!dependent_type_p (basetype)
16700 && !complete_type_or_else (basetype, NULL))
16701 /* An incomplete type. Remove it from the list. */
16702 *basep = TREE_CHAIN (*basep);
16703 else
16705 max_bases++;
16706 if (TREE_TYPE (*basep))
16707 max_dvbases++;
16708 if (CLASS_TYPE_P (basetype))
16709 max_vbases += vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
16710 basep = &TREE_CHAIN (*basep);
16713 max_vbases += max_dvbases;
16715 TYPE_MARKED_P (ref) = 1;
16717 /* The binfo slot should be empty, unless this is an (ill-formed)
16718 redefinition. */
16719 gcc_assert (!TYPE_BINFO (ref) || TYPE_SIZE (ref));
16721 gcc_assert (TYPE_MAIN_VARIANT (ref) == ref);
16723 binfo = make_tree_binfo (max_bases);
16725 TYPE_BINFO (ref) = binfo;
16726 BINFO_OFFSET (binfo) = size_zero_node;
16727 BINFO_TYPE (binfo) = ref;
16729 /* Apply base-class info set up to the variants of this type. */
16730 fixup_type_variants (ref);
16732 if (max_bases)
16734 vec_alloc (BINFO_BASE_ACCESSES (binfo), max_bases);
16735 /* A C++98 POD cannot have base classes. */
16736 CLASSTYPE_NON_LAYOUT_POD_P (ref) = true;
16738 if (TREE_CODE (ref) == UNION_TYPE)
16740 error ("derived union %qT invalid", ref);
16741 return;
16745 if (max_bases > 1)
16746 warning (OPT_Wmultiple_inheritance,
16747 "%qT defined with multiple direct bases", ref);
16749 if (max_vbases)
16751 /* An aggregate can't have virtual base classes. */
16752 CLASSTYPE_NON_AGGREGATE (ref) = true;
16754 vec_alloc (CLASSTYPE_VBASECLASSES (ref), max_vbases);
16756 if (max_dvbases)
16757 warning (OPT_Wvirtual_inheritance,
16758 "%qT defined with direct virtual base", ref);
16761 for (igo_prev = binfo; base_list; base_list = TREE_CHAIN (base_list))
16763 tree access = TREE_PURPOSE (base_list);
16764 int via_virtual = TREE_TYPE (base_list) != NULL_TREE;
16765 tree basetype = TREE_VALUE (base_list);
16767 if (access == access_default_node)
16768 access = default_access;
16770 /* Before C++17, an aggregate cannot have base classes. In C++17, an
16771 aggregate can't have virtual, private, or protected base classes. */
16772 if (cxx_dialect < cxx17
16773 || access != access_public_node
16774 || via_virtual)
16775 CLASSTYPE_NON_AGGREGATE (ref) = true;
16777 if (PACK_EXPANSION_P (basetype))
16778 basetype = PACK_EXPANSION_PATTERN (basetype);
16779 if (TREE_CODE (basetype) == TYPE_DECL)
16780 basetype = TREE_TYPE (basetype);
16781 if (!MAYBE_CLASS_TYPE_P (basetype) || TREE_CODE (basetype) == UNION_TYPE)
16783 error ("base type %qT fails to be a struct or class type",
16784 basetype);
16785 goto dropped_base;
16788 base_binfo = NULL_TREE;
16789 if (CLASS_TYPE_P (basetype) && !dependent_scope_p (basetype))
16791 base_binfo = TYPE_BINFO (basetype);
16792 /* The original basetype could have been a typedef'd type. */
16793 basetype = BINFO_TYPE (base_binfo);
16795 /* Inherit flags from the base. */
16796 TYPE_HAS_NEW_OPERATOR (ref)
16797 |= TYPE_HAS_NEW_OPERATOR (basetype);
16798 TYPE_HAS_ARRAY_NEW_OPERATOR (ref)
16799 |= TYPE_HAS_ARRAY_NEW_OPERATOR (basetype);
16800 TYPE_GETS_DELETE (ref) |= TYPE_GETS_DELETE (basetype);
16801 TYPE_HAS_CONVERSION (ref) |= TYPE_HAS_CONVERSION (basetype);
16802 CLASSTYPE_DIAMOND_SHAPED_P (ref)
16803 |= CLASSTYPE_DIAMOND_SHAPED_P (basetype);
16804 CLASSTYPE_REPEATED_BASE_P (ref)
16805 |= CLASSTYPE_REPEATED_BASE_P (basetype);
16808 /* We must do this test after we've seen through a typedef
16809 type. */
16810 if (TYPE_MARKED_P (basetype))
16812 if (basetype == ref)
16813 error ("recursive type %qT undefined", basetype);
16814 else
16815 error ("duplicate base type %qT invalid", basetype);
16816 goto dropped_base;
16819 if (PACK_EXPANSION_P (TREE_VALUE (base_list)))
16820 /* Regenerate the pack expansion for the bases. */
16821 basetype = make_pack_expansion (basetype);
16823 TYPE_MARKED_P (basetype) = 1;
16825 base_binfo = copy_binfo (base_binfo, basetype, ref,
16826 &igo_prev, via_virtual);
16827 if (!BINFO_INHERITANCE_CHAIN (base_binfo))
16828 BINFO_INHERITANCE_CHAIN (base_binfo) = binfo;
16830 BINFO_BASE_APPEND (binfo, base_binfo);
16831 BINFO_BASE_ACCESS_APPEND (binfo, access);
16832 continue;
16834 dropped_base:
16835 /* Update max_vbases to reflect the reality that we are dropping
16836 this base: if it reaches zero we want to undo the vec_alloc
16837 above to avoid inconsistencies during error-recovery: eg, in
16838 build_special_member_call, CLASSTYPE_VBASECLASSES non null
16839 and vtt null (c++/27952). */
16840 if (via_virtual)
16841 max_vbases--;
16842 if (CLASS_TYPE_P (basetype))
16843 max_vbases
16844 -= vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
16847 if (CLASSTYPE_VBASECLASSES (ref)
16848 && max_vbases == 0)
16849 vec_free (CLASSTYPE_VBASECLASSES (ref));
16851 if (vec_safe_length (CLASSTYPE_VBASECLASSES (ref)) < max_vbases)
16852 /* If we didn't get max_vbases vbases, we must have shared at
16853 least one of them, and are therefore diamond shaped. */
16854 CLASSTYPE_DIAMOND_SHAPED_P (ref) = 1;
16856 /* Unmark all the types. */
16857 for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
16858 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
16859 TYPE_MARKED_P (ref) = 0;
16861 /* Now see if we have a repeated base type. */
16862 if (!CLASSTYPE_REPEATED_BASE_P (ref))
16864 for (base_binfo = binfo; base_binfo;
16865 base_binfo = TREE_CHAIN (base_binfo))
16867 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
16869 CLASSTYPE_REPEATED_BASE_P (ref) = 1;
16870 break;
16872 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 1;
16874 for (base_binfo = binfo; base_binfo;
16875 base_binfo = TREE_CHAIN (base_binfo))
16876 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
16877 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
16878 else
16879 break;
16884 /* Copies the enum-related properties from type SRC to type DST.
16885 Used with the underlying type of an enum and the enum itself. */
16886 static void
16887 copy_type_enum (tree dst, tree src)
16889 tree t;
16890 for (t = dst; t; t = TYPE_NEXT_VARIANT (t))
16892 TYPE_MIN_VALUE (t) = TYPE_MIN_VALUE (src);
16893 TYPE_MAX_VALUE (t) = TYPE_MAX_VALUE (src);
16894 TYPE_SIZE (t) = TYPE_SIZE (src);
16895 TYPE_SIZE_UNIT (t) = TYPE_SIZE_UNIT (src);
16896 SET_TYPE_MODE (dst, TYPE_MODE (src));
16897 TYPE_PRECISION (t) = TYPE_PRECISION (src);
16898 unsigned valign = TYPE_ALIGN (src);
16899 if (TYPE_USER_ALIGN (t))
16900 valign = MAX (valign, TYPE_ALIGN (t));
16901 else
16902 TYPE_USER_ALIGN (t) = TYPE_USER_ALIGN (src);
16903 SET_TYPE_ALIGN (t, valign);
16904 TYPE_UNSIGNED (t) = TYPE_UNSIGNED (src);
16908 /* Begin compiling the definition of an enumeration type.
16909 NAME is its name,
16911 if ENUMTYPE is not NULL_TREE then the type has alredy been found.
16913 UNDERLYING_TYPE is the type that will be used as the storage for
16914 the enumeration type. This should be NULL_TREE if no storage type
16915 was specified.
16917 ATTRIBUTES are any attributes specified after the enum-key.
16919 SCOPED_ENUM_P is true if this is a scoped enumeration type.
16921 if IS_NEW is not NULL, gets TRUE iff a new type is created.
16923 Returns the type object, as yet incomplete.
16924 Also records info about it so that build_enumerator
16925 may be used to declare the individual values as they are read. */
16927 tree
16928 start_enum (tree name, tree enumtype, tree underlying_type,
16929 tree attributes, bool scoped_enum_p, bool *is_new)
16931 tree prevtype = NULL_TREE;
16932 gcc_assert (identifier_p (name));
16934 if (is_new)
16935 *is_new = false;
16936 /* [C++0x dcl.enum]p5:
16938 If not explicitly specified, the underlying type of a scoped
16939 enumeration type is int. */
16940 if (!underlying_type && scoped_enum_p)
16941 underlying_type = integer_type_node;
16943 if (underlying_type)
16944 underlying_type = cv_unqualified (underlying_type);
16946 /* If this is the real definition for a previous forward reference,
16947 fill in the contents in the same object that used to be the
16948 forward reference. */
16949 if (!enumtype)
16950 enumtype = lookup_and_check_tag (enum_type, name,
16951 /*tag_scope=*/TAG_how::CURRENT_ONLY,
16952 /*template_header_p=*/false);
16954 /* In case of a template_decl, the only check that should be deferred
16955 to instantiation time is the comparison of underlying types. */
16956 if (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE)
16958 /* Attempt to set the declaring module. */
16959 if (modules_p ())
16961 tree decl = TYPE_NAME (enumtype);
16962 if (!module_may_redeclare (decl))
16964 auto_diagnostic_group d;
16965 error ("cannot declare %qD in different module", decl);
16966 inform (DECL_SOURCE_LOCATION (decl), "previously declared here");
16967 enumtype = error_mark_node;
16969 else
16970 set_instantiating_module (decl);
16973 if (enumtype == error_mark_node)
16975 else if (scoped_enum_p != SCOPED_ENUM_P (enumtype))
16977 auto_diagnostic_group d;
16978 error_at (input_location, "scoped/unscoped mismatch "
16979 "in enum %q#T", enumtype);
16980 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16981 "previous definition here");
16982 enumtype = error_mark_node;
16984 else if (ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) != !! underlying_type)
16986 auto_diagnostic_group d;
16987 error_at (input_location, "underlying type mismatch "
16988 "in enum %q#T", enumtype);
16989 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16990 "previous definition here");
16991 enumtype = error_mark_node;
16993 else if (underlying_type && ENUM_UNDERLYING_TYPE (enumtype)
16994 && !same_type_p (underlying_type,
16995 ENUM_UNDERLYING_TYPE (enumtype)))
16997 auto_diagnostic_group d;
16998 error_at (input_location, "different underlying type "
16999 "in enum %q#T", enumtype);
17000 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
17001 "previous definition here");
17002 underlying_type = NULL_TREE;
17006 if (!enumtype || TREE_CODE (enumtype) != ENUMERAL_TYPE
17007 || processing_template_decl)
17009 /* In case of error, make a dummy enum to allow parsing to
17010 continue. */
17011 if (enumtype == error_mark_node)
17013 name = make_anon_name ();
17014 enumtype = NULL_TREE;
17017 /* enumtype may be an ENUMERAL_TYPE if this is a redefinition
17018 of an opaque enum, or an opaque enum of an already defined
17019 enumeration (C++11).
17020 In any other case, it'll be NULL_TREE. */
17021 if (!enumtype)
17023 if (is_new)
17024 *is_new = true;
17026 prevtype = enumtype;
17028 /* Do not push the decl more than once. */
17029 if (!enumtype
17030 || TREE_CODE (enumtype) != ENUMERAL_TYPE)
17032 enumtype = cxx_make_type (ENUMERAL_TYPE);
17033 enumtype = pushtag (name, enumtype);
17035 /* std::byte aliases anything. */
17036 if (enumtype != error_mark_node
17037 && TYPE_CONTEXT (enumtype) == std_node
17038 && !strcmp ("byte", TYPE_NAME_STRING (enumtype)))
17039 TYPE_ALIAS_SET (enumtype) = 0;
17041 else
17042 enumtype = xref_tag (enum_type, name);
17044 if (enumtype == error_mark_node)
17045 return error_mark_node;
17047 /* The enum is considered opaque until the opening '{' of the
17048 enumerator list. */
17049 SET_OPAQUE_ENUM_P (enumtype, true);
17050 ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) = !! underlying_type;
17053 SET_SCOPED_ENUM_P (enumtype, scoped_enum_p);
17055 cplus_decl_attributes (&enumtype, attributes, (int)ATTR_FLAG_TYPE_IN_PLACE);
17057 if (underlying_type)
17059 if (ENUM_UNDERLYING_TYPE (enumtype))
17060 /* We already checked that it matches, don't change it to a different
17061 typedef variant. */;
17062 else if (CP_INTEGRAL_TYPE_P (underlying_type))
17064 copy_type_enum (enumtype, underlying_type);
17065 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
17067 else if (dependent_type_p (underlying_type))
17068 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
17069 else
17071 error ("underlying type %qT of %qT must be an integral type",
17072 underlying_type, enumtype);
17073 ENUM_UNDERLYING_TYPE (enumtype) = integer_type_node;
17077 /* If into a template class, the returned enum is always the first
17078 declaration (opaque or not) seen. This way all the references to
17079 this type will be to the same declaration. The following ones are used
17080 only to check for definition errors. */
17081 if (prevtype && processing_template_decl)
17082 return prevtype;
17083 else
17084 return enumtype;
17087 /* After processing and defining all the values of an enumeration type,
17088 install their decls in the enumeration type.
17089 ENUMTYPE is the type object. */
17091 void
17092 finish_enum_value_list (tree enumtype)
17094 tree values;
17095 tree underlying_type;
17096 tree decl;
17097 tree value;
17098 tree minnode, maxnode;
17099 tree t;
17101 bool fixed_underlying_type_p
17102 = ENUM_UNDERLYING_TYPE (enumtype) != NULL_TREE;
17104 /* We built up the VALUES in reverse order. */
17105 TYPE_VALUES (enumtype) = nreverse (TYPE_VALUES (enumtype));
17107 /* For an enum defined in a template, just set the type of the values;
17108 all further processing is postponed until the template is
17109 instantiated. We need to set the type so that tsubst of a CONST_DECL
17110 works. */
17111 if (processing_template_decl)
17113 for (values = TYPE_VALUES (enumtype);
17114 values;
17115 values = TREE_CHAIN (values))
17116 TREE_TYPE (TREE_VALUE (values)) = enumtype;
17117 return;
17120 /* Determine the minimum and maximum values of the enumerators. */
17121 if (TYPE_VALUES (enumtype))
17123 minnode = maxnode = NULL_TREE;
17125 for (values = TYPE_VALUES (enumtype);
17126 values;
17127 values = TREE_CHAIN (values))
17129 decl = TREE_VALUE (values);
17131 /* [dcl.enum]: Following the closing brace of an enum-specifier,
17132 each enumerator has the type of its enumeration. Prior to the
17133 closing brace, the type of each enumerator is the type of its
17134 initializing value. */
17135 TREE_TYPE (decl) = enumtype;
17137 /* Update the minimum and maximum values, if appropriate. */
17138 value = DECL_INITIAL (decl);
17139 if (TREE_CODE (value) != INTEGER_CST)
17140 value = integer_zero_node;
17141 /* Figure out what the minimum and maximum values of the
17142 enumerators are. */
17143 if (!minnode)
17144 minnode = maxnode = value;
17145 else if (tree_int_cst_lt (maxnode, value))
17146 maxnode = value;
17147 else if (tree_int_cst_lt (value, minnode))
17148 minnode = value;
17151 else
17152 /* [dcl.enum]
17154 If the enumerator-list is empty, the underlying type is as if
17155 the enumeration had a single enumerator with value 0. */
17156 minnode = maxnode = integer_zero_node;
17158 if (!fixed_underlying_type_p)
17160 /* Compute the number of bits require to represent all values of the
17161 enumeration. We must do this before the type of MINNODE and
17162 MAXNODE are transformed, since tree_int_cst_min_precision relies
17163 on the TREE_TYPE of the value it is passed. */
17164 signop sgn = tree_int_cst_sgn (minnode) >= 0 ? UNSIGNED : SIGNED;
17165 int lowprec = tree_int_cst_min_precision (minnode, sgn);
17166 int highprec = tree_int_cst_min_precision (maxnode, sgn);
17167 int precision = MAX (lowprec, highprec);
17168 unsigned int itk;
17169 bool use_short_enum;
17171 /* Determine the underlying type of the enumeration.
17173 [dcl.enum]
17175 The underlying type of an enumeration is an integral type that
17176 can represent all the enumerator values defined in the
17177 enumeration. It is implementation-defined which integral type is
17178 used as the underlying type for an enumeration except that the
17179 underlying type shall not be larger than int unless the value of
17180 an enumerator cannot fit in an int or unsigned int.
17182 We use "int" or an "unsigned int" as the underlying type, even if
17183 a smaller integral type would work, unless the user has
17184 explicitly requested that we use the smallest possible type. The
17185 user can request that for all enumerations with a command line
17186 flag, or for just one enumeration with an attribute. */
17188 use_short_enum = flag_short_enums
17189 || lookup_attribute ("packed", TYPE_ATTRIBUTES (enumtype));
17191 /* If the precision of the type was specified with an attribute and it
17192 was too small, give an error. Otherwise, use it. */
17193 if (TYPE_PRECISION (enumtype))
17195 if (precision > TYPE_PRECISION (enumtype))
17196 error ("specified mode too small for enumerated values");
17197 else
17199 use_short_enum = true;
17200 precision = TYPE_PRECISION (enumtype);
17204 for (itk = (use_short_enum ? itk_char : itk_int);
17205 itk != itk_none;
17206 itk++)
17208 underlying_type = integer_types[itk];
17209 if (underlying_type != NULL_TREE
17210 && TYPE_PRECISION (underlying_type) >= precision
17211 && TYPE_SIGN (underlying_type) == sgn)
17212 break;
17214 if (itk == itk_none)
17216 /* DR 377
17218 IF no integral type can represent all the enumerator values, the
17219 enumeration is ill-formed. */
17220 error ("no integral type can represent all of the enumerator values "
17221 "for %qT", enumtype);
17222 precision = TYPE_PRECISION (long_long_integer_type_node);
17223 underlying_type = integer_types[itk_unsigned_long_long];
17226 /* [dcl.enum]
17228 The value of sizeof() applied to an enumeration type, an object
17229 of an enumeration type, or an enumerator, is the value of sizeof()
17230 applied to the underlying type. */
17231 copy_type_enum (enumtype, underlying_type);
17233 /* Compute the minimum and maximum values for the type.
17235 [dcl.enum]
17237 For an enumeration where emin is the smallest enumerator and emax
17238 is the largest, the values of the enumeration are the values of the
17239 underlying type in the range bmin to bmax, where bmin and bmax are,
17240 respectively, the smallest and largest values of the smallest bit-
17241 field that can store emin and emax. */
17243 /* The middle-end currently assumes that types with TYPE_PRECISION
17244 narrower than their underlying type are suitably zero or sign
17245 extended to fill their mode. Similarly, it assumes that the front
17246 end assures that a value of a particular type must be within
17247 TYPE_MIN_VALUE and TYPE_MAX_VALUE.
17249 We used to set these fields based on bmin and bmax, but that led
17250 to invalid assumptions like optimizing away bounds checking. So
17251 now we just set the TYPE_PRECISION, TYPE_MIN_VALUE, and
17252 TYPE_MAX_VALUE to the values for the mode above and only restrict
17253 the ENUM_UNDERLYING_TYPE for the benefit of diagnostics. */
17254 ENUM_UNDERLYING_TYPE (enumtype)
17255 = build_distinct_type_copy (underlying_type);
17256 TYPE_PRECISION (ENUM_UNDERLYING_TYPE (enumtype)) = precision;
17257 set_min_and_max_values_for_integral_type
17258 (ENUM_UNDERLYING_TYPE (enumtype), precision, sgn);
17260 /* If -fstrict-enums, still constrain TYPE_MIN/MAX_VALUE. */
17261 if (flag_strict_enums)
17262 set_min_and_max_values_for_integral_type (enumtype, precision, sgn);
17264 if (use_short_enum)
17266 TYPE_PACKED (enumtype) = use_short_enum;
17267 fixup_attribute_variants (enumtype);
17270 else
17271 underlying_type = ENUM_UNDERLYING_TYPE (enumtype);
17273 /* If the enum is exported, mark the consts too. */
17274 bool export_p = (UNSCOPED_ENUM_P (enumtype)
17275 && DECL_MODULE_EXPORT_P (TYPE_STUB_DECL (enumtype))
17276 && at_namespace_scope_p ());
17278 /* Convert each of the enumerators to the type of the underlying
17279 type of the enumeration. */
17280 for (values = TYPE_VALUES (enumtype); values; values = TREE_CHAIN (values))
17282 decl = TREE_VALUE (values);
17283 iloc_sentinel ils (DECL_SOURCE_LOCATION (decl));
17284 if (fixed_underlying_type_p)
17285 /* If the enumeration type has a fixed underlying type, we
17286 already checked all of the enumerator values. */
17287 value = DECL_INITIAL (decl);
17288 else
17289 value = perform_implicit_conversion (underlying_type,
17290 DECL_INITIAL (decl),
17291 tf_warning_or_error);
17292 /* Do not clobber shared ints. */
17293 if (value != error_mark_node)
17295 value = copy_node (value);
17297 TREE_TYPE (value) = enumtype;
17299 DECL_INITIAL (decl) = value;
17300 if (export_p)
17301 DECL_MODULE_EXPORT_P (decl) = true;
17304 /* Fix up all variant types of this enum type. */
17305 for (t = TYPE_MAIN_VARIANT (enumtype); t; t = TYPE_NEXT_VARIANT (t))
17306 TYPE_VALUES (t) = TYPE_VALUES (enumtype);
17308 if (at_class_scope_p ()
17309 && COMPLETE_TYPE_P (current_class_type)
17310 && UNSCOPED_ENUM_P (enumtype))
17312 insert_late_enum_def_bindings (current_class_type, enumtype);
17313 /* TYPE_FIELDS needs fixup. */
17314 fixup_type_variants (current_class_type);
17317 /* Finish debugging output for this type. */
17318 rest_of_type_compilation (enumtype, namespace_bindings_p ());
17320 /* Each enumerator now has the type of its enumeration. Clear the cache
17321 so that this change in types doesn't confuse us later on. */
17322 clear_cv_and_fold_caches ();
17325 /* Finishes the enum type. This is called only the first time an
17326 enumeration is seen, be it opaque or odinary.
17327 ENUMTYPE is the type object. */
17329 void
17330 finish_enum (tree enumtype)
17332 if (processing_template_decl)
17334 if (at_function_scope_p ())
17335 add_stmt (build_min (TAG_DEFN, enumtype));
17336 return;
17339 /* If this is a forward declaration, there should not be any variants,
17340 though we can get a variant in the middle of an enum-specifier with
17341 wacky code like 'enum E { e = sizeof(const E*) };' */
17342 gcc_assert (enumtype == TYPE_MAIN_VARIANT (enumtype)
17343 && (TYPE_VALUES (enumtype)
17344 || !TYPE_NEXT_VARIANT (enumtype)));
17347 /* Build and install a CONST_DECL for an enumeration constant of the
17348 enumeration type ENUMTYPE whose NAME and VALUE (if any) are provided.
17349 Apply ATTRIBUTES if available. LOC is the location of NAME.
17350 Assignment of sequential values by default is handled here. */
17352 tree
17353 build_enumerator (tree name, tree value, tree enumtype, tree attributes,
17354 location_t loc)
17356 tree decl;
17357 tree context;
17358 tree type;
17360 /* scalar_constant_value will pull out this expression, so make sure
17361 it's folded as appropriate. */
17362 if (processing_template_decl)
17363 value = fold_non_dependent_expr (value);
17365 /* If the VALUE was erroneous, pretend it wasn't there; that will
17366 result in the enum being assigned the next value in sequence. */
17367 if (value == error_mark_node)
17368 value = NULL_TREE;
17370 /* Remove no-op casts from the value. */
17371 if (value)
17372 STRIP_TYPE_NOPS (value);
17374 if (! processing_template_decl)
17376 /* Validate and default VALUE. */
17377 if (value != NULL_TREE)
17379 if (!ENUM_UNDERLYING_TYPE (enumtype))
17381 tree tmp_value = build_expr_type_conversion (WANT_INT | WANT_ENUM,
17382 value, true);
17383 if (tmp_value)
17384 value = tmp_value;
17386 else if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
17387 (TREE_TYPE (value)))
17388 value = perform_implicit_conversion_flags
17389 (ENUM_UNDERLYING_TYPE (enumtype), value, tf_warning_or_error,
17390 LOOKUP_IMPLICIT | LOOKUP_NO_NARROWING);
17392 if (value == error_mark_node)
17393 value = NULL_TREE;
17395 if (value != NULL_TREE)
17397 if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
17398 (TREE_TYPE (value)))
17400 error_at (cp_expr_loc_or_input_loc (value),
17401 "enumerator value for %qD must have integral or "
17402 "unscoped enumeration type", name);
17403 value = NULL_TREE;
17405 else
17407 value = cxx_constant_value (value);
17409 if (TREE_CODE (value) != INTEGER_CST)
17411 error ("enumerator value for %qD is not an integer "
17412 "constant", name);
17413 value = NULL_TREE;
17419 /* Default based on previous value. */
17420 if (value == NULL_TREE)
17422 if (TYPE_VALUES (enumtype))
17424 tree prev_value;
17426 /* C++03 7.2/4: If no initializer is specified for the first
17427 enumerator, the type is an unspecified integral
17428 type. Otherwise the type is the same as the type of the
17429 initializing value of the preceding enumerator unless the
17430 incremented value is not representable in that type, in
17431 which case the type is an unspecified integral type
17432 sufficient to contain the incremented value. */
17433 prev_value = DECL_INITIAL (TREE_VALUE (TYPE_VALUES (enumtype)));
17434 if (TREE_CODE (prev_value) != INTEGER_CST)
17435 value = error_mark_node;
17436 else
17438 wi::overflow_type overflowed;
17439 tree type = TREE_TYPE (prev_value);
17440 signop sgn = TYPE_SIGN (type);
17441 widest_int wi = wi::add (wi::to_widest (prev_value), 1, sgn,
17442 &overflowed);
17443 if (!overflowed)
17445 bool pos = !wi::neg_p (wi, sgn);
17446 if (!wi::fits_to_tree_p (wi, type))
17448 unsigned int itk;
17449 for (itk = itk_int; itk != itk_none; itk++)
17451 type = integer_types[itk];
17452 if (type != NULL_TREE
17453 && (pos || !TYPE_UNSIGNED (type))
17454 && wi::fits_to_tree_p (wi, type))
17455 break;
17457 if (type && cxx_dialect < cxx11
17458 && itk > itk_unsigned_long)
17459 pedwarn (input_location, OPT_Wlong_long,
17460 pos ? G_("\
17461 incremented enumerator value is too large for %<unsigned long%>") : G_("\
17462 incremented enumerator value is too large for %<long%>"));
17464 if (type == NULL_TREE)
17465 overflowed = wi::OVF_UNKNOWN;
17466 else
17467 value = wide_int_to_tree (type, wi);
17470 if (overflowed)
17472 error ("overflow in enumeration values at %qD", name);
17473 value = error_mark_node;
17477 else
17478 value = integer_zero_node;
17481 /* Remove no-op casts from the value. */
17482 STRIP_TYPE_NOPS (value);
17484 /* If the underlying type of the enum is fixed, check whether
17485 the enumerator values fits in the underlying type. If it
17486 does not fit, the program is ill-formed [C++0x dcl.enum]. */
17487 if (ENUM_UNDERLYING_TYPE (enumtype)
17488 && value
17489 && TREE_CODE (value) == INTEGER_CST)
17491 if (!int_fits_type_p (value, ENUM_UNDERLYING_TYPE (enumtype)))
17492 error ("enumerator value %qE is outside the range of underlying "
17493 "type %qT", value, ENUM_UNDERLYING_TYPE (enumtype));
17495 /* Convert the value to the appropriate type. */
17496 value = fold_convert (ENUM_UNDERLYING_TYPE (enumtype), value);
17500 /* C++ associates enums with global, function, or class declarations. */
17501 context = current_scope ();
17503 /* Build the actual enumeration constant. Note that the enumeration
17504 constants have the underlying type of the enum (if it is fixed)
17505 or the type of their initializer (if the underlying type of the
17506 enum is not fixed):
17508 [ C++0x dcl.enum ]
17510 If the underlying type is fixed, the type of each enumerator
17511 prior to the closing brace is the underlying type; if the
17512 initializing value of an enumerator cannot be represented by
17513 the underlying type, the program is ill-formed. If the
17514 underlying type is not fixed, the type of each enumerator is
17515 the type of its initializing value.
17517 If the underlying type is not fixed, it will be computed by
17518 finish_enum and we will reset the type of this enumerator. Of
17519 course, if we're processing a template, there may be no value. */
17520 type = value ? TREE_TYPE (value) : NULL_TREE;
17522 decl = build_decl (loc, CONST_DECL, name, type);
17524 DECL_CONTEXT (decl) = enumtype;
17525 TREE_CONSTANT (decl) = 1;
17526 TREE_READONLY (decl) = 1;
17527 DECL_INITIAL (decl) = value;
17529 if (attributes)
17530 cplus_decl_attributes (&decl, attributes, 0);
17532 if (context && context == current_class_type && !SCOPED_ENUM_P (enumtype))
17534 /* In something like `struct S { enum E { i = 7 }; };' we put `i'
17535 on the TYPE_FIELDS list for `S'. (That's so that you can say
17536 things like `S::i' later.) */
17538 /* The enumerator may be getting declared outside of its enclosing
17539 class, like so:
17541 class S { public: enum E : int; }; enum S::E : int { i = 7; };
17543 For which case we need to make sure that the access of `S::i'
17544 matches the access of `S::E'. */
17545 auto cas = make_temp_override (current_access_specifier);
17546 set_current_access_from_decl (TYPE_NAME (enumtype));
17547 finish_member_declaration (decl);
17549 else
17550 pushdecl (decl);
17552 /* Add this enumeration constant to the list for this type. */
17553 TYPE_VALUES (enumtype) = tree_cons (name, decl, TYPE_VALUES (enumtype));
17555 return decl;
17558 /* Look for an enumerator with the given NAME within the enumeration
17559 type ENUMTYPE. This routine is used primarily for qualified name
17560 lookup into an enumerator in C++0x, e.g.,
17562 enum class Color { Red, Green, Blue };
17564 Color color = Color::Red;
17566 Returns the value corresponding to the enumerator, or
17567 NULL_TREE if no such enumerator was found. */
17568 tree
17569 lookup_enumerator (tree enumtype, tree name)
17571 tree e;
17572 gcc_assert (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE);
17574 e = purpose_member (name, TYPE_VALUES (enumtype));
17575 return e? TREE_VALUE (e) : NULL_TREE;
17578 /* Implement LANG_HOOKS_SIMULATE_ENUM_DECL. */
17580 tree
17581 cxx_simulate_enum_decl (location_t loc, const char *name,
17582 vec<string_int_pair> *values)
17584 location_t saved_loc = input_location;
17585 input_location = loc;
17587 tree enumtype = start_enum (get_identifier (name), NULL_TREE, NULL_TREE,
17588 NULL_TREE, false, NULL);
17589 if (!OPAQUE_ENUM_P (enumtype))
17591 error_at (loc, "multiple definition of %q#T", enumtype);
17592 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
17593 "previous definition here");
17594 return enumtype;
17596 SET_OPAQUE_ENUM_P (enumtype, false);
17597 DECL_SOURCE_LOCATION (TYPE_NAME (enumtype)) = loc;
17599 for (const string_int_pair &value : values)
17600 build_enumerator (get_identifier (value.first),
17601 build_int_cst (integer_type_node, value.second),
17602 enumtype, NULL_TREE, loc);
17604 finish_enum_value_list (enumtype);
17605 finish_enum (enumtype);
17607 input_location = saved_loc;
17608 return enumtype;
17611 /* Implement LANG_HOOKS_SIMULATE_RECORD_DECL. */
17613 tree
17614 cxx_simulate_record_decl (location_t loc, const char *name,
17615 array_slice<const tree> fields)
17617 iloc_sentinel ils (loc);
17619 tree ident = get_identifier (name);
17620 tree type = xref_tag (/*tag_code=*/record_type, ident);
17621 if (type != error_mark_node
17622 && (TREE_CODE (type) != RECORD_TYPE || COMPLETE_TYPE_P (type)))
17624 error ("redefinition of %q#T", type);
17625 type = error_mark_node;
17627 if (type == error_mark_node)
17628 return lhd_simulate_record_decl (loc, name, fields);
17630 xref_basetypes (type, NULL_TREE);
17631 type = begin_class_definition (type);
17632 if (type == error_mark_node)
17633 return lhd_simulate_record_decl (loc, name, fields);
17635 for (tree field : fields)
17636 finish_member_declaration (field);
17638 type = finish_struct (type, NULL_TREE);
17640 tree decl = build_decl (loc, TYPE_DECL, ident, type);
17641 set_underlying_type (decl);
17642 lang_hooks.decls.pushdecl (decl);
17644 return type;
17647 /* We're defining DECL. Make sure that its type is OK. */
17649 static void
17650 check_function_type (tree decl, tree current_function_parms)
17652 tree fntype = TREE_TYPE (decl);
17653 tree return_type = complete_type (TREE_TYPE (fntype));
17655 /* In a function definition, arg types must be complete. */
17656 require_complete_types_for_parms (current_function_parms);
17658 if (dependent_type_p (return_type)
17659 || type_uses_auto (return_type))
17660 return;
17661 if (!COMPLETE_OR_VOID_TYPE_P (return_type))
17663 tree args = TYPE_ARG_TYPES (fntype);
17665 error ("return type %q#T is incomplete", return_type);
17667 /* Make it return void instead. */
17668 if (TREE_CODE (fntype) == METHOD_TYPE)
17669 fntype = build_method_type_directly (TREE_TYPE (TREE_VALUE (args)),
17670 void_type_node,
17671 TREE_CHAIN (args));
17672 else
17673 fntype = build_function_type (void_type_node, args);
17674 fntype = (cp_build_type_attribute_variant
17675 (fntype, TYPE_ATTRIBUTES (TREE_TYPE (decl))));
17676 fntype = cxx_copy_lang_qualifiers (fntype, TREE_TYPE (decl));
17677 TREE_TYPE (decl) = fntype;
17679 else
17681 abstract_virtuals_error (decl, TREE_TYPE (fntype));
17682 maybe_warn_parm_abi (TREE_TYPE (fntype),
17683 DECL_SOURCE_LOCATION (decl));
17687 /* True iff FN is an implicitly-defined default constructor. */
17689 static bool
17690 implicit_default_ctor_p (tree fn)
17692 return (DECL_CONSTRUCTOR_P (fn)
17693 && !user_provided_p (fn)
17694 && sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (fn)));
17697 /* Clobber the contents of *this to let the back end know that the object
17698 storage is dead when we enter the constructor or leave the destructor. */
17700 static tree
17701 build_clobber_this (clobber_kind kind)
17703 /* Clobbering an empty base is pointless, and harmful if its one byte
17704 TYPE_SIZE overlays real data. */
17705 if (is_empty_class (current_class_type))
17706 return void_node;
17708 /* If we have virtual bases, clobber the whole object, but only if we're in
17709 charge. If we don't have virtual bases, clobber the as-base type so we
17710 don't mess with tail padding. */
17711 bool vbases = CLASSTYPE_VBASECLASSES (current_class_type);
17713 tree ctype = current_class_type;
17714 if (!vbases)
17715 ctype = CLASSTYPE_AS_BASE (ctype);
17717 tree clobber = build_clobber (ctype, kind);
17719 tree thisref = current_class_ref;
17720 if (ctype != current_class_type)
17722 thisref = build_nop (build_reference_type (ctype), current_class_ptr);
17723 thisref = convert_from_reference (thisref);
17726 tree exprstmt = build2 (MODIFY_EXPR, void_type_node, thisref, clobber);
17727 if (vbases)
17728 exprstmt = build_if_in_charge (exprstmt);
17730 return exprstmt;
17733 /* Create the FUNCTION_DECL for a function definition.
17734 DECLSPECS and DECLARATOR are the parts of the declaration;
17735 they describe the function's name and the type it returns,
17736 but twisted together in a fashion that parallels the syntax of C.
17738 FLAGS is a bitwise or of SF_PRE_PARSED (indicating that the
17739 DECLARATOR is really the DECL for the function we are about to
17740 process and that DECLSPECS should be ignored), SF_INCLASS_INLINE
17741 indicating that the function is an inline defined in-class.
17743 This function creates a binding context for the function body
17744 as well as setting up the FUNCTION_DECL in current_function_decl.
17746 For C++, we must first check whether that datum makes any sense.
17747 For example, "class A local_a(1,2);" means that variable local_a
17748 is an aggregate of type A, which should have a constructor
17749 applied to it with the argument list [1, 2].
17751 On entry, DECL_INITIAL (decl1) should be NULL_TREE or error_mark_node,
17752 or may be a BLOCK if the function has been defined previously
17753 in this translation unit. On exit, DECL_INITIAL (decl1) will be
17754 error_mark_node if the function has never been defined, or
17755 a BLOCK if the function has been defined somewhere. */
17757 bool
17758 start_preparsed_function (tree decl1, tree attrs, int flags)
17760 tree ctype = NULL_TREE;
17761 bool doing_friend = false;
17763 /* Sanity check. */
17764 gcc_assert (VOID_TYPE_P (TREE_VALUE (void_list_node)));
17765 gcc_assert (TREE_CHAIN (void_list_node) == NULL_TREE);
17767 tree fntype = TREE_TYPE (decl1);
17768 if (DECL_CLASS_SCOPE_P (decl1))
17769 ctype = DECL_CONTEXT (decl1);
17770 else
17772 ctype = DECL_FRIEND_CONTEXT (decl1);
17774 if (ctype)
17775 doing_friend = true;
17778 if (DECL_DECLARED_INLINE_P (decl1)
17779 && lookup_attribute ("noinline", attrs))
17780 warning_at (DECL_SOURCE_LOCATION (decl1), 0,
17781 "inline function %qD given attribute %qs", decl1, "noinline");
17783 /* Handle gnu_inline attribute. */
17784 if (GNU_INLINE_P (decl1))
17786 DECL_EXTERNAL (decl1) = 1;
17787 DECL_NOT_REALLY_EXTERN (decl1) = 0;
17788 DECL_INTERFACE_KNOWN (decl1) = 1;
17789 DECL_DISREGARD_INLINE_LIMITS (decl1) = 1;
17792 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl1))
17793 /* This is a constructor, we must ensure that any default args
17794 introduced by this definition are propagated to the clones
17795 now. The clones are used directly in overload resolution. */
17796 adjust_clone_args (decl1);
17798 /* Sometimes we don't notice that a function is a static member, and
17799 build a METHOD_TYPE for it. Fix that up now. */
17800 gcc_assert (!(DECL_STATIC_FUNCTION_P (decl1)
17801 && TREE_CODE (TREE_TYPE (decl1)) == METHOD_TYPE));
17803 /* Set up current_class_type, and enter the scope of the class, if
17804 appropriate. */
17805 if (ctype)
17806 push_nested_class (ctype);
17808 /* Now that we have entered the scope of the class, we must restore
17809 the bindings for any template parameters surrounding DECL1, if it
17810 is an inline member template. (Order is important; consider the
17811 case where a template parameter has the same name as a field of
17812 the class.) It is not until after this point that
17813 PROCESSING_TEMPLATE_DECL is guaranteed to be set up correctly. */
17814 if (flags & SF_INCLASS_INLINE)
17815 maybe_begin_member_template_processing (decl1);
17817 /* Effective C++ rule 15. */
17818 if (warn_ecpp
17819 && DECL_ASSIGNMENT_OPERATOR_P (decl1)
17820 && DECL_OVERLOADED_OPERATOR_IS (decl1, NOP_EXPR)
17821 && VOID_TYPE_P (TREE_TYPE (fntype)))
17822 warning (OPT_Weffc__,
17823 "%<operator=%> should return a reference to %<*this%>");
17825 /* Make the init_value nonzero so pushdecl knows this is not tentative.
17826 error_mark_node is replaced below (in poplevel) with the BLOCK. */
17827 if (!DECL_INITIAL (decl1))
17828 DECL_INITIAL (decl1) = error_mark_node;
17830 /* This function exists in static storage.
17831 (This does not mean `static' in the C sense!) */
17832 TREE_STATIC (decl1) = 1;
17834 /* We must call push_template_decl after current_class_type is set
17835 up. (If we are processing inline definitions after exiting a
17836 class scope, current_class_type will be NULL_TREE until set above
17837 by push_nested_class.) */
17838 if (processing_template_decl)
17840 tree newdecl1 = push_template_decl (decl1, doing_friend);
17841 if (newdecl1 == error_mark_node)
17843 if (ctype)
17844 pop_nested_class ();
17845 return false;
17847 decl1 = newdecl1;
17850 /* Make sure the parameter and return types are reasonable. When
17851 you declare a function, these types can be incomplete, but they
17852 must be complete when you define the function. */
17853 check_function_type (decl1, DECL_ARGUMENTS (decl1));
17855 /* Build the return declaration for the function. */
17856 tree restype = TREE_TYPE (fntype);
17858 if (DECL_RESULT (decl1) == NULL_TREE)
17860 /* In a template instantiation, copy the return type location. When
17861 parsing, the location will be set in grokdeclarator. */
17862 location_t loc = input_location;
17863 if (DECL_TEMPLATE_INSTANTIATION (decl1))
17865 tree tmpl = template_for_substitution (decl1);
17866 if (tree res = DECL_RESULT (DECL_TEMPLATE_RESULT (tmpl)))
17867 loc = DECL_SOURCE_LOCATION (res);
17870 tree resdecl = build_decl (loc, RESULT_DECL, 0, restype);
17871 DECL_ARTIFICIAL (resdecl) = 1;
17872 DECL_IGNORED_P (resdecl) = 1;
17873 DECL_RESULT (decl1) = resdecl;
17875 cp_apply_type_quals_to_decl (cp_type_quals (restype), resdecl);
17878 /* Record the decl so that the function name is defined.
17879 If we already have a decl for this name, and it is a FUNCTION_DECL,
17880 use the old decl. */
17881 if (!processing_template_decl && !(flags & SF_PRE_PARSED))
17883 /* A specialization is not used to guide overload resolution. */
17884 if (!DECL_FUNCTION_MEMBER_P (decl1)
17885 && !(DECL_USE_TEMPLATE (decl1) &&
17886 PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl1))))
17888 tree olddecl = pushdecl (decl1);
17890 if (olddecl == error_mark_node)
17891 /* If something went wrong when registering the declaration,
17892 use DECL1; we have to have a FUNCTION_DECL to use when
17893 parsing the body of the function. */
17895 else
17897 /* Otherwise, OLDDECL is either a previous declaration
17898 of the same function or DECL1 itself. */
17900 if (warn_missing_declarations
17901 && olddecl == decl1
17902 && !DECL_MAIN_P (decl1)
17903 && TREE_PUBLIC (decl1)
17904 && !DECL_DECLARED_INLINE_P (decl1))
17906 tree context;
17908 /* Check whether DECL1 is in an anonymous
17909 namespace. */
17910 for (context = DECL_CONTEXT (decl1);
17911 context;
17912 context = DECL_CONTEXT (context))
17914 if (TREE_CODE (context) == NAMESPACE_DECL
17915 && DECL_NAME (context) == NULL_TREE)
17916 break;
17919 if (context == NULL)
17920 warning_at (DECL_SOURCE_LOCATION (decl1),
17921 OPT_Wmissing_declarations,
17922 "no previous declaration for %qD", decl1);
17925 decl1 = olddecl;
17928 else
17930 /* We need to set the DECL_CONTEXT. */
17931 if (!DECL_CONTEXT (decl1) && DECL_TEMPLATE_INFO (decl1))
17932 DECL_CONTEXT (decl1) = DECL_CONTEXT (DECL_TI_TEMPLATE (decl1));
17934 fntype = TREE_TYPE (decl1);
17935 restype = TREE_TYPE (fntype);
17937 /* If #pragma weak applies, mark the decl appropriately now.
17938 The pragma only applies to global functions. Because
17939 determining whether or not the #pragma applies involves
17940 computing the mangled name for the declaration, we cannot
17941 apply the pragma until after we have merged this declaration
17942 with any previous declarations; if the original declaration
17943 has a linkage specification, that specification applies to
17944 the definition as well, and may affect the mangled name. */
17945 if (DECL_FILE_SCOPE_P (decl1))
17946 maybe_apply_pragma_weak (decl1);
17949 /* We are now in the scope of the function being defined. */
17950 current_function_decl = decl1;
17952 /* Save the parm names or decls from this function's declarator
17953 where store_parm_decls will find them. */
17954 tree current_function_parms = DECL_ARGUMENTS (decl1);
17956 /* Let the user know we're compiling this function. */
17957 announce_function (decl1);
17959 gcc_assert (DECL_INITIAL (decl1));
17961 /* This function may already have been parsed, in which case just
17962 return; our caller will skip over the body without parsing. */
17963 if (DECL_INITIAL (decl1) != error_mark_node)
17964 return true;
17966 /* Initialize RTL machinery. We cannot do this until
17967 CURRENT_FUNCTION_DECL and DECL_RESULT are set up. We do this
17968 even when processing a template; this is how we get
17969 CFUN set up, and our per-function variables initialized.
17970 FIXME factor out the non-RTL stuff. */
17971 cp_binding_level *bl = current_binding_level;
17972 allocate_struct_function (decl1, processing_template_decl);
17974 /* Initialize the language data structures. Whenever we start
17975 a new function, we destroy temporaries in the usual way. */
17976 cfun->language = ggc_cleared_alloc<language_function> ();
17977 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
17978 current_binding_level = bl;
17980 /* If we are (erroneously) defining a function that we have already
17981 defined before, wipe out what we knew before. */
17982 gcc_checking_assert (!DECL_PENDING_INLINE_P (decl1));
17983 FNDECL_USED_AUTO (decl1) = false;
17984 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = NULL;
17986 if (!processing_template_decl && type_uses_auto (restype))
17988 FNDECL_USED_AUTO (decl1) = true;
17989 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = restype;
17992 /* Start the statement-tree, start the tree now. */
17993 DECL_SAVED_TREE (decl1) = push_stmt_list ();
17995 if (DECL_IOBJ_MEMBER_FUNCTION_P (decl1))
17997 /* We know that this was set up by `grokclassfn'. We do not
17998 wait until `store_parm_decls', since evil parse errors may
17999 never get us to that point. Here we keep the consistency
18000 between `current_class_type' and `current_class_ptr'. */
18001 tree t = DECL_ARGUMENTS (decl1);
18003 gcc_assert (t != NULL_TREE && TREE_CODE (t) == PARM_DECL);
18004 gcc_assert (TYPE_PTR_P (TREE_TYPE (t)));
18006 cp_function_chain->x_current_class_ref
18007 = cp_build_fold_indirect_ref (t);
18008 /* Set this second to avoid shortcut in cp_build_indirect_ref. */
18009 cp_function_chain->x_current_class_ptr = t;
18011 /* Constructors and destructors need to know whether they're "in
18012 charge" of initializing virtual base classes. */
18013 t = DECL_CHAIN (t);
18014 if (DECL_HAS_IN_CHARGE_PARM_P (decl1))
18016 current_in_charge_parm = t;
18017 t = DECL_CHAIN (t);
18019 if (DECL_HAS_VTT_PARM_P (decl1))
18021 gcc_assert (DECL_NAME (t) == vtt_parm_identifier);
18022 current_vtt_parm = t;
18026 bool honor_interface = (!DECL_TEMPLATE_INSTANTIATION (decl1)
18027 /* Implicitly-defined methods (like the
18028 destructor for a class in which no destructor
18029 is explicitly declared) must not be defined
18030 until their definition is needed. So, we
18031 ignore interface specifications for
18032 compiler-generated functions. */
18033 && !DECL_ARTIFICIAL (decl1));
18034 struct c_fileinfo *finfo
18035 = get_fileinfo (LOCATION_FILE (DECL_SOURCE_LOCATION (decl1)));
18037 if (processing_template_decl)
18038 /* Don't mess with interface flags. */;
18039 else if (DECL_INTERFACE_KNOWN (decl1))
18041 tree ctx = decl_function_context (decl1);
18043 if (DECL_NOT_REALLY_EXTERN (decl1))
18044 DECL_EXTERNAL (decl1) = 0;
18046 if (ctx != NULL_TREE && vague_linkage_p (ctx))
18047 /* This is a function in a local class in an extern inline
18048 or template function. */
18049 comdat_linkage (decl1);
18051 /* If this function belongs to an interface, it is public.
18052 If it belongs to someone else's interface, it is also external.
18053 This only affects inlines and template instantiations. */
18054 else if (!finfo->interface_unknown && honor_interface)
18056 if (DECL_DECLARED_INLINE_P (decl1)
18057 || DECL_TEMPLATE_INSTANTIATION (decl1))
18059 DECL_EXTERNAL (decl1)
18060 = (finfo->interface_only
18061 || (DECL_DECLARED_INLINE_P (decl1)
18062 && ! flag_implement_inlines
18063 && !DECL_VINDEX (decl1)));
18065 /* For WIN32 we also want to put these in linkonce sections. */
18066 maybe_make_one_only (decl1);
18068 else
18069 DECL_EXTERNAL (decl1) = 0;
18070 DECL_INTERFACE_KNOWN (decl1) = 1;
18071 /* If this function is in an interface implemented in this file,
18072 make sure that the back end knows to emit this function
18073 here. */
18074 if (!DECL_EXTERNAL (decl1))
18075 mark_needed (decl1);
18077 else if (finfo->interface_unknown && finfo->interface_only
18078 && honor_interface)
18080 /* If MULTIPLE_SYMBOL_SPACES is defined and we saw a #pragma
18081 interface, we will have both finfo->interface_unknown and
18082 finfo->interface_only set. In that case, we don't want to
18083 use the normal heuristics because someone will supply a
18084 #pragma implementation elsewhere, and deducing it here would
18085 produce a conflict. */
18086 comdat_linkage (decl1);
18087 DECL_EXTERNAL (decl1) = 0;
18088 DECL_INTERFACE_KNOWN (decl1) = 1;
18089 DECL_DEFER_OUTPUT (decl1) = 1;
18091 else
18093 /* This is a definition, not a reference.
18094 So clear DECL_EXTERNAL, unless this is a GNU extern inline. */
18095 if (!GNU_INLINE_P (decl1))
18096 DECL_EXTERNAL (decl1) = 0;
18098 if ((DECL_DECLARED_INLINE_P (decl1)
18099 || DECL_TEMPLATE_INSTANTIATION (decl1))
18100 && ! DECL_INTERFACE_KNOWN (decl1))
18101 DECL_DEFER_OUTPUT (decl1) = 1;
18102 else
18103 DECL_INTERFACE_KNOWN (decl1) = 1;
18106 /* Determine the ELF visibility attribute for the function. We must not
18107 do this before calling "pushdecl", as we must allow "duplicate_decls"
18108 to merge any attributes appropriately. We also need to wait until
18109 linkage is set. */
18110 if (!DECL_CLONED_FUNCTION_P (decl1))
18111 determine_visibility (decl1);
18113 if (!processing_template_decl)
18114 maybe_instantiate_noexcept (decl1);
18116 begin_scope (sk_function_parms, decl1);
18118 ++function_depth;
18120 start_fname_decls ();
18122 store_parm_decls (current_function_parms);
18124 start_function_contracts (decl1);
18126 if (!processing_template_decl
18127 && (flag_lifetime_dse > 1)
18128 && DECL_CONSTRUCTOR_P (decl1)
18129 && !DECL_CLONED_FUNCTION_P (decl1)
18130 /* Clobbering an empty base is harmful if it overlays real data. */
18131 && !is_empty_class (current_class_type)
18132 /* We can't clobber safely for an implicitly-defined default constructor
18133 because part of the initialization might happen before we enter the
18134 constructor, via AGGR_INIT_ZERO_FIRST (c++/68006). */
18135 && !implicit_default_ctor_p (decl1))
18136 finish_expr_stmt (build_clobber_this (CLOBBER_OBJECT_BEGIN));
18138 if (!processing_template_decl
18139 && DECL_CONSTRUCTOR_P (decl1)
18140 && sanitize_flags_p (SANITIZE_VPTR)
18141 && !DECL_CLONED_FUNCTION_P (decl1)
18142 && !implicit_default_ctor_p (decl1))
18143 cp_ubsan_maybe_initialize_vtbl_ptrs (current_class_ptr);
18145 if (!DECL_OMP_DECLARE_REDUCTION_P (decl1))
18146 start_lambda_scope (decl1);
18148 return true;
18152 /* Like start_preparsed_function, except that instead of a
18153 FUNCTION_DECL, this function takes DECLSPECS and DECLARATOR.
18155 Returns true on success. If the DECLARATOR is not suitable
18156 for a function, we return false, which tells the parser to
18157 skip the entire function. */
18159 bool
18160 start_function (cp_decl_specifier_seq *declspecs,
18161 const cp_declarator *declarator,
18162 tree attrs)
18164 tree decl1;
18166 decl1 = grokdeclarator (declarator, declspecs, FUNCDEF, 1, &attrs);
18167 invoke_plugin_callbacks (PLUGIN_START_PARSE_FUNCTION, decl1);
18168 if (decl1 == error_mark_node)
18169 return false;
18171 if (DECL_MAIN_P (decl1))
18172 /* main must return int. grokfndecl should have corrected it
18173 (and issued a diagnostic) if the user got it wrong. */
18174 gcc_assert (same_type_p (TREE_TYPE (TREE_TYPE (decl1)),
18175 integer_type_node));
18177 return start_preparsed_function (decl1, attrs, /*flags=*/SF_DEFAULT);
18180 /* Returns true iff an EH_SPEC_BLOCK should be created in the body of
18181 FN. */
18183 static bool
18184 use_eh_spec_block (tree fn)
18186 return (flag_exceptions && flag_enforce_eh_specs
18187 && !processing_template_decl
18188 /* We insert the EH_SPEC_BLOCK only in the original
18189 function; then, it is copied automatically to the
18190 clones. */
18191 && !DECL_CLONED_FUNCTION_P (fn)
18192 /* Implicitly-generated constructors and destructors have
18193 exception specifications. However, those specifications
18194 are the union of the possible exceptions specified by the
18195 constructors/destructors for bases and members, so no
18196 unallowed exception will ever reach this function. By
18197 not creating the EH_SPEC_BLOCK we save a little memory,
18198 and we avoid spurious warnings about unreachable
18199 code. */
18200 && !DECL_DEFAULTED_FN (fn)
18201 && !type_throw_all_p (TREE_TYPE (fn)));
18204 /* Helper function to push ARGS into the current lexical scope. DECL
18205 is the function declaration. NONPARMS is used to handle enum
18206 constants. */
18208 void
18209 do_push_parm_decls (tree decl, tree args, tree *nonparms)
18211 /* If we're doing semantic analysis, then we'll call pushdecl
18212 for each of these. We must do them in reverse order so that
18213 they end in the correct forward order. */
18214 args = nreverse (args);
18216 tree next;
18217 for (tree parm = args; parm; parm = next)
18219 next = DECL_CHAIN (parm);
18220 if (TREE_CODE (parm) == PARM_DECL)
18221 pushdecl (parm);
18222 else if (nonparms)
18224 /* If we find an enum constant or a type tag, put it aside for
18225 the moment. */
18226 TREE_CHAIN (parm) = NULL_TREE;
18227 *nonparms = chainon (*nonparms, parm);
18231 /* Get the decls in their original chain order and record in the
18232 function. This is all and only the PARM_DECLs that were
18233 pushed into scope by the loop above. */
18234 DECL_ARGUMENTS (decl) = get_local_decls ();
18237 /* Store the parameter declarations into the current function declaration.
18238 This is called after parsing the parameter declarations, before
18239 digesting the body of the function.
18241 Also install to binding contour return value identifier, if any. */
18243 static void
18244 store_parm_decls (tree current_function_parms)
18246 tree fndecl = current_function_decl;
18248 /* This is a chain of any other decls that came in among the parm
18249 declarations. If a parm is declared with enum {foo, bar} x;
18250 then CONST_DECLs for foo and bar are put here. */
18251 tree nonparms = NULL_TREE;
18253 if (current_function_parms)
18255 /* This case is when the function was defined with an ANSI prototype.
18256 The parms already have decls, so we need not do anything here
18257 except record them as in effect
18258 and complain if any redundant old-style parm decls were written. */
18260 tree specparms = current_function_parms;
18262 /* Must clear this because it might contain TYPE_DECLs declared
18263 at class level. */
18264 current_binding_level->names = NULL;
18266 do_push_parm_decls (fndecl, specparms, &nonparms);
18268 else
18269 DECL_ARGUMENTS (fndecl) = NULL_TREE;
18271 /* Now store the final chain of decls for the arguments
18272 as the decl-chain of the current lexical scope.
18273 Put the enumerators in as well, at the front so that
18274 DECL_ARGUMENTS is not modified. */
18275 current_binding_level->names = chainon (nonparms, DECL_ARGUMENTS (fndecl));
18277 if (use_eh_spec_block (current_function_decl))
18278 current_eh_spec_block = begin_eh_spec_block ();
18282 /* Mark CDTOR's implicit THIS argument for returning, if required by
18283 the ABI.. Return the decl for THIS, if it is to be returned, and
18284 NULL otherwise. */
18286 tree
18287 maybe_prepare_return_this (tree cdtor)
18289 if (targetm.cxx.cdtor_returns_this ())
18290 if (tree val = DECL_ARGUMENTS (cdtor))
18292 suppress_warning (val, OPT_Wuse_after_free);
18293 return val;
18296 return NULL_TREE;
18299 /* Set the return value of the [cd]tor if the ABI wants that. */
18301 void
18302 maybe_return_this ()
18304 if (tree val = maybe_prepare_return_this (current_function_decl))
18306 /* Return the address of the object. */
18307 val = fold_convert (TREE_TYPE (DECL_RESULT (current_function_decl)), val);
18308 val = build2 (MODIFY_EXPR, TREE_TYPE (val),
18309 DECL_RESULT (current_function_decl), val);
18310 tree exprstmt = build_stmt (input_location, RETURN_EXPR, val);
18311 add_stmt (exprstmt);
18315 /* Do all the processing for the beginning of a destructor; set up the
18316 vtable pointers and cleanups for bases and members. */
18318 static void
18319 begin_destructor_body (void)
18321 tree compound_stmt;
18323 /* If the CURRENT_CLASS_TYPE is incomplete, we will have already
18324 issued an error message. We still want to try to process the
18325 body of the function, but initialize_vtbl_ptrs will crash if
18326 TYPE_BINFO is NULL. */
18327 if (COMPLETE_TYPE_P (current_class_type))
18329 compound_stmt = begin_compound_stmt (0);
18330 /* Make all virtual function table pointers in non-virtual base
18331 classes point to CURRENT_CLASS_TYPE's virtual function
18332 tables. */
18333 initialize_vtbl_ptrs (current_class_ptr);
18334 finish_compound_stmt (compound_stmt);
18336 if (flag_lifetime_dse
18337 /* Clobbering an empty base is harmful if it overlays real data. */
18338 && !is_empty_class (current_class_type))
18340 if (sanitize_flags_p (SANITIZE_VPTR)
18341 && (flag_sanitize_recover & SANITIZE_VPTR) == 0
18342 && TYPE_CONTAINS_VPTR_P (current_class_type))
18344 tree binfo = TYPE_BINFO (current_class_type);
18345 tree ref
18346 = cp_build_fold_indirect_ref (current_class_ptr);
18348 tree vtbl_ptr = build_vfield_ref (ref, TREE_TYPE (binfo));
18349 tree vtbl = build_zero_cst (TREE_TYPE (vtbl_ptr));
18350 tree stmt = cp_build_modify_expr (input_location, vtbl_ptr,
18351 NOP_EXPR, vtbl,
18352 tf_warning_or_error);
18353 /* If the vptr is shared with some virtual nearly empty base,
18354 don't clear it if not in charge, the dtor of the virtual
18355 nearly empty base will do that later. */
18356 if (CLASSTYPE_VBASECLASSES (current_class_type))
18358 tree c = current_class_type;
18359 while (CLASSTYPE_PRIMARY_BINFO (c))
18361 if (BINFO_VIRTUAL_P (CLASSTYPE_PRIMARY_BINFO (c)))
18363 stmt = convert_to_void (stmt, ICV_STATEMENT,
18364 tf_warning_or_error);
18365 stmt = build_if_in_charge (stmt);
18366 break;
18368 c = BINFO_TYPE (CLASSTYPE_PRIMARY_BINFO (c));
18371 finish_decl_cleanup (NULL_TREE, stmt);
18373 else
18374 finish_decl_cleanup (NULL_TREE,
18375 build_clobber_this (CLOBBER_OBJECT_END));
18378 /* And insert cleanups for our bases and members so that they
18379 will be properly destroyed if we throw. */
18380 push_base_cleanups ();
18384 /* Do the necessary processing for the beginning of a function body, which
18385 in this case includes member-initializers, but not the catch clauses of
18386 a function-try-block. Currently, this means opening a binding level
18387 for the member-initializers (in a ctor), member cleanups (in a dtor),
18388 and capture proxies (in a lambda operator()). */
18390 tree
18391 begin_function_body (void)
18393 if (! FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
18394 return NULL_TREE;
18396 if (processing_template_decl)
18397 /* Do nothing now. */;
18398 else
18399 /* Always keep the BLOCK node associated with the outermost pair of
18400 curly braces of a function. These are needed for correct
18401 operation of dwarfout.c. */
18402 keep_next_level (true);
18404 tree stmt = begin_compound_stmt (BCS_FN_BODY);
18405 current_binding_level->artificial = 1;
18407 if (processing_template_decl)
18408 /* Do nothing now. */;
18409 else if (DECL_DESTRUCTOR_P (current_function_decl))
18410 begin_destructor_body ();
18412 return stmt;
18415 /* Do the processing for the end of a function body. Currently, this means
18416 closing out the cleanups for fully-constructed bases and members, and in
18417 the case of the destructor, deleting the object if desired. Again, this
18418 is only meaningful for [cd]tors, since they are the only functions where
18419 there is a significant distinction between the main body and any
18420 function catch clauses. Handling, say, main() return semantics here
18421 would be wrong, as flowing off the end of a function catch clause for
18422 main() would also need to return 0. */
18424 void
18425 finish_function_body (tree compstmt)
18427 if (compstmt == NULL_TREE)
18428 return;
18430 /* Close the block. */
18431 finish_compound_stmt (compstmt);
18433 if (processing_template_decl)
18434 /* Do nothing now. */;
18435 else if (DECL_CONSTRUCTOR_P (current_function_decl)
18436 || DECL_DESTRUCTOR_P (current_function_decl))
18437 maybe_return_this ();
18440 /* Given a function, returns the BLOCK corresponding to the outermost level
18441 of curly braces, skipping the artificial block created for constructor
18442 initializers. */
18444 tree
18445 outer_curly_brace_block (tree fndecl)
18447 tree block = DECL_INITIAL (fndecl);
18448 if (BLOCK_OUTER_CURLY_BRACE_P (block))
18449 return block;
18450 block = BLOCK_SUBBLOCKS (block);
18451 if (BLOCK_OUTER_CURLY_BRACE_P (block))
18452 return block;
18453 block = BLOCK_SUBBLOCKS (block);
18454 gcc_assert (BLOCK_OUTER_CURLY_BRACE_P (block));
18455 return block;
18458 /* If FNDECL is a class's key method, add the class to the list of
18459 keyed classes that should be emitted. */
18461 static void
18462 record_key_method_defined (tree fndecl)
18464 if (DECL_OBJECT_MEMBER_FUNCTION_P (fndecl)
18465 && DECL_VIRTUAL_P (fndecl)
18466 && !processing_template_decl)
18468 tree fnclass = DECL_CONTEXT (fndecl);
18469 if (fndecl == CLASSTYPE_KEY_METHOD (fnclass))
18470 vec_safe_push (keyed_classes, fnclass);
18474 /* Attempt to add a fix-it hint to RICHLOC suggesting the insertion
18475 of "return *this;" immediately before its location, using FNDECL's
18476 first statement (if any) to give the indentation, if appropriate. */
18478 static void
18479 add_return_star_this_fixit (gcc_rich_location *richloc, tree fndecl)
18481 location_t indent = UNKNOWN_LOCATION;
18482 tree stmts = expr_first (DECL_SAVED_TREE (fndecl));
18483 if (stmts)
18484 indent = EXPR_LOCATION (stmts);
18485 richloc->add_fixit_insert_formatted ("return *this;",
18486 richloc->get_loc (),
18487 indent);
18490 /* This function carries out the subset of finish_function operations needed
18491 to emit the compiler-generated outlined helper functions used by the
18492 coroutines implementation. */
18494 static void
18495 emit_coro_helper (tree helper)
18497 /* This is a partial set of the operations done by finish_function()
18498 plus emitting the result. */
18499 set_cfun (NULL);
18500 current_function_decl = helper;
18501 begin_scope (sk_function_parms, NULL);
18502 store_parm_decls (DECL_ARGUMENTS (helper));
18503 announce_function (helper);
18504 allocate_struct_function (helper, false);
18505 cfun->language = ggc_cleared_alloc<language_function> ();
18506 poplevel (1, 0, 1);
18507 maybe_save_constexpr_fundef (helper);
18508 /* We must start each function with a clear fold cache. */
18509 clear_fold_cache ();
18510 cp_fold_function (helper);
18511 DECL_CONTEXT (DECL_RESULT (helper)) = helper;
18512 BLOCK_SUPERCONTEXT (DECL_INITIAL (helper)) = helper;
18513 /* This function has coroutine IFNs that we should handle in middle
18514 end lowering. */
18515 cfun->coroutine_component = true;
18516 cp_genericize (helper);
18517 expand_or_defer_fn (helper);
18520 /* Finish up a function declaration and compile that function
18521 all the way to assembler language output. The free the storage
18522 for the function definition. INLINE_P is TRUE if we just
18523 finished processing the body of an in-class inline function
18524 definition. (This processing will have taken place after the
18525 class definition is complete.) */
18527 tree
18528 finish_function (bool inline_p)
18530 tree fndecl = current_function_decl;
18531 tree fntype, ctype = NULL_TREE;
18532 tree resumer = NULL_TREE, destroyer = NULL_TREE;
18533 bool coro_p = flag_coroutines
18534 && !processing_template_decl
18535 && DECL_COROUTINE_P (fndecl);
18536 bool coro_emit_helpers = false;
18538 /* When we get some parse errors, we can end up without a
18539 current_function_decl, so cope. */
18540 if (fndecl == NULL_TREE)
18541 return error_mark_node;
18543 if (!DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18544 finish_lambda_scope ();
18546 if (c_dialect_objc ())
18547 objc_finish_function ();
18549 record_key_method_defined (fndecl);
18551 fntype = TREE_TYPE (fndecl);
18553 /* TREE_READONLY (fndecl) = 1;
18554 This caused &foo to be of type ptr-to-const-function
18555 which then got a warning when stored in a ptr-to-function variable. */
18557 gcc_assert (building_stmt_list_p ());
18558 /* The current function is being defined, so its DECL_INITIAL should
18559 be set, and unless there's a multiple definition, it should be
18560 error_mark_node. */
18561 gcc_assert (DECL_INITIAL (fndecl) == error_mark_node);
18563 if (coro_p)
18565 /* Only try to emit the coroutine outlined helper functions if the
18566 transforms succeeded. Otherwise, treat errors in the same way as
18567 a regular function. */
18568 coro_emit_helpers = morph_fn_to_coro (fndecl, &resumer, &destroyer);
18570 /* We should handle coroutine IFNs in middle end lowering. */
18571 cfun->coroutine_component = true;
18573 /* Do not try to process the ramp's EH unless outlining succeeded. */
18574 if (coro_emit_helpers && use_eh_spec_block (fndecl))
18575 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
18576 (TREE_TYPE (fndecl)),
18577 current_eh_spec_block);
18579 else
18580 /* For a cloned function, we've already got all the code we need;
18581 there's no need to add any extra bits. */
18582 if (!DECL_CLONED_FUNCTION_P (fndecl))
18584 /* Make it so that `main' always returns 0 by default. */
18585 if (DECL_MAIN_FREESTANDING_P (current_function_decl)
18586 && !TREE_THIS_VOLATILE (current_function_decl))
18587 finish_return_stmt (integer_zero_node);
18589 if (use_eh_spec_block (current_function_decl))
18590 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
18591 (TREE_TYPE (current_function_decl)),
18592 current_eh_spec_block);
18595 /* If we're saving up tree structure, tie off the function now. */
18596 DECL_SAVED_TREE (fndecl) = pop_stmt_list (DECL_SAVED_TREE (fndecl));
18598 finish_fname_decls ();
18600 /* This must come after expand_function_end because cleanups might
18601 have declarations (from inline functions) that need to go into
18602 this function's blocks. */
18604 /* If the current binding level isn't the outermost binding level
18605 for this function, either there is a bug, or we have experienced
18606 syntax errors and the statement tree is malformed. */
18607 if (current_binding_level->kind != sk_function_parms)
18609 /* Make sure we have already experienced errors. */
18610 gcc_assert (errorcount);
18612 /* Throw away the broken statement tree and extra binding
18613 levels. */
18614 DECL_SAVED_TREE (fndecl) = alloc_stmt_list ();
18616 while (current_binding_level->kind != sk_function_parms)
18618 if (current_binding_level->kind == sk_class)
18619 pop_nested_class ();
18620 else
18621 poplevel (0, 0, 0);
18624 poplevel (1, 0, 1);
18626 /* Statements should always be full-expressions at the outermost set
18627 of curly braces for a function. */
18628 gcc_assert (stmts_are_full_exprs_p ());
18630 /* If there are no return statements in a function with auto return type,
18631 the return type is void. But if the declared type is something like
18632 auto*, this is an error. */
18633 if (!processing_template_decl && FNDECL_USED_AUTO (fndecl)
18634 && TREE_TYPE (fntype) == DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
18636 if (is_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
18637 && !current_function_returns_value
18638 && !current_function_returns_null)
18640 /* We haven't applied return type deduction because we haven't
18641 seen any return statements. Do that now. */
18642 tree node = type_uses_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
18643 do_auto_deduction (DECL_SAVED_AUTO_RETURN_TYPE (fndecl),
18644 void_node, node, tf_warning_or_error,
18645 adc_return_type);
18647 apply_deduced_return_type (fndecl, void_type_node);
18648 fntype = TREE_TYPE (fndecl);
18650 else if (!current_function_returns_value
18651 && !current_function_returns_null)
18653 error ("no return statements in function returning %qT",
18654 DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
18655 inform (input_location, "only plain %<auto%> return type can be "
18656 "deduced to %<void%>");
18660 /* Remember that we were in class scope. */
18661 if (current_class_name)
18662 ctype = current_class_type;
18664 if (DECL_DELETED_FN (fndecl))
18666 DECL_INITIAL (fndecl) = error_mark_node;
18667 DECL_SAVED_TREE (fndecl) = NULL_TREE;
18668 goto cleanup;
18671 // If this is a concept, check that the definition is reasonable.
18672 if (DECL_DECLARED_CONCEPT_P (fndecl))
18673 check_function_concept (fndecl);
18675 if (flag_openmp)
18676 if (tree attr = lookup_attribute ("omp declare variant base",
18677 DECL_ATTRIBUTES (fndecl)))
18678 omp_declare_variant_finalize (fndecl, attr);
18680 /* Complain if there's just no return statement. */
18681 if ((warn_return_type
18682 || (cxx_dialect >= cxx14
18683 && DECL_DECLARED_CONSTEXPR_P (fndecl)))
18684 && !VOID_TYPE_P (TREE_TYPE (fntype))
18685 && !dependent_type_p (TREE_TYPE (fntype))
18686 && !current_function_returns_value && !current_function_returns_null
18687 /* Don't complain if we abort or throw. */
18688 && !current_function_returns_abnormally
18689 /* Don't complain if there's an infinite loop. */
18690 && !current_function_infinite_loop
18691 /* Don't complain if we are declared noreturn. */
18692 && !TREE_THIS_VOLATILE (fndecl)
18693 && !DECL_NAME (DECL_RESULT (fndecl))
18694 && !warning_suppressed_p (fndecl, OPT_Wreturn_type)
18695 /* Structor return values (if any) are set by the compiler. */
18696 && !DECL_CONSTRUCTOR_P (fndecl)
18697 && !DECL_DESTRUCTOR_P (fndecl)
18698 && targetm.warn_func_return (fndecl))
18700 gcc_rich_location richloc (input_location);
18701 /* Potentially add a "return *this;" fix-it hint for
18702 assignment operators. */
18703 if (IDENTIFIER_ASSIGN_OP_P (DECL_NAME (fndecl)))
18705 tree valtype = TREE_TYPE (DECL_RESULT (fndecl));
18706 if (TREE_CODE (valtype) == REFERENCE_TYPE
18707 && current_class_ref
18708 && same_type_ignoring_top_level_qualifiers_p
18709 (TREE_TYPE (valtype), TREE_TYPE (current_class_ref))
18710 && global_dc->option_enabled_p (OPT_Wreturn_type))
18711 add_return_star_this_fixit (&richloc, fndecl);
18713 if (cxx_dialect >= cxx14
18714 && DECL_DECLARED_CONSTEXPR_P (fndecl))
18715 error_at (&richloc, "no return statement in %<constexpr%> function "
18716 "returning non-void");
18717 else if (warning_at (&richloc, OPT_Wreturn_type,
18718 "no return statement in function returning "
18719 "non-void"))
18720 suppress_warning (fndecl, OPT_Wreturn_type);
18723 /* Lambda closure members are implicitly constexpr if possible. */
18724 if (cxx_dialect >= cxx17
18725 && LAMBDA_TYPE_P (CP_DECL_CONTEXT (fndecl)))
18726 DECL_DECLARED_CONSTEXPR_P (fndecl)
18727 = ((processing_template_decl
18728 || is_valid_constexpr_fn (fndecl, /*complain*/false))
18729 && potential_constant_expression (DECL_SAVED_TREE (fndecl)));
18731 /* Save constexpr function body before it gets munged by
18732 the NRV transformation. */
18733 maybe_save_constexpr_fundef (fndecl);
18735 /* Invoke the pre-genericize plugin before we start munging things. */
18736 if (!processing_template_decl)
18737 invoke_plugin_callbacks (PLUGIN_PRE_GENERICIZE, fndecl);
18739 /* Perform delayed folding before NRV transformation. */
18740 if (!processing_template_decl
18741 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
18742 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18743 cp_fold_function (fndecl);
18745 /* Set up the named return value optimization, if we can. Candidate
18746 variables are selected in check_return_expr. */
18747 if (tree r = current_function_return_value)
18749 if (r != error_mark_node)
18750 finalize_nrv (fndecl, r);
18751 current_function_return_value = NULL_TREE;
18754 /* Must mark the RESULT_DECL as being in this function. */
18755 DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
18757 /* Set the BLOCK_SUPERCONTEXT of the outermost function scope to point
18758 to the FUNCTION_DECL node itself. */
18759 BLOCK_SUPERCONTEXT (DECL_INITIAL (fndecl)) = fndecl;
18761 /* Store the end of the function, so that we get good line number
18762 info for the epilogue. */
18763 cfun->function_end_locus = input_location;
18765 /* Complain about parameters that are only set, but never otherwise used. */
18766 if (warn_unused_but_set_parameter
18767 && !processing_template_decl
18768 && errorcount == unused_but_set_errorcount
18769 && !DECL_CLONED_FUNCTION_P (fndecl))
18771 tree decl;
18773 for (decl = DECL_ARGUMENTS (fndecl);
18774 decl;
18775 decl = DECL_CHAIN (decl))
18776 if (TREE_USED (decl)
18777 && TREE_CODE (decl) == PARM_DECL
18778 && !DECL_READ_P (decl)
18779 && DECL_NAME (decl)
18780 && !DECL_ARTIFICIAL (decl)
18781 && !warning_suppressed_p (decl,OPT_Wunused_but_set_parameter)
18782 && !DECL_IN_SYSTEM_HEADER (decl)
18783 && TREE_TYPE (decl) != error_mark_node
18784 && !TYPE_REF_P (TREE_TYPE (decl))
18785 && (!CLASS_TYPE_P (TREE_TYPE (decl))
18786 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl))))
18787 warning_at (DECL_SOURCE_LOCATION (decl),
18788 OPT_Wunused_but_set_parameter,
18789 "parameter %qD set but not used", decl);
18790 unused_but_set_errorcount = errorcount;
18793 /* Complain about locally defined typedefs that are not used in this
18794 function. */
18795 maybe_warn_unused_local_typedefs ();
18797 /* Possibly warn about unused parameters. */
18798 if (warn_unused_parameter
18799 && !processing_template_decl
18800 && !DECL_CLONED_FUNCTION_P (fndecl))
18801 do_warn_unused_parameter (fndecl);
18803 /* Genericize before inlining. */
18804 if (!processing_template_decl
18805 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
18806 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18807 cp_genericize (fndecl);
18809 /* If this function can't throw any exceptions, remember that. */
18810 if (!processing_template_decl
18811 && !cp_function_chain->can_throw
18812 && !flag_non_call_exceptions
18813 && !decl_replaceable_p (fndecl,
18814 opt_for_fn (fndecl, flag_semantic_interposition)))
18815 TREE_NOTHROW (fndecl) = 1;
18817 /* Emit the resumer and destroyer functions now, providing that we have
18818 not encountered some fatal error. */
18819 if (coro_emit_helpers)
18821 emit_coro_helper (resumer);
18822 emit_coro_helper (destroyer);
18825 cleanup:
18826 /* We're leaving the context of this function, so zap cfun. It's still in
18827 DECL_STRUCT_FUNCTION, and we'll restore it in tree_rest_of_compilation. */
18828 set_cfun (NULL);
18829 current_function_decl = NULL;
18831 /* If this is an in-class inline definition, we may have to pop the
18832 bindings for the template parameters that we added in
18833 maybe_begin_member_template_processing when start_function was
18834 called. */
18835 if (inline_p)
18836 maybe_end_member_template_processing ();
18838 /* Leave the scope of the class. */
18839 if (ctype)
18840 pop_nested_class ();
18842 --function_depth;
18844 /* Clean up. */
18845 current_function_decl = NULL_TREE;
18847 invoke_plugin_callbacks (PLUGIN_FINISH_PARSE_FUNCTION, fndecl);
18849 finish_function_contracts (fndecl);
18851 return fndecl;
18854 /* Create the FUNCTION_DECL for a function definition.
18855 DECLSPECS and DECLARATOR are the parts of the declaration;
18856 they describe the return type and the name of the function,
18857 but twisted together in a fashion that parallels the syntax of C.
18859 This function creates a binding context for the function body
18860 as well as setting up the FUNCTION_DECL in current_function_decl.
18862 Returns a FUNCTION_DECL on success.
18864 If the DECLARATOR is not suitable for a function (it defines a datum
18865 instead), we return 0, which tells yyparse to report a parse error.
18867 May return void_type_node indicating that this method is actually
18868 a friend. See grokfield for more details.
18870 Came here with a `.pushlevel' .
18872 DO NOT MAKE ANY CHANGES TO THIS CODE WITHOUT MAKING CORRESPONDING
18873 CHANGES TO CODE IN `grokfield'. */
18875 tree
18876 grokmethod (cp_decl_specifier_seq *declspecs,
18877 const cp_declarator *declarator, tree attrlist)
18879 tree fndecl = grokdeclarator (declarator, declspecs, MEMFUNCDEF, 0,
18880 &attrlist);
18882 if (fndecl == error_mark_node)
18883 return error_mark_node;
18885 if (attrlist)
18886 cplus_decl_attributes (&fndecl, attrlist, 0);
18888 /* Pass friends other than inline friend functions back. */
18889 if (fndecl == void_type_node)
18890 return fndecl;
18892 if (DECL_IN_AGGR_P (fndecl))
18894 if (DECL_CLASS_SCOPE_P (fndecl))
18895 error ("%qD is already defined in class %qT", fndecl,
18896 DECL_CONTEXT (fndecl));
18897 return error_mark_node;
18900 check_template_shadow (fndecl);
18902 /* p1779 ABI-Isolation makes inline not a default for in-class
18903 definitions in named module purview. If the user explicitly
18904 made it inline, grokdeclarator will already have done the right
18905 things. */
18906 if ((!named_module_purview_p ()
18907 || flag_module_implicit_inline
18908 /* Lambda's operator function remains inline. */
18909 || LAMBDA_TYPE_P (DECL_CONTEXT (fndecl)))
18910 /* If the user explicitly asked for this to be inline, we don't
18911 need to do more, but more importantly we want to warn if we
18912 can't inline it. */
18913 && !DECL_DECLARED_INLINE_P (fndecl))
18915 if (TREE_PUBLIC (fndecl))
18916 DECL_COMDAT (fndecl) = 1;
18917 DECL_DECLARED_INLINE_P (fndecl) = 1;
18918 /* It's ok if we can't inline this. */
18919 DECL_NO_INLINE_WARNING_P (fndecl) = 1;
18922 /* We process method specializations in finish_struct_1. */
18923 if (processing_template_decl && !DECL_TEMPLATE_SPECIALIZATION (fndecl))
18925 /* Avoid calling decl_spec_seq... until we have to. */
18926 bool friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
18927 fndecl = push_template_decl (fndecl, friendp);
18928 if (fndecl == error_mark_node)
18929 return fndecl;
18932 if (DECL_CHAIN (fndecl) && !decl_spec_seq_has_spec_p (declspecs, ds_friend))
18934 fndecl = copy_node (fndecl);
18935 TREE_CHAIN (fndecl) = NULL_TREE;
18938 cp_finish_decl (fndecl, NULL_TREE, false, NULL_TREE, 0);
18940 DECL_IN_AGGR_P (fndecl) = 1;
18941 return fndecl;
18945 /* VAR is a VAR_DECL. If its type is incomplete, remember VAR so that
18946 we can lay it out later, when and if its type becomes complete.
18948 Also handle constexpr variables where the initializer involves
18949 an unlowered PTRMEM_CST because the class isn't complete yet. */
18951 void
18952 maybe_register_incomplete_var (tree var)
18954 gcc_assert (VAR_P (var));
18956 /* Keep track of variables with incomplete types. */
18957 if (!processing_template_decl && TREE_TYPE (var) != error_mark_node
18958 && DECL_EXTERNAL (var))
18960 tree inner_type = TREE_TYPE (var);
18962 while (TREE_CODE (inner_type) == ARRAY_TYPE)
18963 inner_type = TREE_TYPE (inner_type);
18964 inner_type = TYPE_MAIN_VARIANT (inner_type);
18966 if ((!COMPLETE_TYPE_P (inner_type) && CLASS_TYPE_P (inner_type))
18967 /* RTTI TD entries are created while defining the type_info. */
18968 || (TYPE_LANG_SPECIFIC (inner_type)
18969 && TYPE_BEING_DEFINED (inner_type)))
18971 incomplete_var iv = {var, inner_type};
18972 vec_safe_push (incomplete_vars, iv);
18974 else if (!(DECL_LANG_SPECIFIC (var) && DECL_TEMPLATE_INFO (var))
18975 && decl_constant_var_p (var)
18976 && (TYPE_PTRMEM_P (inner_type) || CLASS_TYPE_P (inner_type)))
18978 /* When the outermost open class is complete we can resolve any
18979 pointers-to-members. */
18980 tree context = outermost_open_class ();
18981 incomplete_var iv = {var, context};
18982 vec_safe_push (incomplete_vars, iv);
18987 /* Called when a class type (given by TYPE) is defined. If there are
18988 any existing VAR_DECLs whose type has been completed by this
18989 declaration, update them now. */
18991 void
18992 complete_vars (tree type)
18994 unsigned ix;
18995 incomplete_var *iv;
18997 for (ix = 0; vec_safe_iterate (incomplete_vars, ix, &iv); )
18999 if (same_type_p (type, iv->incomplete_type))
19001 tree var = iv->decl;
19002 tree type = TREE_TYPE (var);
19004 if (type != error_mark_node
19005 && (TYPE_MAIN_VARIANT (strip_array_types (type))
19006 == iv->incomplete_type))
19008 /* Complete the type of the variable. */
19009 complete_type (type);
19010 cp_apply_type_quals_to_decl (cp_type_quals (type), var);
19011 if (COMPLETE_TYPE_P (type))
19012 layout_var_decl (var);
19015 /* Remove this entry from the list. */
19016 incomplete_vars->unordered_remove (ix);
19018 else
19019 ix++;
19023 /* If DECL is of a type which needs a cleanup, build and return an
19024 expression to perform that cleanup here. Return NULL_TREE if no
19025 cleanup need be done. DECL can also be a _REF when called from
19026 split_nonconstant_init_1. */
19028 tree
19029 cxx_maybe_build_cleanup (tree decl, tsubst_flags_t complain)
19031 tree type;
19032 tree attr;
19033 tree cleanup;
19035 /* Assume no cleanup is required. */
19036 cleanup = NULL_TREE;
19038 if (error_operand_p (decl))
19039 return cleanup;
19041 /* Handle "__attribute__((cleanup))". We run the cleanup function
19042 before the destructor since the destructor is what actually
19043 terminates the lifetime of the object. */
19044 if (DECL_P (decl))
19045 attr = lookup_attribute ("cleanup", DECL_ATTRIBUTES (decl));
19046 else
19047 attr = NULL_TREE;
19048 if (attr)
19050 tree id;
19051 tree fn;
19052 tree arg;
19054 /* Get the name specified by the user for the cleanup function. */
19055 id = TREE_VALUE (TREE_VALUE (attr));
19056 /* Look up the name to find the cleanup function to call. It is
19057 important to use lookup_name here because that is what is
19058 used in c-common.cc:handle_cleanup_attribute when performing
19059 initial checks on the attribute. Note that those checks
19060 include ensuring that the function found is not an overloaded
19061 function, or an object with an overloaded call operator,
19062 etc.; we can rely on the fact that the function found is an
19063 ordinary FUNCTION_DECL. */
19064 fn = lookup_name (id);
19065 arg = build_address (decl);
19066 if (!mark_used (decl, complain) && !(complain & tf_error))
19067 return error_mark_node;
19068 cleanup = cp_build_function_call_nary (fn, complain, arg, NULL_TREE);
19069 if (cleanup == error_mark_node)
19070 return error_mark_node;
19072 /* Handle ordinary C++ destructors. */
19073 type = TREE_TYPE (decl);
19074 if (type_build_dtor_call (type))
19076 int flags = LOOKUP_NORMAL|LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR;
19077 tree addr;
19078 tree call;
19080 if (TREE_CODE (type) == ARRAY_TYPE)
19081 addr = decl;
19082 else
19083 addr = build_address (decl);
19085 call = build_delete (input_location, TREE_TYPE (addr), addr,
19086 sfk_complete_destructor, flags, 0, complain);
19087 if (call == error_mark_node)
19088 cleanup = error_mark_node;
19089 else if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
19090 /* Discard the call. */;
19091 else if (decl_maybe_constant_destruction (decl, type)
19092 && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
19093 cxx_constant_dtor (call, decl);
19094 else if (cleanup)
19095 cleanup = cp_build_compound_expr (cleanup, call, complain);
19096 else
19097 cleanup = call;
19100 /* build_delete sets the location of the destructor call to the
19101 current location, even though the destructor is going to be
19102 called later, at the end of the current scope. This can lead to
19103 a "jumpy" behavior for users of debuggers when they step around
19104 the end of the block. So let's unset the location of the
19105 destructor call instead. */
19106 protected_set_expr_location (cleanup, UNKNOWN_LOCATION);
19107 if (cleanup && CONVERT_EXPR_P (cleanup))
19108 protected_set_expr_location (TREE_OPERAND (cleanup, 0), UNKNOWN_LOCATION);
19110 if (cleanup
19111 && DECL_P (decl)
19112 && !lookup_attribute ("warn_unused", TYPE_ATTRIBUTES (TREE_TYPE (decl)))
19113 /* Treat objects with destructors as used; the destructor may do
19114 something substantive. */
19115 && !mark_used (decl, complain) && !(complain & tf_error))
19116 return error_mark_node;
19118 if (cleanup && cfun && !processing_template_decl
19119 && !expr_noexcept_p (cleanup, tf_none))
19120 cp_function_chain->throwing_cleanup = true;
19122 return cleanup;
19126 /* Return the FUNCTION_TYPE that corresponds to MEMFNTYPE, which can be a
19127 FUNCTION_DECL, METHOD_TYPE, FUNCTION_TYPE, pointer or reference to
19128 METHOD_TYPE or FUNCTION_TYPE, or pointer to member function. */
19130 tree
19131 static_fn_type (tree memfntype)
19133 tree fntype;
19134 tree args;
19136 if (TYPE_PTRMEMFUNC_P (memfntype))
19137 memfntype = TYPE_PTRMEMFUNC_FN_TYPE (memfntype);
19138 if (INDIRECT_TYPE_P (memfntype)
19139 || TREE_CODE (memfntype) == FUNCTION_DECL)
19140 memfntype = TREE_TYPE (memfntype);
19141 if (TREE_CODE (memfntype) == FUNCTION_TYPE)
19142 return memfntype;
19143 gcc_assert (TREE_CODE (memfntype) == METHOD_TYPE);
19144 args = TYPE_ARG_TYPES (memfntype);
19145 fntype = build_function_type (TREE_TYPE (memfntype), TREE_CHAIN (args));
19146 fntype = apply_memfn_quals (fntype, type_memfn_quals (memfntype));
19147 fntype = (cp_build_type_attribute_variant
19148 (fntype, TYPE_ATTRIBUTES (memfntype)));
19149 fntype = cxx_copy_lang_qualifiers (fntype, memfntype);
19150 return fntype;
19153 /* DECL was originally constructed as a non-static member function,
19154 but turned out to be static. Update it accordingly. */
19156 void
19157 revert_static_member_fn (tree decl)
19159 tree stype = static_fn_type (decl);
19160 cp_cv_quals quals = type_memfn_quals (stype);
19161 cp_ref_qualifier rqual = type_memfn_rqual (stype);
19163 if (quals != TYPE_UNQUALIFIED || rqual != REF_QUAL_NONE)
19164 stype = apply_memfn_quals (stype, TYPE_UNQUALIFIED, REF_QUAL_NONE);
19166 TREE_TYPE (decl) = stype;
19168 if (DECL_ARGUMENTS (decl))
19169 DECL_ARGUMENTS (decl) = DECL_CHAIN (DECL_ARGUMENTS (decl));
19170 DECL_STATIC_FUNCTION_P (decl) = 1;
19173 /* Return which tree structure is used by T, or TS_CP_GENERIC if T is
19174 one of the language-independent trees. */
19176 enum cp_tree_node_structure_enum
19177 cp_tree_node_structure (union lang_tree_node * t)
19179 switch (TREE_CODE (&t->generic))
19181 case ARGUMENT_PACK_SELECT: return TS_CP_ARGUMENT_PACK_SELECT;
19182 case BASELINK: return TS_CP_BASELINK;
19183 case CONSTRAINT_INFO: return TS_CP_CONSTRAINT_INFO;
19184 case DEFERRED_NOEXCEPT: return TS_CP_DEFERRED_NOEXCEPT;
19185 case DEFERRED_PARSE: return TS_CP_DEFERRED_PARSE;
19186 case IDENTIFIER_NODE: return TS_CP_IDENTIFIER;
19187 case LAMBDA_EXPR: return TS_CP_LAMBDA_EXPR;
19188 case BINDING_VECTOR: return TS_CP_BINDING_VECTOR;
19189 case OVERLOAD: return TS_CP_OVERLOAD;
19190 case PTRMEM_CST: return TS_CP_PTRMEM;
19191 case STATIC_ASSERT: return TS_CP_STATIC_ASSERT;
19192 case TEMPLATE_DECL: return TS_CP_TEMPLATE_DECL;
19193 case TEMPLATE_INFO: return TS_CP_TEMPLATE_INFO;
19194 case TEMPLATE_PARM_INDEX: return TS_CP_TPI;
19195 case TRAIT_EXPR: return TS_CP_TRAIT_EXPR;
19196 case USERDEF_LITERAL: return TS_CP_USERDEF_LITERAL;
19197 default: return TS_CP_GENERIC;
19201 bool
19202 cp_missing_noreturn_ok_p (tree decl)
19204 /* A missing noreturn is ok for the `main' function. */
19205 return DECL_MAIN_P (decl);
19208 /* Return the decl used to identify the COMDAT group into which DECL should
19209 be placed. */
19211 tree
19212 cxx_comdat_group (tree decl)
19214 /* Virtual tables, construction virtual tables, and virtual table
19215 tables all go in a single COMDAT group, named after the primary
19216 virtual table. */
19217 if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
19218 decl = CLASSTYPE_VTABLES (DECL_CONTEXT (decl));
19219 /* For all other DECLs, the COMDAT group is the mangled name of the
19220 declaration itself. */
19221 else
19223 while (DECL_THUNK_P (decl))
19225 /* If TARGET_USE_LOCAL_THUNK_ALIAS_P, use_thunk puts the thunk
19226 into the same section as the target function. In that case
19227 we must return target's name. */
19228 tree target = THUNK_TARGET (decl);
19229 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (target)
19230 && DECL_SECTION_NAME (target) != NULL
19231 && DECL_ONE_ONLY (target))
19232 decl = target;
19233 else
19234 break;
19238 return decl;
19241 /* Returns the return type for FN as written by the user, which may include
19242 a placeholder for a deduced return type. */
19244 tree
19245 fndecl_declared_return_type (tree fn)
19247 fn = STRIP_TEMPLATE (fn);
19248 if (FNDECL_USED_AUTO (fn))
19249 return DECL_SAVED_AUTO_RETURN_TYPE (fn);
19251 return TREE_TYPE (TREE_TYPE (fn));
19254 /* Returns true iff DECL is a variable or function declared with an auto type
19255 that has not yet been deduced to a real type. */
19257 bool
19258 undeduced_auto_decl (tree decl)
19260 if (cxx_dialect < cxx11)
19261 return false;
19262 STRIP_ANY_LOCATION_WRAPPER (decl);
19263 return ((VAR_OR_FUNCTION_DECL_P (decl)
19264 || TREE_CODE (decl) == TEMPLATE_DECL)
19265 && type_uses_auto (TREE_TYPE (decl)));
19268 /* Complain if DECL has an undeduced return type. */
19270 bool
19271 require_deduced_type (tree decl, tsubst_flags_t complain)
19273 if (undeduced_auto_decl (decl))
19275 if (TREE_CODE (decl) == FUNCTION_DECL
19276 && fndecl_built_in_p (decl, BUILT_IN_FRONTEND)
19277 && DECL_FE_FUNCTION_CODE (decl) == CP_BUILT_IN_SOURCE_LOCATION)
19279 /* Set the return type of __builtin_source_location. */
19280 tree type = get_source_location_impl_type ();
19281 if (type == error_mark_node)
19283 inform (input_location, "using %qs", "__builtin_source_location");
19284 return false;
19286 type = cp_build_qualified_type (type, TYPE_QUAL_CONST);
19287 type = build_pointer_type (type);
19288 apply_deduced_return_type (decl, type);
19289 return true;
19292 if (warning_suppressed_p (decl) && seen_error ())
19293 /* We probably already complained about deduction failure. */;
19294 else if (complain & tf_error)
19295 error ("use of %qD before deduction of %<auto%>", decl);
19296 note_failed_type_completion_for_satisfaction (decl);
19297 return false;
19299 return true;
19302 /* Create a representation of the explicit-specifier with
19303 constant-expression of EXPR. COMPLAIN is as for tsubst. */
19305 tree
19306 build_explicit_specifier (tree expr, tsubst_flags_t complain)
19308 if (check_for_bare_parameter_packs (expr))
19309 return error_mark_node;
19311 if (instantiation_dependent_expression_p (expr))
19312 /* Wait for instantiation, tsubst_function_decl will handle it. */
19313 return expr;
19315 expr = build_converted_constant_bool_expr (expr, complain);
19316 expr = instantiate_non_dependent_expr (expr, complain);
19317 expr = cxx_constant_value (expr, complain);
19318 return expr;
19321 #include "gt-cp-decl.h"