Daily bump.
[official-gcc.git] / gcc / cp / decl.cc
blobb10a72a87bf0a1cabab52c1e4b657bc8a379b91e
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 gcc_rich_location bad_xobj_parm
13395 (DECL_SOURCE_LOCATION (TREE_VALUE (parm)));
13396 error_at (&bad_xobj_parm,
13397 "Only the first parameter of a member function "
13398 "can be declared as an explicit object parameter");
13400 if (bad_xobj_parm_encountered && xobj_parm)
13401 inform (DECL_SOURCE_LOCATION (xobj_parm),
13402 "Valid explicit object parameter declared here");
13405 if (reqs)
13406 error_at (location_of (reqs), "requires-clause on return type");
13407 reqs = declarator->u.function.requires_clause;
13409 /* Say it's a definition only for the CALL_EXPR
13410 closest to the identifier. */
13411 funcdecl_p = inner_declarator && inner_declarator->kind == cdk_id;
13413 /* Handle a late-specified return type. */
13414 tree late_return_type = declarator->u.function.late_return_type;
13415 if (tree auto_node = type_uses_auto (type))
13417 if (!late_return_type)
13419 if (!funcdecl_p)
13420 /* auto (*fp)() = f; is OK. */;
13421 else if (current_class_type
13422 && LAMBDA_TYPE_P (current_class_type))
13423 /* OK for C++11 lambdas. */;
13424 else if (cxx_dialect < cxx14)
13426 error_at (typespec_loc, "%qs function uses "
13427 "%<auto%> type specifier without "
13428 "trailing return type", name);
13429 inform (typespec_loc,
13430 "deduced return type only available "
13431 "with %<-std=c++14%> or %<-std=gnu++14%>");
13433 else if (virtualp)
13435 error_at (typespec_loc, "virtual function "
13436 "cannot have deduced return type");
13437 virtualp = false;
13440 else if (!is_auto (type) && sfk != sfk_conversion)
13442 error_at (typespec_loc, "%qs function with trailing "
13443 "return type has %qT as its type rather "
13444 "than plain %<auto%>", name, type);
13445 return error_mark_node;
13447 else if (is_auto (type) && AUTO_IS_DECLTYPE (type))
13449 if (funcdecl_p)
13450 error_at (typespec_loc,
13451 "%qs function with trailing return type "
13452 "has %<decltype(auto)%> as its type "
13453 "rather than plain %<auto%>", name);
13454 else
13455 error_at (typespec_loc,
13456 "invalid use of %<decltype(auto)%>");
13457 return error_mark_node;
13459 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node);
13460 if (!tmpl)
13461 if (tree late_auto = type_uses_auto (late_return_type))
13462 tmpl = CLASS_PLACEHOLDER_TEMPLATE (late_auto);
13463 if (tmpl)
13465 if (!funcdecl_p || !dguide_name_p (unqualified_id))
13467 auto_diagnostic_group g;
13468 error_at (typespec_loc, "deduced class "
13469 "type %qD in function return type",
13470 DECL_NAME (tmpl));
13471 inform (DECL_SOURCE_LOCATION (tmpl),
13472 "%qD declared here", tmpl);
13473 return error_mark_node;
13475 else if (!late_return_type)
13477 error_at (declarator->id_loc, "deduction guide "
13478 "for %qT must have trailing return "
13479 "type", TREE_TYPE (tmpl));
13480 inform (DECL_SOURCE_LOCATION (tmpl),
13481 "%qD declared here", tmpl);
13482 return error_mark_node;
13484 else if (CLASS_TYPE_P (late_return_type)
13485 && CLASSTYPE_TEMPLATE_INFO (late_return_type)
13486 && (CLASSTYPE_TI_TEMPLATE (late_return_type)
13487 == tmpl))
13488 /* OK */;
13489 else
13490 error ("trailing return type %qT of deduction guide "
13491 "is not a specialization of %qT",
13492 late_return_type, TREE_TYPE (tmpl));
13495 else if (late_return_type
13496 && sfk != sfk_conversion)
13498 if (late_return_type == error_mark_node)
13499 return error_mark_node;
13500 if (cxx_dialect < cxx11)
13501 /* Not using maybe_warn_cpp0x because this should
13502 always be an error. */
13503 error_at (typespec_loc,
13504 "trailing return type only available "
13505 "with %<-std=c++11%> or %<-std=gnu++11%>");
13506 else
13507 error_at (typespec_loc, "%qs function with trailing "
13508 "return type not declared with %<auto%> "
13509 "type specifier", name);
13510 return error_mark_node;
13512 if (late_return_type && sfk == sfk_conversion)
13514 error ("a conversion function cannot have a trailing return type");
13515 return error_mark_node;
13517 type = splice_late_return_type (type, late_return_type);
13518 if (type == error_mark_node)
13519 return error_mark_node;
13521 if (late_return_type)
13523 late_return_type_p = true;
13524 type_quals = cp_type_quals (type);
13527 if (type_quals != TYPE_UNQUALIFIED)
13529 /* It's wrong, for instance, to issue a -Wignored-qualifiers
13530 warning for
13531 static_assert(!is_same_v<void(*)(), const void(*)()>);
13532 because there the qualifier matters. */
13533 if (funcdecl_p && (SCALAR_TYPE_P (type) || VOID_TYPE_P (type)))
13534 warning_at (typespec_loc, OPT_Wignored_qualifiers, "type "
13535 "qualifiers ignored on function return type");
13536 /* [dcl.fct] "A volatile-qualified return type is
13537 deprecated." */
13538 if (type_quals & TYPE_QUAL_VOLATILE)
13539 warning_at (typespec_loc, OPT_Wvolatile,
13540 "%<volatile%>-qualified return type is "
13541 "deprecated");
13543 /* We now know that the TYPE_QUALS don't apply to the
13544 decl, but to its return type. */
13545 type_quals = TYPE_UNQUALIFIED;
13548 /* Error about some types functions can't return. */
13550 if (TREE_CODE (type) == FUNCTION_TYPE)
13552 error_at (typespec_loc, "%qs declared as function returning "
13553 "a function", name);
13554 return error_mark_node;
13556 if (TREE_CODE (type) == ARRAY_TYPE)
13558 error_at (typespec_loc, "%qs declared as function returning "
13559 "an array", name);
13560 return error_mark_node;
13562 if (constinit_p && funcdecl_p)
13564 error_at (declspecs->locations[ds_constinit],
13565 "%<constinit%> on function return type is not "
13566 "allowed");
13567 return error_mark_node;
13570 if (check_decltype_auto (typespec_loc, type))
13571 return error_mark_node;
13573 if (ctype == NULL_TREE
13574 && decl_context == FIELD
13575 && funcdecl_p
13576 && friendp == 0)
13577 ctype = current_class_type;
13579 if (ctype && (sfk == sfk_constructor
13580 || sfk == sfk_destructor))
13582 /* We are within a class's scope. If our declarator name
13583 is the same as the class name, and we are defining
13584 a function, then it is a constructor/destructor, and
13585 therefore returns a void type. */
13587 /* ISO C++ 12.4/2. A destructor may not be declared
13588 const or volatile. A destructor may not be static.
13589 A destructor may not be declared with ref-qualifier.
13591 ISO C++ 12.1. A constructor may not be declared
13592 const or volatile. A constructor may not be
13593 virtual. A constructor may not be static.
13594 A constructor may not be declared with ref-qualifier. */
13595 if (staticp == 2)
13596 error_at (declspecs->locations[ds_storage_class],
13597 (flags == DTOR_FLAG)
13598 ? G_("destructor cannot be static member "
13599 "function")
13600 : G_("constructor cannot be static member "
13601 "function"));
13602 if (memfn_quals)
13604 error ((flags == DTOR_FLAG)
13605 ? G_("destructors may not be cv-qualified")
13606 : G_("constructors may not be cv-qualified"));
13607 memfn_quals = TYPE_UNQUALIFIED;
13610 if (rqual)
13612 maybe_warn_cpp0x (CPP0X_REF_QUALIFIER);
13613 error ((flags == DTOR_FLAG)
13614 ? G_("destructors may not be ref-qualified")
13615 : G_("constructors may not be ref-qualified"));
13616 rqual = REF_QUAL_NONE;
13619 if (decl_context == FIELD
13620 && !member_function_or_else (ctype,
13621 current_class_type,
13622 flags))
13623 return error_mark_node;
13625 if (flags != DTOR_FLAG)
13627 /* It's a constructor. */
13628 if (explicitp == 1)
13629 explicitp = 2;
13630 if (virtualp)
13632 permerror (declspecs->locations[ds_virtual],
13633 "constructors cannot be declared %<virtual%>");
13634 virtualp = 0;
13636 if (decl_context == FIELD
13637 && sfk != sfk_constructor)
13638 return error_mark_node;
13640 if (decl_context == FIELD)
13641 staticp = 0;
13643 else if (friendp)
13645 if (virtualp)
13647 /* Cannot be both friend and virtual. */
13648 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
13649 richloc.add_range (declspecs->locations[ds_friend]);
13650 error_at (&richloc, "virtual functions cannot be friends");
13651 friendp = 0;
13653 if (decl_context == NORMAL)
13654 error_at (declarator->id_loc,
13655 "friend declaration not in class definition");
13656 if (current_function_decl && funcdef_flag)
13658 error_at (declarator->id_loc,
13659 "cannot define friend function %qs in a local "
13660 "class definition", name);
13661 friendp = 0;
13663 /* [class.friend]/6: A function can be defined in a friend
13664 declaration if the function name is unqualified. */
13665 if (funcdef_flag && in_namespace)
13667 if (in_namespace == global_namespace)
13668 error_at (declarator->id_loc,
13669 "friend function definition %qs cannot have "
13670 "a name qualified with %<::%>", name);
13671 else
13672 error_at (declarator->id_loc,
13673 "friend function definition %qs cannot have "
13674 "a name qualified with %<%D::%>", name,
13675 in_namespace);
13678 else if (ctype && sfk == sfk_conversion)
13680 if (explicitp == 1)
13682 maybe_warn_cpp0x (CPP0X_EXPLICIT_CONVERSION);
13683 explicitp = 2;
13686 else if (sfk == sfk_deduction_guide)
13688 if (explicitp == 1)
13689 explicitp = 2;
13692 if (xobj_parm)
13694 if (!ctype
13695 && decl_context == NORMAL
13696 && (in_namespace
13697 || !declarator->declarator->u.id.qualifying_scope))
13698 error_at (DECL_SOURCE_LOCATION (xobj_parm),
13699 "a non-member function cannot have "
13700 "an explicit object parameter");
13701 else
13703 if (virtualp)
13705 auto_diagnostic_group d;
13706 error_at (declspecs->locations[ds_virtual],
13707 "an explicit object member function cannot "
13708 "be %<virtual%>");
13709 inform (DECL_SOURCE_LOCATION (xobj_parm),
13710 "explicit object parameter declared here");
13711 virtualp = false;
13713 if (staticp >= 2)
13715 auto_diagnostic_group d;
13716 error_at (declspecs->locations[ds_storage_class],
13717 "an explicit object member function cannot "
13718 "be %<static%>");
13719 inform (DECL_SOURCE_LOCATION (xobj_parm),
13720 "explicit object parameter declared here");
13724 tree pushed_scope = NULL_TREE;
13725 if (funcdecl_p
13726 && decl_context != FIELD
13727 && inner_declarator->u.id.qualifying_scope
13728 && CLASS_TYPE_P (inner_declarator->u.id.qualifying_scope))
13729 pushed_scope
13730 = push_scope (inner_declarator->u.id.qualifying_scope);
13732 arg_types = grokparms (declarator->u.function.parameters, &parms);
13734 if (pushed_scope)
13735 pop_scope (pushed_scope);
13737 if (inner_declarator
13738 && inner_declarator->kind == cdk_id
13739 && inner_declarator->u.id.sfk == sfk_destructor
13740 && arg_types != void_list_node)
13742 error_at (declarator->id_loc,
13743 "destructors may not have parameters");
13744 arg_types = void_list_node;
13745 parms = NULL_TREE;
13748 type = build_function_type (type, arg_types);
13750 tree attrs = declarator->std_attributes;
13751 if (tx_qual)
13753 tree att = build_tree_list (tx_qual, NULL_TREE);
13754 /* transaction_safe applies to the type, but
13755 transaction_safe_dynamic applies to the function. */
13756 if (is_attribute_p ("transaction_safe", tx_qual))
13757 attrs = attr_chainon (attrs, att);
13758 else
13759 returned_attrs = attr_chainon (returned_attrs, att);
13762 /* Actually apply the contract attributes to the declaration. */
13763 for (tree *p = &attrs; *p;)
13765 tree l = *p;
13766 if (cxx_contract_attribute_p (l))
13768 *p = TREE_CHAIN (l);
13769 /* Intentionally reverse order of contracts so they're
13770 reversed back into their lexical order. */
13771 TREE_CHAIN (l) = NULL_TREE;
13772 returned_attrs = chainon (l, returned_attrs);
13774 else
13775 p = &TREE_CHAIN (l);
13778 if (attrs)
13779 /* [dcl.fct]/2:
13781 The optional attribute-specifier-seq appertains to
13782 the function type. */
13783 cplus_decl_attributes (&type, attrs, 0);
13785 if (raises)
13786 type = build_exception_variant (type, raises);
13788 break;
13790 case cdk_pointer:
13791 case cdk_reference:
13792 case cdk_ptrmem:
13793 /* Filter out pointers-to-references and references-to-references.
13794 We can get these if a TYPE_DECL is used. */
13796 if (TYPE_REF_P (type))
13798 if (declarator->kind != cdk_reference)
13800 error ("cannot declare pointer to %q#T", type);
13801 type = TREE_TYPE (type);
13804 /* In C++0x, we allow reference to reference declarations
13805 that occur indirectly through typedefs [7.1.3/8 dcl.typedef]
13806 and template type arguments [14.3.1/4 temp.arg.type]. The
13807 check for direct reference to reference declarations, which
13808 are still forbidden, occurs below. Reasoning behind the change
13809 can be found in DR106, DR540, and the rvalue reference
13810 proposals. */
13811 else if (cxx_dialect == cxx98)
13813 error ("cannot declare reference to %q#T", type);
13814 type = TREE_TYPE (type);
13817 else if (VOID_TYPE_P (type))
13819 if (declarator->kind == cdk_reference)
13820 error ("cannot declare reference to %q#T", type);
13821 else if (declarator->kind == cdk_ptrmem)
13822 error ("cannot declare pointer to %q#T member", type);
13825 /* We now know that the TYPE_QUALS don't apply to the decl,
13826 but to the target of the pointer. */
13827 type_quals = TYPE_UNQUALIFIED;
13829 /* This code used to handle METHOD_TYPE, but I don't think it's
13830 possible to get it here anymore. */
13831 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
13832 if (declarator->kind == cdk_ptrmem
13833 && TREE_CODE (type) == FUNCTION_TYPE)
13835 memfn_quals |= type_memfn_quals (type);
13836 type = build_memfn_type (type,
13837 declarator->u.pointer.class_type,
13838 memfn_quals,
13839 rqual);
13840 if (type == error_mark_node)
13841 return error_mark_node;
13843 rqual = REF_QUAL_NONE;
13844 memfn_quals = TYPE_UNQUALIFIED;
13847 if (TREE_CODE (type) == FUNCTION_TYPE
13848 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
13849 || type_memfn_rqual (type) != REF_QUAL_NONE))
13850 error (declarator->kind == cdk_reference
13851 ? G_("cannot declare reference to qualified function type %qT")
13852 : G_("cannot declare pointer to qualified function type %qT"),
13853 type);
13855 /* When the pointed-to type involves components of variable size,
13856 care must be taken to ensure that the size evaluation code is
13857 emitted early enough to dominate all the possible later uses
13858 and late enough for the variables on which it depends to have
13859 been assigned.
13861 This is expected to happen automatically when the pointed-to
13862 type has a name/declaration of it's own, but special attention
13863 is required if the type is anonymous.
13865 We handle the NORMAL and FIELD contexts here by inserting a
13866 dummy statement that just evaluates the size at a safe point
13867 and ensures it is not deferred until e.g. within a deeper
13868 conditional context (c++/43555).
13870 We expect nothing to be needed here for PARM or TYPENAME.
13871 Evaluating the size at this point for TYPENAME would
13872 actually be incorrect, as we might be in the middle of an
13873 expression with side effects on the pointed-to type size
13874 "arguments" prior to the pointer declaration point and the
13875 size evaluation could end up prior to the side effects. */
13877 if (!TYPE_NAME (type)
13878 && (decl_context == NORMAL || decl_context == FIELD)
13879 && at_function_scope_p ()
13880 && variably_modified_type_p (type, NULL_TREE))
13882 TYPE_NAME (type) = build_decl (UNKNOWN_LOCATION, TYPE_DECL,
13883 NULL_TREE, type);
13884 add_decl_expr (TYPE_NAME (type));
13887 if (declarator->kind == cdk_reference)
13889 /* In C++0x, the type we are creating a reference to might be
13890 a typedef which is itself a reference type. In that case,
13891 we follow the reference collapsing rules in
13892 [7.1.3/8 dcl.typedef] to create the final reference type:
13894 "If a typedef TD names a type that is a reference to a type
13895 T, an attempt to create the type 'lvalue reference to cv TD'
13896 creates the type 'lvalue reference to T,' while an attempt
13897 to create the type "rvalue reference to cv TD' creates the
13898 type TD."
13900 if (VOID_TYPE_P (type))
13901 /* We already gave an error. */;
13902 else if (TYPE_REF_P (type))
13904 if (declarator->u.reference.rvalue_ref)
13905 /* Leave type alone. */;
13906 else
13907 type = cp_build_reference_type (TREE_TYPE (type), false);
13909 else
13910 type = cp_build_reference_type
13911 (type, declarator->u.reference.rvalue_ref);
13913 /* In C++0x, we need this check for direct reference to
13914 reference declarations, which are forbidden by
13915 [8.3.2/5 dcl.ref]. Reference to reference declarations
13916 are only allowed indirectly through typedefs and template
13917 type arguments. Example:
13919 void foo(int & &); // invalid ref-to-ref decl
13921 typedef int & int_ref;
13922 void foo(int_ref &); // valid ref-to-ref decl
13924 if (inner_declarator && inner_declarator->kind == cdk_reference)
13925 error ("cannot declare reference to %q#T, which is not "
13926 "a typedef or a template type argument", type);
13928 else if (TREE_CODE (type) == METHOD_TYPE)
13929 type = build_ptrmemfunc_type (build_pointer_type (type));
13930 else if (declarator->kind == cdk_ptrmem)
13932 gcc_assert (TREE_CODE (declarator->u.pointer.class_type)
13933 != NAMESPACE_DECL);
13934 if (declarator->u.pointer.class_type == error_mark_node)
13935 /* We will already have complained. */
13936 type = error_mark_node;
13937 else
13938 type = build_ptrmem_type (declarator->u.pointer.class_type,
13939 type);
13941 else
13942 type = build_pointer_type (type);
13944 /* Process a list of type modifier keywords (such as
13945 const or volatile) that were given inside the `*' or `&'. */
13947 if (declarator->u.pointer.qualifiers)
13949 type
13950 = cp_build_qualified_type (type,
13951 declarator->u.pointer.qualifiers);
13952 type_quals = cp_type_quals (type);
13955 /* Apply C++11 attributes to the pointer, and not to the
13956 type pointed to. This is unlike what is done for GNU
13957 attributes above. It is to comply with [dcl.ptr]/1:
13959 [the optional attribute-specifier-seq (7.6.1) appertains
13960 to the pointer and not to the object pointed to]. */
13961 if (declarator->std_attributes)
13962 decl_attributes (&type, declarator->std_attributes,
13965 ctype = NULL_TREE;
13966 break;
13968 case cdk_error:
13969 break;
13971 default:
13972 gcc_unreachable ();
13976 id_loc = declarator ? declarator->id_loc : input_location;
13978 if (innermost_code != cdk_function
13979 /* Don't check this if it can be the artifical decltype(auto)
13980 we created when building a constraint in a compound-requirement:
13981 that the type-constraint is plain is going to be checked in
13982 cp_parser_compound_requirement. */
13983 && decl_context != TYPENAME
13984 && check_decltype_auto (id_loc, type))
13985 return error_mark_node;
13987 /* A `constexpr' specifier used in an object declaration declares
13988 the object as `const'. */
13989 if (constexpr_p && innermost_code != cdk_function)
13991 /* DR1688 says that a `constexpr' specifier in combination with
13992 `volatile' is valid. */
13994 if (!TYPE_REF_P (type))
13996 type_quals |= TYPE_QUAL_CONST;
13997 type = cp_build_qualified_type (type, type_quals);
14001 if (unqualified_id && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR
14002 && !FUNC_OR_METHOD_TYPE_P (type)
14003 && !variable_template_p (TREE_OPERAND (unqualified_id, 0)))
14005 error ("template-id %qD used as a declarator",
14006 unqualified_id);
14007 unqualified_id = dname;
14010 /* If TYPE is a FUNCTION_TYPE, but the function name was explicitly
14011 qualified with a class-name, turn it into a METHOD_TYPE, unless
14012 we know that the function is static. We take advantage of this
14013 opportunity to do other processing that pertains to entities
14014 explicitly declared to be class members. Note that if DECLARATOR
14015 is non-NULL, we know it is a cdk_id declarator; otherwise, we
14016 would not have exited the loop above. */
14017 if (declarator
14018 && declarator->kind == cdk_id
14019 && declarator->u.id.qualifying_scope
14020 && MAYBE_CLASS_TYPE_P (declarator->u.id.qualifying_scope))
14022 ctype = declarator->u.id.qualifying_scope;
14023 ctype = TYPE_MAIN_VARIANT (ctype);
14024 template_count = num_template_headers_for_class (ctype);
14026 if (ctype == current_class_type)
14028 if (friendp)
14030 permerror (declspecs->locations[ds_friend],
14031 "member functions are implicitly "
14032 "friends of their class");
14033 friendp = 0;
14035 else
14036 permerror (id_loc, "extra qualification %<%T::%> on member %qs",
14037 ctype, name);
14039 else if (/* If the qualifying type is already complete, then we
14040 can skip the following checks. */
14041 !COMPLETE_TYPE_P (ctype)
14042 && (/* If the function is being defined, then
14043 qualifying type must certainly be complete. */
14044 funcdef_flag
14045 /* A friend declaration of "T::f" is OK, even if
14046 "T" is a template parameter. But, if this
14047 function is not a friend, the qualifying type
14048 must be a class. */
14049 || (!friendp && !CLASS_TYPE_P (ctype))
14050 /* For a declaration, the type need not be
14051 complete, if either it is dependent (since there
14052 is no meaningful definition of complete in that
14053 case) or the qualifying class is currently being
14054 defined. */
14055 || !(dependent_type_p (ctype)
14056 || currently_open_class (ctype)))
14057 /* Check that the qualifying type is complete. */
14058 && !complete_type_or_else (ctype, NULL_TREE))
14059 return error_mark_node;
14060 else if (TREE_CODE (type) == FUNCTION_TYPE)
14062 if (current_class_type
14063 && (!friendp || funcdef_flag || initialized))
14065 error_at (id_loc, funcdef_flag || initialized
14066 ? G_("cannot define member function %<%T::%s%> "
14067 "within %qT")
14068 : G_("cannot declare member function %<%T::%s%> "
14069 "within %qT"),
14070 ctype, name, current_class_type);
14071 return error_mark_node;
14074 else if (typedef_p && current_class_type)
14076 error_at (id_loc, "cannot declare member %<%T::%s%> within %qT",
14077 ctype, name, current_class_type);
14078 return error_mark_node;
14082 if (ctype == NULL_TREE && decl_context == FIELD && friendp == 0)
14083 ctype = current_class_type;
14085 /* Now TYPE has the actual type. */
14087 if (returned_attrs)
14089 if (attrlist)
14090 *attrlist = attr_chainon (returned_attrs, *attrlist);
14091 else
14092 attrlist = &returned_attrs;
14095 if (declarator
14096 && declarator->kind == cdk_id
14097 && declarator->std_attributes
14098 && attrlist != NULL)
14100 /* [dcl.meaning]/1: The optional attribute-specifier-seq following
14101 a declarator-id appertains to the entity that is declared. */
14102 if (declarator->std_attributes != error_mark_node)
14103 *attrlist = attr_chainon (declarator->std_attributes, *attrlist);
14104 else
14105 /* We should have already diagnosed the issue (c++/78344). */
14106 gcc_assert (seen_error ());
14109 /* Handle parameter packs. */
14110 if (parameter_pack_p)
14112 if (decl_context == PARM)
14113 /* Turn the type into a pack expansion.*/
14114 type = make_pack_expansion (type);
14115 else
14116 error ("non-parameter %qs cannot be a parameter pack", name);
14119 if ((decl_context == FIELD || decl_context == PARM)
14120 && !processing_template_decl
14121 && variably_modified_type_p (type, NULL_TREE))
14123 if (decl_context == FIELD)
14124 error_at (id_loc,
14125 "data member may not have variably modified type %qT", type);
14126 else
14127 error_at (id_loc,
14128 "parameter may not have variably modified type %qT", type);
14129 type = error_mark_node;
14132 if (explicitp == 1 || (explicitp && friendp))
14134 /* [dcl.fct.spec] (C++11) The explicit specifier shall be used only
14135 in the declaration of a constructor or conversion function within
14136 a class definition. */
14137 if (!current_class_type)
14138 error_at (declspecs->locations[ds_explicit],
14139 "%<explicit%> outside class declaration");
14140 else if (friendp)
14141 error_at (declspecs->locations[ds_explicit],
14142 "%<explicit%> in friend declaration");
14143 else
14144 error_at (declspecs->locations[ds_explicit],
14145 "only declarations of constructors and conversion operators "
14146 "can be %<explicit%>");
14147 explicitp = 0;
14150 if (storage_class == sc_mutable)
14152 location_t sloc = declspecs->locations[ds_storage_class];
14153 if (decl_context != FIELD || friendp)
14155 error_at (sloc, "non-member %qs cannot be declared %<mutable%>",
14156 name);
14157 storage_class = sc_none;
14159 else if (decl_context == TYPENAME || typedef_p)
14161 error_at (sloc,
14162 "non-object member %qs cannot be declared %<mutable%>",
14163 name);
14164 storage_class = sc_none;
14166 else if (FUNC_OR_METHOD_TYPE_P (type))
14168 error_at (sloc, "function %qs cannot be declared %<mutable%>",
14169 name);
14170 storage_class = sc_none;
14172 else if (staticp)
14174 error_at (sloc, "%<static%> %qs cannot be declared %<mutable%>",
14175 name);
14176 storage_class = sc_none;
14178 else if (type_quals & TYPE_QUAL_CONST)
14180 error_at (sloc, "%<const%> %qs cannot be declared %<mutable%>",
14181 name);
14182 storage_class = sc_none;
14184 else if (TYPE_REF_P (type))
14186 permerror (sloc, "reference %qs cannot be declared %<mutable%>",
14187 name);
14188 storage_class = sc_none;
14192 /* If this is declaring a typedef name, return a TYPE_DECL. */
14193 if (typedef_p && decl_context != TYPENAME)
14195 bool alias_p = decl_spec_seq_has_spec_p (declspecs, ds_alias);
14196 tree decl;
14198 if (funcdef_flag)
14200 if (decl_context == NORMAL)
14201 error_at (id_loc,
14202 "typedef may not be a function definition");
14203 else
14204 error_at (id_loc,
14205 "typedef may not be a member function definition");
14206 return error_mark_node;
14209 /* This declaration:
14211 typedef void f(int) const;
14213 declares a function type which is not a member of any
14214 particular class, but which is cv-qualified; for
14215 example "f S::*" declares a pointer to a const-qualified
14216 member function of S. We record the cv-qualification in the
14217 function type. */
14218 if ((rqual || memfn_quals) && TREE_CODE (type) == FUNCTION_TYPE)
14220 type = apply_memfn_quals (type, memfn_quals, rqual);
14222 /* We have now dealt with these qualifiers. */
14223 memfn_quals = TYPE_UNQUALIFIED;
14224 rqual = REF_QUAL_NONE;
14227 if (type_uses_auto (type))
14229 if (alias_p)
14230 error_at (declspecs->locations[ds_type_spec],
14231 "%<auto%> not allowed in alias declaration");
14232 else
14233 error_at (declspecs->locations[ds_type_spec],
14234 "typedef declared %<auto%>");
14235 type = error_mark_node;
14238 if (reqs)
14239 error_at (location_of (reqs), "requires-clause on typedef");
14241 if (id_declarator && declarator->u.id.qualifying_scope)
14243 error_at (id_loc, "typedef name may not be a nested-name-specifier");
14244 type = error_mark_node;
14247 if (decl_context == FIELD)
14248 decl = build_lang_decl_loc (id_loc, TYPE_DECL, unqualified_id, type);
14249 else
14250 decl = build_decl (id_loc, TYPE_DECL, unqualified_id, type);
14252 if (decl_context != FIELD)
14254 if (!current_function_decl)
14255 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
14256 else if (DECL_MAYBE_IN_CHARGE_CDTOR_P (current_function_decl))
14257 /* The TYPE_DECL is "abstract" because there will be
14258 clones of this constructor/destructor, and there will
14259 be copies of this TYPE_DECL generated in those
14260 clones. The decloning optimization (for space) may
14261 revert this subsequently if it determines that
14262 the clones should share a common implementation. */
14263 DECL_ABSTRACT_P (decl) = true;
14265 set_originating_module (decl);
14267 else if (current_class_type
14268 && constructor_name_p (unqualified_id, current_class_type))
14269 permerror (id_loc, "ISO C++ forbids nested type %qD with same name "
14270 "as enclosing class",
14271 unqualified_id);
14273 /* If the user declares "typedef struct {...} foo" then the
14274 struct will have an anonymous name. Fill that name in now.
14275 Nothing can refer to it, so nothing needs know about the name
14276 change. */
14277 if (type != error_mark_node
14278 && unqualified_id
14279 && TYPE_NAME (type)
14280 && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL
14281 && TYPE_UNNAMED_P (type)
14282 && declspecs->type_definition_p
14283 && attributes_naming_typedef_ok (*attrlist)
14284 && cp_type_quals (type) == TYPE_UNQUALIFIED)
14285 name_unnamed_type (type, decl);
14287 if (signed_p
14288 || (typedef_decl && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl)))
14289 C_TYPEDEF_EXPLICITLY_SIGNED (decl) = 1;
14291 bad_specifiers (decl, BSP_TYPE, virtualp,
14292 memfn_quals != TYPE_UNQUALIFIED,
14293 inlinep, friendp, raises != NULL_TREE,
14294 declspecs->locations);
14296 if (alias_p)
14297 /* Acknowledge that this was written:
14298 `using analias = atype;'. */
14299 TYPE_DECL_ALIAS_P (decl) = 1;
14301 return decl;
14304 /* Detect the case of an array type of unspecified size
14305 which came, as such, direct from a typedef name.
14306 We must copy the type, so that the array's domain can be
14307 individually set by the object's initializer. */
14309 if (type && typedef_type
14310 && TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type)
14311 && TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (typedef_type))
14312 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
14314 /* Detect where we're using a typedef of function type to declare a
14315 function. PARMS will not be set, so we must create it now. */
14317 if (type == typedef_type && TREE_CODE (type) == FUNCTION_TYPE)
14319 tree decls = NULL_TREE;
14320 tree args;
14322 for (args = TYPE_ARG_TYPES (type);
14323 args && args != void_list_node;
14324 args = TREE_CHAIN (args))
14326 tree decl = cp_build_parm_decl (NULL_TREE, NULL_TREE,
14327 TREE_VALUE (args));
14329 DECL_CHAIN (decl) = decls;
14330 decls = decl;
14333 parms = nreverse (decls);
14335 if (decl_context != TYPENAME)
14337 /* The qualifiers on the function type become the qualifiers on
14338 the non-static member function. */
14339 memfn_quals |= type_memfn_quals (type);
14340 rqual = type_memfn_rqual (type);
14341 type_quals = TYPE_UNQUALIFIED;
14342 raises = TYPE_RAISES_EXCEPTIONS (type);
14346 /* If this is a type name (such as, in a cast or sizeof),
14347 compute the type and return it now. */
14349 if (decl_context == TYPENAME)
14351 /* Note that here we don't care about type_quals. */
14353 /* Special case: "friend class foo" looks like a TYPENAME context. */
14354 if (friendp)
14356 if (inlinep)
14358 error ("%<inline%> specified for friend class declaration");
14359 inlinep = 0;
14362 if (!current_aggr)
14364 /* Don't allow friend declaration without a class-key. */
14365 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
14366 permerror (input_location, "template parameters cannot be friends");
14367 else if (TREE_CODE (type) == TYPENAME_TYPE)
14368 permerror (input_location, "friend declaration requires class-key, "
14369 "i.e. %<friend class %T::%D%>",
14370 TYPE_CONTEXT (type), TYPENAME_TYPE_FULLNAME (type));
14371 else
14372 permerror (input_location, "friend declaration requires class-key, "
14373 "i.e. %<friend %#T%>",
14374 type);
14377 /* Only try to do this stuff if we didn't already give up. */
14378 if (type != integer_type_node)
14380 /* A friendly class? */
14381 if (current_class_type)
14382 make_friend_class (current_class_type, TYPE_MAIN_VARIANT (type),
14383 /*complain=*/true);
14384 else
14385 error ("trying to make class %qT a friend of global scope",
14386 type);
14388 type = void_type_node;
14391 else if (memfn_quals || rqual)
14393 if (ctype == NULL_TREE
14394 && TREE_CODE (type) == METHOD_TYPE)
14395 ctype = TYPE_METHOD_BASETYPE (type);
14397 if (ctype)
14398 type = build_memfn_type (type, ctype, memfn_quals, rqual);
14399 /* Core issue #547: need to allow this in template type args.
14400 Allow it in general in C++11 for alias-declarations. */
14401 else if ((template_type_arg || cxx_dialect >= cxx11)
14402 && TREE_CODE (type) == FUNCTION_TYPE)
14403 type = apply_memfn_quals (type, memfn_quals, rqual);
14404 else
14405 error ("invalid qualifiers on non-member function type");
14408 if (reqs)
14409 error_at (location_of (reqs), "requires-clause on type-id");
14411 return type;
14413 else if (unqualified_id == NULL_TREE && decl_context != PARM
14414 && decl_context != CATCHPARM
14415 && TREE_CODE (type) != UNION_TYPE
14416 && ! bitfield
14417 && innermost_code != cdk_decomp)
14419 error ("abstract declarator %qT used as declaration", type);
14420 return error_mark_node;
14423 if (!FUNC_OR_METHOD_TYPE_P (type))
14425 /* Only functions may be declared using an operator-function-id. */
14426 if (dname && IDENTIFIER_ANY_OP_P (dname))
14428 error_at (id_loc, "declaration of %qD as non-function", dname);
14429 return error_mark_node;
14432 if (reqs)
14433 error_at (location_of (reqs),
14434 "requires-clause on declaration of non-function type %qT",
14435 type);
14438 /* We don't check parameter types here because we can emit a better
14439 error message later. */
14440 if (decl_context != PARM)
14442 type = check_var_type (unqualified_id, type, id_loc);
14443 if (type == error_mark_node)
14444 return error_mark_node;
14447 /* Now create the decl, which may be a VAR_DECL, a PARM_DECL
14448 or a FUNCTION_DECL, depending on DECL_CONTEXT and TYPE. */
14450 if (decl_context == PARM || decl_context == CATCHPARM)
14452 if (ctype || in_namespace)
14453 error ("cannot use %<::%> in parameter declaration");
14455 tree auto_node = type_uses_auto (type);
14456 if (auto_node && !(cxx_dialect >= cxx17 && template_parm_flag))
14458 bool err_p = true;
14459 if (cxx_dialect >= cxx14)
14461 if (decl_context == PARM && AUTO_IS_DECLTYPE (auto_node))
14462 error_at (typespec_loc,
14463 "cannot declare a parameter with %<decltype(auto)%>");
14464 else if (tree c = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14466 auto_diagnostic_group g;
14467 gcc_rich_location richloc (typespec_loc);
14468 richloc.add_fixit_insert_after ("<>");
14469 error_at (&richloc,
14470 "missing template argument list after %qE; template "
14471 "placeholder not permitted in parameter", c);
14472 if (decl_context == PARM && cxx_dialect >= cxx20)
14473 inform (typespec_loc, "or use %<auto%> for an "
14474 "abbreviated function template");
14475 inform (DECL_SOURCE_LOCATION (c), "%qD declared here", c);
14477 else if (decl_context == CATCHPARM || template_parm_flag)
14478 error_at (typespec_loc,
14479 "%<auto%> parameter not permitted in this context");
14480 else
14481 /* Do not issue an error while tentatively parsing a function
14482 parameter: for T t(auto(a), 42);, when we just saw the 1st
14483 parameter, we don't know yet that this construct won't be
14484 a function declaration. Defer the checking to
14485 cp_parser_parameter_declaration_clause. */
14486 err_p = false;
14488 else
14489 error_at (typespec_loc, "parameter declared %<auto%>");
14490 if (err_p)
14491 type = error_mark_node;
14494 /* A parameter declared as an array of T is really a pointer to T.
14495 One declared as a function is really a pointer to a function.
14496 One declared as a member is really a pointer to member. */
14498 if (TREE_CODE (type) == ARRAY_TYPE)
14500 /* Transfer const-ness of array into that of type pointed to. */
14501 type = build_pointer_type (TREE_TYPE (type));
14502 type_quals = TYPE_UNQUALIFIED;
14503 array_parameter_p = true;
14505 else if (TREE_CODE (type) == FUNCTION_TYPE)
14506 type = build_pointer_type (type);
14509 if (ctype && TREE_CODE (type) == FUNCTION_TYPE && staticp < 2
14510 /* Don't convert xobj member functions to METHOD_TYPE. */
14511 && !is_xobj_member_function
14512 && !(unqualified_id
14513 && identifier_p (unqualified_id)
14514 && IDENTIFIER_NEWDEL_OP_P (unqualified_id)))
14516 cp_cv_quals real_quals = memfn_quals;
14517 if (cxx_dialect < cxx14 && constexpr_p
14518 && sfk != sfk_constructor && sfk != sfk_destructor)
14519 real_quals |= TYPE_QUAL_CONST;
14520 type = build_memfn_type (type, ctype, real_quals, rqual);
14524 tree decl = NULL_TREE;
14526 if (decl_context == PARM)
14528 decl = cp_build_parm_decl (NULL_TREE, unqualified_id, type);
14529 DECL_ARRAY_PARAMETER_P (decl) = array_parameter_p;
14531 bad_specifiers (decl, BSP_PARM, virtualp,
14532 memfn_quals != TYPE_UNQUALIFIED,
14533 inlinep, friendp, raises != NULL_TREE,
14534 declspecs->locations);
14536 else if (decl_context == FIELD)
14538 if (!staticp && !friendp && !FUNC_OR_METHOD_TYPE_P (type))
14539 if (tree auto_node = type_uses_auto (type))
14541 location_t tloc = declspecs->locations[ds_type_spec];
14542 if (CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14543 error_at (tloc, "invalid use of template-name %qE without an "
14544 "argument list",
14545 CLASS_PLACEHOLDER_TEMPLATE (auto_node));
14546 else
14547 error_at (tloc, "non-static data member declared with "
14548 "placeholder %qT", auto_node);
14549 type = error_mark_node;
14552 /* The C99 flexible array extension. */
14553 if (!staticp && TREE_CODE (type) == ARRAY_TYPE
14554 && TYPE_DOMAIN (type) == NULL_TREE)
14556 if (ctype
14557 && (TREE_CODE (ctype) == UNION_TYPE
14558 || TREE_CODE (ctype) == QUAL_UNION_TYPE))
14560 error_at (id_loc, "flexible array member in union");
14561 type = error_mark_node;
14563 else
14565 /* Array is a flexible member. */
14566 if (name)
14567 pedwarn (id_loc, OPT_Wpedantic,
14568 "ISO C++ forbids flexible array member %qs", name);
14569 else
14570 pedwarn (input_location, OPT_Wpedantic,
14571 "ISO C++ forbids flexible array members");
14573 /* Flexible array member has a null domain. */
14574 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
14578 if (type == error_mark_node)
14580 /* Happens when declaring arrays of sizes which
14581 are error_mark_node, for example. */
14582 decl = NULL_TREE;
14584 else if (in_namespace && !friendp)
14586 /* Something like struct S { int N::j; }; */
14587 error_at (id_loc, "invalid use of %<::%>");
14588 return error_mark_node;
14590 else if (FUNC_OR_METHOD_TYPE_P (type) && unqualified_id)
14592 int publicp = 0;
14593 tree function_context;
14595 if (friendp == 0)
14597 /* This should never happen in pure C++ (the check
14598 could be an assert). It could happen in
14599 Objective-C++ if someone writes invalid code that
14600 uses a function declaration for an instance
14601 variable or property (instance variables and
14602 properties are parsed as FIELD_DECLs, but they are
14603 part of an Objective-C class, not a C++ class).
14604 That code is invalid and is caught by this
14605 check. */
14606 if (!ctype)
14608 error ("declaration of function %qD in invalid context",
14609 unqualified_id);
14610 return error_mark_node;
14613 /* ``A union may [ ... ] not [ have ] virtual functions.''
14614 ARM 9.5 */
14615 if (virtualp && TREE_CODE (ctype) == UNION_TYPE)
14617 error_at (declspecs->locations[ds_virtual],
14618 "function %qD declared %<virtual%> inside a union",
14619 unqualified_id);
14620 return error_mark_node;
14623 if (virtualp
14624 && identifier_p (unqualified_id)
14625 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14627 error_at (declspecs->locations[ds_virtual],
14628 "%qD cannot be declared %<virtual%>, since it "
14629 "is always static", unqualified_id);
14630 virtualp = 0;
14634 /* Check that the name used for a destructor makes sense. */
14635 if (sfk == sfk_destructor)
14637 tree uqname = id_declarator->u.id.unqualified_name;
14639 if (!ctype)
14641 gcc_assert (friendp);
14642 error_at (id_loc, "expected qualified name in friend "
14643 "declaration for destructor %qD", uqname);
14644 return error_mark_node;
14647 if (!check_dtor_name (ctype, TREE_OPERAND (uqname, 0)))
14649 error_at (id_loc, "declaration of %qD as member of %qT",
14650 uqname, ctype);
14651 return error_mark_node;
14653 if (concept_p)
14655 error_at (declspecs->locations[ds_concept],
14656 "a destructor cannot be %qs", "concept");
14657 return error_mark_node;
14659 if (constexpr_p && cxx_dialect < cxx20)
14661 error_at (declspecs->locations[ds_constexpr],
14662 "%<constexpr%> destructors only available"
14663 " with %<-std=c++20%> or %<-std=gnu++20%>");
14664 return error_mark_node;
14666 if (consteval_p)
14668 error_at (declspecs->locations[ds_consteval],
14669 "a destructor cannot be %qs", "consteval");
14670 return error_mark_node;
14673 else if (sfk == sfk_constructor && friendp && !ctype)
14675 error ("expected qualified name in friend declaration "
14676 "for constructor %qD",
14677 id_declarator->u.id.unqualified_name);
14678 return error_mark_node;
14680 if (sfk == sfk_constructor)
14681 if (concept_p)
14683 error_at (declspecs->locations[ds_concept],
14684 "a constructor cannot be %<concept%>");
14685 return error_mark_node;
14687 if (concept_p)
14689 error_at (declspecs->locations[ds_concept],
14690 "a concept cannot be a member function");
14691 concept_p = false;
14693 else if (consteval_p
14694 && identifier_p (unqualified_id)
14695 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14697 error_at (declspecs->locations[ds_consteval],
14698 "%qD cannot be %qs", unqualified_id, "consteval");
14699 consteval_p = false;
14702 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14704 tree tmpl = TREE_OPERAND (unqualified_id, 0);
14705 if (variable_template_p (tmpl))
14707 error_at (id_loc, "specialization of variable template "
14708 "%qD declared as function", tmpl);
14709 inform (DECL_SOURCE_LOCATION (tmpl),
14710 "variable template declared here");
14711 return error_mark_node;
14715 /* Tell grokfndecl if it needs to set TREE_PUBLIC on the node. */
14716 function_context
14717 = (ctype != NULL_TREE
14718 ? decl_function_context (TYPE_MAIN_DECL (ctype)) : NULL_TREE);
14719 publicp = ((! friendp || ! staticp)
14720 && function_context == NULL_TREE);
14722 decl = grokfndecl (ctype, type,
14723 TREE_CODE (unqualified_id) != TEMPLATE_ID_EXPR
14724 ? unqualified_id : dname,
14725 parms,
14726 unqualified_id,
14727 declspecs,
14728 reqs,
14729 virtualp, flags, memfn_quals, rqual, raises,
14730 friendp ? -1 : 0, friendp, publicp,
14731 inlinep | (2 * constexpr_p) | (4 * concept_p)
14732 | (8 * consteval_p),
14733 initialized == SD_DELETED,
14734 is_xobj_member_function, sfk,
14735 funcdef_flag, late_return_type_p,
14736 template_count, in_namespace,
14737 attrlist, id_loc);
14738 decl = set_virt_specifiers (decl, virt_specifiers);
14739 if (decl == NULL_TREE)
14740 return error_mark_node;
14741 #if 0
14742 /* This clobbers the attrs stored in `decl' from `attrlist'. */
14743 /* The decl and setting of decl_attr is also turned off. */
14744 decl = build_decl_attribute_variant (decl, decl_attr);
14745 #endif
14747 /* [class.conv.ctor]
14749 A constructor declared without the function-specifier
14750 explicit that can be called with a single parameter
14751 specifies a conversion from the type of its first
14752 parameter to the type of its class. Such a constructor
14753 is called a converting constructor. */
14754 if (explicitp == 2)
14755 DECL_NONCONVERTING_P (decl) = 1;
14757 if (declspecs->explicit_specifier)
14758 store_explicit_specifier (decl, declspecs->explicit_specifier);
14760 else if (!staticp
14761 && ((current_class_type
14762 && same_type_p (type, current_class_type))
14763 || (!dependent_type_p (type)
14764 && !COMPLETE_TYPE_P (complete_type (type))
14765 && (!complete_or_array_type_p (type)
14766 || initialized == SD_UNINITIALIZED))))
14768 if (TREE_CODE (type) != ARRAY_TYPE
14769 || !COMPLETE_TYPE_P (TREE_TYPE (type)))
14771 if (unqualified_id)
14773 error_at (id_loc, "field %qD has incomplete type %qT",
14774 unqualified_id, type);
14775 cxx_incomplete_type_inform (strip_array_types (type));
14777 else
14778 error ("name %qT has incomplete type", type);
14780 type = error_mark_node;
14781 decl = NULL_TREE;
14784 else if (!verify_type_context (input_location,
14785 staticp
14786 ? TCTX_STATIC_STORAGE
14787 : TCTX_FIELD, type))
14789 type = error_mark_node;
14790 decl = NULL_TREE;
14792 else
14794 if (friendp)
14796 if (unqualified_id)
14797 error_at (id_loc,
14798 "%qE is neither function nor member function; "
14799 "cannot be declared friend", unqualified_id);
14800 else
14801 error ("unnamed field is neither function nor member "
14802 "function; cannot be declared friend");
14803 return error_mark_node;
14805 decl = NULL_TREE;
14808 if (friendp)
14810 /* Packages tend to use GNU attributes on friends, so we only
14811 warn for standard attributes. */
14812 if (attrlist
14813 && !funcdef_flag
14814 && cxx11_attribute_p (*attrlist)
14815 && !all_attributes_are_contracts_p (*attrlist))
14817 *attrlist = NULL_TREE;
14818 if (warning_at (id_loc, OPT_Wattributes, "attribute ignored"))
14819 inform (id_loc, "an attribute that appertains to a friend "
14820 "declaration that is not a definition is ignored");
14822 /* Friends are treated specially. */
14823 if (ctype == current_class_type)
14824 ; /* We already issued a permerror. */
14825 else if (decl && DECL_NAME (decl))
14827 set_originating_module (decl, true);
14829 if (initialized)
14830 /* Kludge: We need funcdef_flag to be true in do_friend for
14831 in-class defaulted functions, but that breaks grokfndecl.
14832 So set it here. */
14833 funcdef_flag = true;
14835 cplus_decl_attributes (&decl, *attrlist, 0);
14836 *attrlist = NULL_TREE;
14838 tree scope = ctype ? ctype : in_namespace;
14839 decl = do_friend (scope, unqualified_id, decl,
14840 flags, funcdef_flag);
14841 return decl;
14843 else
14844 return error_mark_node;
14847 /* Structure field. It may not be a function, except for C++. */
14849 if (decl == NULL_TREE)
14851 if (staticp)
14853 /* C++ allows static class members. All other work
14854 for this is done by grokfield. */
14855 decl = build_lang_decl_loc (id_loc, VAR_DECL,
14856 dname, type);
14857 if (unqualified_id
14858 && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14860 decl = check_explicit_specialization (unqualified_id, decl,
14861 template_count,
14862 concept_p * 8);
14863 if (decl == error_mark_node)
14864 return error_mark_node;
14866 set_linkage_for_static_data_member (decl);
14867 if (concept_p)
14868 error_at (declspecs->locations[ds_concept],
14869 "static data member %qE declared %qs",
14870 unqualified_id, "concept");
14871 else if (constexpr_p && !initialized)
14873 error_at (DECL_SOURCE_LOCATION (decl),
14874 "%<constexpr%> static data member %qD must "
14875 "have an initializer", decl);
14876 constexpr_p = false;
14878 if (consteval_p)
14879 error_at (declspecs->locations[ds_consteval],
14880 "static data member %qE declared %qs",
14881 unqualified_id, "consteval");
14883 if (inlinep)
14884 mark_inline_variable (decl, declspecs->locations[ds_inline]);
14886 if (!DECL_VAR_DECLARED_INLINE_P (decl)
14887 && !(cxx_dialect >= cxx17 && constexpr_p))
14888 /* Even if there is an in-class initialization, DECL
14889 is considered undefined until an out-of-class
14890 definition is provided, unless this is an inline
14891 variable. */
14892 DECL_EXTERNAL (decl) = 1;
14894 if (thread_p)
14896 CP_DECL_THREAD_LOCAL_P (decl) = true;
14897 if (!processing_template_decl)
14898 set_decl_tls_model (decl, decl_default_tls_model (decl));
14899 if (declspecs->gnu_thread_keyword_p)
14900 SET_DECL_GNU_TLS_P (decl);
14903 /* Set the constraints on the declaration. */
14904 bool memtmpl = (current_template_depth
14905 > template_class_depth (current_class_type));
14906 if (memtmpl)
14908 tree ci = current_template_constraints ();
14909 set_constraints (decl, ci);
14912 else
14914 if (concept_p)
14916 error_at (declspecs->locations[ds_concept],
14917 "non-static data member %qE declared %qs",
14918 unqualified_id, "concept");
14919 concept_p = false;
14920 constexpr_p = false;
14922 else if (constexpr_p)
14924 error_at (declspecs->locations[ds_constexpr],
14925 "non-static data member %qE declared %qs",
14926 unqualified_id, "constexpr");
14927 constexpr_p = false;
14929 if (constinit_p)
14931 error_at (declspecs->locations[ds_constinit],
14932 "non-static data member %qE declared %qs",
14933 unqualified_id, "constinit");
14934 constinit_p = false;
14936 if (consteval_p)
14938 error_at (declspecs->locations[ds_consteval],
14939 "non-static data member %qE declared %qs",
14940 unqualified_id, "consteval");
14941 consteval_p = false;
14943 decl = build_decl (id_loc, FIELD_DECL, unqualified_id, type);
14944 DECL_NONADDRESSABLE_P (decl) = bitfield;
14945 if (bitfield && !unqualified_id)
14946 DECL_PADDING_P (decl) = 1;
14948 if (storage_class == sc_mutable)
14950 DECL_MUTABLE_P (decl) = 1;
14951 storage_class = sc_none;
14954 if (initialized)
14956 /* An attempt is being made to initialize a non-static
14957 member. This is new in C++11. */
14958 maybe_warn_cpp0x (CPP0X_NSDMI, init_loc);
14960 /* If this has been parsed with static storage class, but
14961 errors forced staticp to be cleared, ensure NSDMI is
14962 not present. */
14963 if (declspecs->storage_class == sc_static)
14964 DECL_INITIAL (decl) = error_mark_node;
14968 bad_specifiers (decl, BSP_FIELD, virtualp,
14969 memfn_quals != TYPE_UNQUALIFIED,
14970 staticp ? false : inlinep, friendp,
14971 raises != NULL_TREE,
14972 declspecs->locations);
14975 else if (FUNC_OR_METHOD_TYPE_P (type))
14977 tree original_name;
14978 int publicp = 0;
14980 if (!unqualified_id)
14981 return error_mark_node;
14983 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14984 original_name = dname;
14985 else
14986 original_name = unqualified_id;
14987 // FIXME:gcc_assert (original_name == dname);
14989 if (storage_class == sc_auto)
14990 error_at (declspecs->locations[ds_storage_class],
14991 "storage class %<auto%> invalid for function %qs", name);
14992 else if (storage_class == sc_register)
14993 error_at (declspecs->locations[ds_storage_class],
14994 "storage class %<register%> invalid for function %qs",
14995 name);
14996 else if (thread_p)
14998 if (declspecs->gnu_thread_keyword_p)
14999 error_at (declspecs->locations[ds_thread],
15000 "storage class %<__thread%> invalid for function %qs",
15001 name);
15002 else
15003 error_at (declspecs->locations[ds_thread],
15004 "storage class %<thread_local%> invalid for "
15005 "function %qs", name);
15007 else if (constinit_p)
15008 error_at (declspecs->locations[ds_constinit],
15009 "%<constinit%> specifier invalid for function %qs", name);
15011 if (virt_specifiers)
15012 error ("virt-specifiers in %qs not allowed outside a class "
15013 "definition", name);
15014 /* Function declaration not at top level.
15015 Storage classes other than `extern' are not allowed
15016 and `extern' makes no difference. */
15017 if (! toplevel_bindings_p ()
15018 && (storage_class == sc_static
15019 || decl_spec_seq_has_spec_p (declspecs, ds_inline))
15020 && pedantic)
15022 if (storage_class == sc_static)
15023 pedwarn (declspecs->locations[ds_storage_class], OPT_Wpedantic,
15024 "%<static%> specifier invalid for function %qs "
15025 "declared out of global scope", name);
15026 else
15027 pedwarn (declspecs->locations[ds_inline], OPT_Wpedantic,
15028 "%<inline%> specifier invalid for function %qs "
15029 "declared out of global scope", name);
15032 if (ctype == NULL_TREE)
15034 if (virtualp)
15036 error ("virtual non-class function %qs", name);
15037 virtualp = 0;
15039 else if (sfk == sfk_constructor
15040 || sfk == sfk_destructor)
15042 error (funcdef_flag
15043 ? G_("%qs defined in a non-class scope")
15044 : G_("%qs declared in a non-class scope"), name);
15045 sfk = sfk_none;
15048 if (consteval_p
15049 && identifier_p (unqualified_id)
15050 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
15052 error_at (declspecs->locations[ds_consteval],
15053 "%qD cannot be %qs", unqualified_id, "consteval");
15054 consteval_p = false;
15057 /* Record whether the function is public. */
15058 publicp = (ctype != NULL_TREE
15059 || storage_class != sc_static);
15061 decl = grokfndecl (ctype, type, original_name, parms, unqualified_id,
15062 declspecs,
15063 reqs, virtualp, flags, memfn_quals, rqual, raises,
15064 1, friendp,
15065 publicp,
15066 inlinep | (2 * constexpr_p) | (4 * concept_p)
15067 | (8 * consteval_p),
15068 initialized == SD_DELETED,
15069 is_xobj_member_function, sfk,
15070 funcdef_flag,
15071 late_return_type_p,
15072 template_count, in_namespace, attrlist,
15073 id_loc);
15074 if (decl == NULL_TREE)
15075 return error_mark_node;
15077 if (explicitp == 2)
15078 DECL_NONCONVERTING_P (decl) = 1;
15079 if (staticp == 1)
15081 int invalid_static = 0;
15083 /* Don't allow a static member function in a class, and forbid
15084 declaring main to be static. */
15085 if (TREE_CODE (type) == METHOD_TYPE)
15087 permerror (input_location, "cannot declare member function %qD to have "
15088 "static linkage", decl);
15089 invalid_static = 1;
15091 else if (current_function_decl)
15093 /* 7.1.1: There can be no static function declarations within a
15094 block. */
15095 error_at (declspecs->locations[ds_storage_class],
15096 "cannot declare static function inside another function");
15097 invalid_static = 1;
15100 if (invalid_static)
15102 staticp = 0;
15103 storage_class = sc_none;
15106 if (declspecs->explicit_specifier)
15107 store_explicit_specifier (decl, declspecs->explicit_specifier);
15109 else
15111 /* It's a variable. */
15113 /* An uninitialized decl with `extern' is a reference. */
15114 decl = grokvardecl (type, dname, unqualified_id,
15115 declspecs,
15116 initialized,
15117 type_quals,
15118 inlinep,
15119 concept_p,
15120 template_count,
15121 ctype ? ctype : in_namespace,
15122 id_loc);
15123 if (decl == NULL_TREE)
15124 return error_mark_node;
15126 bad_specifiers (decl, BSP_VAR, virtualp,
15127 memfn_quals != TYPE_UNQUALIFIED,
15128 inlinep, friendp, raises != NULL_TREE,
15129 declspecs->locations);
15131 if (ctype)
15133 DECL_CONTEXT (decl) = ctype;
15134 if (staticp == 1)
15136 permerror (declspecs->locations[ds_storage_class],
15137 "%<static%> may not be used when defining "
15138 "(as opposed to declaring) a static data member");
15139 staticp = 0;
15140 storage_class = sc_none;
15142 if (storage_class == sc_register && TREE_STATIC (decl))
15144 error ("static member %qD declared %<register%>", decl);
15145 storage_class = sc_none;
15147 if (storage_class == sc_extern && pedantic)
15149 pedwarn (input_location, OPT_Wpedantic,
15150 "cannot explicitly declare member %q#D to have "
15151 "extern linkage", decl);
15152 storage_class = sc_none;
15155 else if (constexpr_p && DECL_EXTERNAL (decl))
15157 error_at (DECL_SOURCE_LOCATION (decl),
15158 "declaration of %<constexpr%> variable %qD "
15159 "is not a definition", decl);
15160 constexpr_p = false;
15162 if (consteval_p)
15164 error_at (DECL_SOURCE_LOCATION (decl),
15165 "a variable cannot be declared %<consteval%>");
15166 consteval_p = false;
15169 if (inlinep)
15170 mark_inline_variable (decl, declspecs->locations[ds_inline]);
15171 if (innermost_code == cdk_decomp)
15173 gcc_assert (declarator && declarator->kind == cdk_decomp);
15174 DECL_SOURCE_LOCATION (decl) = id_loc;
15175 DECL_ARTIFICIAL (decl) = 1;
15176 fit_decomposition_lang_decl (decl, NULL_TREE);
15180 if (VAR_P (decl) && !initialized)
15181 if (tree auto_node = type_uses_auto (type))
15182 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
15184 location_t loc = declspecs->locations[ds_type_spec];
15185 error_at (loc, "declaration of %q#D has no initializer", decl);
15186 TREE_TYPE (decl) = error_mark_node;
15189 if (storage_class == sc_extern && initialized && !funcdef_flag)
15191 if (toplevel_bindings_p ())
15193 /* It's common practice (and completely valid) to have a const
15194 be initialized and declared extern. */
15195 if (!(type_quals & TYPE_QUAL_CONST))
15196 warning_at (DECL_SOURCE_LOCATION (decl), 0,
15197 "%qs initialized and declared %<extern%>", name);
15199 else
15201 error_at (DECL_SOURCE_LOCATION (decl),
15202 "%qs has both %<extern%> and initializer", name);
15203 return error_mark_node;
15207 /* Record `register' declaration for warnings on &
15208 and in case doing stupid register allocation. */
15210 if (storage_class == sc_register)
15212 DECL_REGISTER (decl) = 1;
15213 /* Warn about register storage specifiers on PARM_DECLs. */
15214 if (TREE_CODE (decl) == PARM_DECL)
15216 if (cxx_dialect >= cxx17)
15217 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
15218 "ISO C++17 does not allow %<register%> storage "
15219 "class specifier");
15220 else
15221 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
15222 "%<register%> storage class specifier used");
15225 else if (storage_class == sc_extern)
15226 DECL_THIS_EXTERN (decl) = 1;
15227 else if (storage_class == sc_static)
15228 DECL_THIS_STATIC (decl) = 1;
15230 if (VAR_P (decl))
15232 /* Set constexpr flag on vars (functions got it in grokfndecl). */
15233 if (constexpr_p)
15234 DECL_DECLARED_CONSTEXPR_P (decl) = true;
15235 /* And the constinit flag (which only applies to variables). */
15236 else if (constinit_p)
15237 DECL_DECLARED_CONSTINIT_P (decl) = true;
15239 else if (TREE_CODE (decl) == FUNCTION_DECL)
15241 /* If we saw a return type, record its location. */
15242 location_t loc = declspecs->locations[ds_type_spec];
15243 if (loc == UNKNOWN_LOCATION)
15244 /* Build DECL_RESULT in start_preparsed_function. */;
15245 else if (!DECL_RESULT (decl))
15247 tree restype = TREE_TYPE (TREE_TYPE (decl));
15248 tree resdecl = build_decl (loc, RESULT_DECL, 0, restype);
15249 DECL_ARTIFICIAL (resdecl) = 1;
15250 DECL_IGNORED_P (resdecl) = 1;
15251 DECL_RESULT (decl) = resdecl;
15253 else if (funcdef_flag)
15254 DECL_SOURCE_LOCATION (DECL_RESULT (decl)) = loc;
15257 /* Record constancy and volatility on the DECL itself . There's
15258 no need to do this when processing a template; we'll do this
15259 for the instantiated declaration based on the type of DECL. */
15260 if (!processing_template_decl)
15261 cp_apply_type_quals_to_decl (type_quals, decl);
15263 return decl;
15267 /* Subroutine of start_function. Ensure that each of the parameter
15268 types (as listed in PARMS) is complete, as is required for a
15269 function definition. */
15271 static void
15272 require_complete_types_for_parms (tree parms)
15274 for (; parms; parms = DECL_CHAIN (parms))
15276 if (dependent_type_p (TREE_TYPE (parms)))
15277 continue;
15278 if (!VOID_TYPE_P (TREE_TYPE (parms))
15279 && complete_type_or_else (TREE_TYPE (parms), parms))
15281 relayout_decl (parms);
15282 DECL_ARG_TYPE (parms) = type_passed_as (TREE_TYPE (parms));
15284 abstract_virtuals_error (parms, TREE_TYPE (parms));
15285 maybe_warn_parm_abi (TREE_TYPE (parms),
15286 DECL_SOURCE_LOCATION (parms));
15288 else
15289 /* grokparms or complete_type_or_else will have already issued
15290 an error. */
15291 TREE_TYPE (parms) = error_mark_node;
15295 /* Returns nonzero if T is a local variable. */
15298 local_variable_p (const_tree t)
15300 if ((VAR_P (t)
15301 && (DECL_LOCAL_DECL_P (t)
15302 || !DECL_CONTEXT (t)
15303 || TREE_CODE (DECL_CONTEXT (t)) == FUNCTION_DECL))
15304 || (TREE_CODE (t) == PARM_DECL))
15305 return 1;
15307 return 0;
15310 /* Like local_variable_p, but suitable for use as a tree-walking
15311 function. */
15313 static tree
15314 local_variable_p_walkfn (tree *tp, int *walk_subtrees,
15315 void * /*data*/)
15317 if (unevaluated_p (TREE_CODE (*tp)))
15319 /* DR 2082 permits local variables in unevaluated contexts
15320 within a default argument. */
15321 *walk_subtrees = 0;
15322 return NULL_TREE;
15325 if (local_variable_p (*tp)
15326 && (!DECL_ARTIFICIAL (*tp) || DECL_NAME (*tp) == this_identifier))
15327 return *tp;
15328 else if (TYPE_P (*tp))
15329 *walk_subtrees = 0;
15331 return NULL_TREE;
15334 /* Check that ARG, which is a default-argument expression for a
15335 parameter DECL, is valid. Returns ARG, or ERROR_MARK_NODE, if
15336 something goes wrong. DECL may also be a _TYPE node, rather than a
15337 DECL, if there is no DECL available. */
15339 tree
15340 check_default_argument (tree decl, tree arg, tsubst_flags_t complain)
15342 tree var;
15343 tree decl_type;
15345 if (TREE_CODE (arg) == DEFERRED_PARSE)
15346 /* We get a DEFERRED_PARSE when looking at an in-class declaration
15347 with a default argument. Ignore the argument for now; we'll
15348 deal with it after the class is complete. */
15349 return arg;
15351 if (TYPE_P (decl))
15353 decl_type = decl;
15354 decl = NULL_TREE;
15356 else
15357 decl_type = TREE_TYPE (decl);
15359 if (arg == error_mark_node
15360 || decl == error_mark_node
15361 || TREE_TYPE (arg) == error_mark_node
15362 || decl_type == error_mark_node)
15363 /* Something already went wrong. There's no need to check
15364 further. */
15365 return error_mark_node;
15367 /* [dcl.fct.default]
15369 A default argument expression is implicitly converted to the
15370 parameter type. */
15371 ++cp_unevaluated_operand;
15372 /* Avoid digest_init clobbering the initializer. */
15373 tree carg = BRACE_ENCLOSED_INITIALIZER_P (arg) ? unshare_expr (arg): arg;
15374 perform_implicit_conversion_flags (decl_type, carg, complain,
15375 LOOKUP_IMPLICIT);
15376 --cp_unevaluated_operand;
15378 /* Avoid redundant -Wzero-as-null-pointer-constant warnings at
15379 the call sites. */
15380 if (TYPE_PTR_OR_PTRMEM_P (decl_type)
15381 && null_ptr_cst_p (arg)
15382 /* Don't lose side-effects as in PR90473. */
15383 && !TREE_SIDE_EFFECTS (arg))
15384 return nullptr_node;
15386 /* [dcl.fct.default]
15388 Local variables shall not be used in default argument
15389 expressions.
15391 The keyword `this' shall not be used in a default argument of a
15392 member function. */
15393 var = cp_walk_tree_without_duplicates (&arg, local_variable_p_walkfn, NULL);
15394 if (var)
15396 if (complain & tf_warning_or_error)
15398 if (DECL_NAME (var) == this_identifier)
15399 permerror (input_location, "default argument %qE uses %qD",
15400 arg, var);
15401 else
15402 error ("default argument %qE uses local variable %qD", arg, var);
15404 return error_mark_node;
15407 /* All is well. */
15408 return arg;
15411 /* Returns a deprecated type used within TYPE, or NULL_TREE if none. */
15413 static tree
15414 type_is_deprecated (tree type)
15416 enum tree_code code;
15417 if (TREE_DEPRECATED (type))
15418 return type;
15419 if (TYPE_NAME (type))
15421 if (TREE_DEPRECATED (TYPE_NAME (type)))
15422 return type;
15423 else
15425 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
15426 return NULL_TREE;
15430 /* Do warn about using typedefs to a deprecated class. */
15431 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
15432 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
15434 code = TREE_CODE (type);
15436 if (code == POINTER_TYPE || code == REFERENCE_TYPE
15437 || code == OFFSET_TYPE || code == FUNCTION_TYPE
15438 || code == METHOD_TYPE || code == ARRAY_TYPE)
15439 return type_is_deprecated (TREE_TYPE (type));
15441 if (TYPE_PTRMEMFUNC_P (type))
15442 return type_is_deprecated
15443 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
15445 return NULL_TREE;
15448 /* Returns an unavailable type used within TYPE, or NULL_TREE if none. */
15450 static tree
15451 type_is_unavailable (tree type)
15453 enum tree_code code;
15454 if (TREE_UNAVAILABLE (type))
15455 return type;
15456 if (TYPE_NAME (type))
15458 if (TREE_UNAVAILABLE (TYPE_NAME (type)))
15459 return type;
15460 else
15462 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
15463 return NULL_TREE;
15467 /* Do warn about using typedefs to a deprecated class. */
15468 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
15469 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
15471 code = TREE_CODE (type);
15473 if (code == POINTER_TYPE || code == REFERENCE_TYPE
15474 || code == OFFSET_TYPE || code == FUNCTION_TYPE
15475 || code == METHOD_TYPE || code == ARRAY_TYPE)
15476 return type_is_unavailable (TREE_TYPE (type));
15478 if (TYPE_PTRMEMFUNC_P (type))
15479 return type_is_unavailable
15480 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
15482 return NULL_TREE;
15485 /* Decode the list of parameter types for a function type.
15486 Given the list of things declared inside the parens,
15487 return a list of types.
15489 If this parameter does not end with an ellipsis, we append
15490 void_list_node.
15492 *PARMS is set to the chain of PARM_DECLs created. */
15494 tree
15495 grokparms (tree parmlist, tree *parms)
15497 tree result = NULL_TREE;
15498 tree decls = NULL_TREE;
15499 tree parm;
15500 int any_error = 0;
15502 for (parm = parmlist; parm != NULL_TREE; parm = TREE_CHAIN (parm))
15504 tree type = NULL_TREE;
15505 tree init = TREE_PURPOSE (parm);
15506 tree decl = TREE_VALUE (parm);
15508 if (parm == void_list_node || parm == explicit_void_list_node)
15509 break;
15511 if (! decl || TREE_TYPE (decl) == error_mark_node)
15513 any_error = 1;
15514 continue;
15517 type = TREE_TYPE (decl);
15518 if (VOID_TYPE_P (type))
15520 if (same_type_p (type, void_type_node)
15521 && !init
15522 && !DECL_NAME (decl) && !result
15523 && TREE_CHAIN (parm) == void_list_node)
15524 /* DR 577: A parameter list consisting of a single
15525 unnamed parameter of non-dependent type 'void'. */
15526 break;
15527 else if (cv_qualified_p (type))
15528 error_at (DECL_SOURCE_LOCATION (decl),
15529 "invalid use of cv-qualified type %qT in "
15530 "parameter declaration", type);
15531 else
15532 error_at (DECL_SOURCE_LOCATION (decl),
15533 "invalid use of type %<void%> in parameter "
15534 "declaration");
15535 /* It's not a good idea to actually create parameters of
15536 type `void'; other parts of the compiler assume that a
15537 void type terminates the parameter list. */
15538 type = error_mark_node;
15539 TREE_TYPE (decl) = error_mark_node;
15542 if (type != error_mark_node)
15544 if (deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
15546 tree unavailtype = type_is_unavailable (type);
15547 if (unavailtype)
15548 cp_handle_deprecated_or_unavailable (unavailtype);
15550 if (deprecated_state != DEPRECATED_SUPPRESS
15551 && deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
15553 tree deptype = type_is_deprecated (type);
15554 if (deptype)
15555 cp_handle_deprecated_or_unavailable (deptype);
15558 /* [dcl.fct] "A parameter with volatile-qualified type is
15559 deprecated." */
15560 if (CP_TYPE_VOLATILE_P (type))
15561 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wvolatile,
15562 "%<volatile%>-qualified parameter is "
15563 "deprecated");
15565 /* Top-level qualifiers on the parameters are
15566 ignored for function types. */
15567 type = cp_build_qualified_type (type, 0);
15568 if (TREE_CODE (type) == METHOD_TYPE)
15570 error ("parameter %qD invalidly declared method type", decl);
15571 type = build_pointer_type (type);
15572 TREE_TYPE (decl) = type;
15574 else if (cxx_dialect < cxx17 && INDIRECT_TYPE_P (type))
15576 /* Before C++17 DR 393:
15577 [dcl.fct]/6, parameter types cannot contain pointers
15578 (references) to arrays of unknown bound. */
15579 tree t = TREE_TYPE (type);
15580 int ptr = TYPE_PTR_P (type);
15582 while (1)
15584 if (TYPE_PTR_P (t))
15585 ptr = 1;
15586 else if (TREE_CODE (t) != ARRAY_TYPE)
15587 break;
15588 else if (!TYPE_DOMAIN (t))
15589 break;
15590 t = TREE_TYPE (t);
15592 if (TREE_CODE (t) == ARRAY_TYPE)
15593 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
15595 ? G_("parameter %qD includes pointer to array of "
15596 "unknown bound %qT")
15597 : G_("parameter %qD includes reference to array of "
15598 "unknown bound %qT"),
15599 decl, t);
15602 if (init && !processing_template_decl)
15603 init = check_default_argument (decl, init, tf_warning_or_error);
15606 DECL_CHAIN (decl) = decls;
15607 decls = decl;
15608 result = tree_cons (init, type, result);
15610 decls = nreverse (decls);
15611 result = nreverse (result);
15612 if (parm)
15613 result = chainon (result, void_list_node);
15614 *parms = decls;
15615 if (any_error)
15616 result = NULL_TREE;
15618 if (any_error)
15619 /* We had parm errors, recover by giving the function (...) type. */
15620 result = NULL_TREE;
15622 return result;
15626 /* D is a constructor or overloaded `operator='.
15628 Let T be the class in which D is declared. Then, this function
15629 returns:
15631 -1 if D's is an ill-formed constructor or copy assignment operator
15632 whose first parameter is of type `T'.
15633 0 if D is not a copy constructor or copy assignment
15634 operator.
15635 1 if D is a copy constructor or copy assignment operator whose
15636 first parameter is a reference to non-const qualified T.
15637 2 if D is a copy constructor or copy assignment operator whose
15638 first parameter is a reference to const qualified T.
15640 This function can be used as a predicate. Positive values indicate
15641 a copy constructor and nonzero values indicate a copy assignment
15642 operator. */
15645 copy_fn_p (const_tree d)
15647 tree args;
15648 tree arg_type;
15649 int result = 1;
15651 gcc_assert (DECL_FUNCTION_MEMBER_P (d));
15653 if (TREE_CODE (d) == TEMPLATE_DECL
15654 || (DECL_TEMPLATE_INFO (d)
15655 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
15656 /* Instantiations of template member functions are never copy
15657 functions. Note that member functions of templated classes are
15658 represented as template functions internally, and we must
15659 accept those as copy functions. */
15660 return 0;
15662 if (!DECL_CONSTRUCTOR_P (d)
15663 && DECL_NAME (d) != assign_op_identifier)
15664 return 0;
15666 if (DECL_XOBJ_MEMBER_FUNCTION_P (d))
15668 tree object_param = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (d)));
15669 if (!TYPE_REF_P (object_param)
15670 || TYPE_REF_IS_RVALUE (object_param)
15671 /* Reject unrelated object parameters. */
15672 || TYPE_MAIN_VARIANT (TREE_TYPE (object_param)) != DECL_CONTEXT (d)
15673 || CP_TYPE_CONST_P (TREE_TYPE (object_param)))
15674 return 0;
15675 args = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (d)));
15677 else
15678 args = FUNCTION_FIRST_USER_PARMTYPE (d);
15679 if (!args)
15680 return 0;
15682 arg_type = TREE_VALUE (args);
15683 if (arg_type == error_mark_node)
15684 return 0;
15686 if (TYPE_MAIN_VARIANT (arg_type) == DECL_CONTEXT (d))
15688 /* Pass by value copy assignment operator. */
15689 result = -1;
15691 else if (TYPE_REF_P (arg_type)
15692 && !TYPE_REF_IS_RVALUE (arg_type)
15693 && TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)) == DECL_CONTEXT (d))
15695 if (CP_TYPE_CONST_P (TREE_TYPE (arg_type)))
15696 result = 2;
15698 else
15699 return 0;
15701 args = TREE_CHAIN (args);
15703 if (args && args != void_list_node && !TREE_PURPOSE (args))
15704 /* There are more non-optional args. */
15705 return 0;
15707 return result;
15710 /* D is a constructor or overloaded `operator='.
15712 Let T be the class in which D is declared. Then, this function
15713 returns true when D is a move constructor or move assignment
15714 operator, false otherwise. */
15716 bool
15717 move_fn_p (const_tree d)
15719 if (cxx_dialect == cxx98)
15720 /* There are no move constructors if we are in C++98 mode. */
15721 return false;
15723 if (TREE_CODE (d) == TEMPLATE_DECL
15724 || (DECL_TEMPLATE_INFO (d)
15725 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
15726 /* Instantiations of template member functions are never move
15727 functions. Note that member functions of templated classes are
15728 represented as template functions internally, and we must
15729 accept those as move functions. */
15730 return 0;
15732 return move_signature_fn_p (d);
15735 /* D is a constructor or overloaded `operator='.
15737 Then, this function returns true when D has the same signature as a move
15738 constructor or move assignment operator (because either it is such a
15739 ctor/op= or it is a template specialization with the same signature),
15740 false otherwise. */
15742 bool
15743 move_signature_fn_p (const_tree d)
15745 tree args;
15746 tree arg_type;
15747 bool result = false;
15749 if (!DECL_CONSTRUCTOR_P (d)
15750 && DECL_NAME (d) != assign_op_identifier)
15751 return 0;
15753 if (DECL_XOBJ_MEMBER_FUNCTION_P (d))
15755 tree object_param = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (d)));
15756 if (!TYPE_REF_P (object_param)
15757 || TYPE_REF_IS_RVALUE (object_param)
15758 /* Reject unrelated object parameters. */
15759 || TYPE_MAIN_VARIANT (TREE_TYPE (object_param)) != DECL_CONTEXT (d)
15760 || CP_TYPE_CONST_P (TREE_TYPE (object_param)))
15761 return 0;
15762 args = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (d)));
15764 else
15765 args = FUNCTION_FIRST_USER_PARMTYPE (d);
15766 if (!args)
15767 return 0;
15769 arg_type = TREE_VALUE (args);
15770 if (arg_type == error_mark_node)
15771 return 0;
15773 if (TYPE_REF_P (arg_type)
15774 && TYPE_REF_IS_RVALUE (arg_type)
15775 && same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)),
15776 DECL_CONTEXT (d)))
15777 result = true;
15779 args = TREE_CHAIN (args);
15781 if (args && args != void_list_node && !TREE_PURPOSE (args))
15782 /* There are more non-optional args. */
15783 return false;
15785 return result;
15788 /* Remember any special properties of member function DECL. */
15790 void
15791 grok_special_member_properties (tree decl)
15793 tree class_type;
15795 if (TREE_CODE (decl) == USING_DECL
15796 || !DECL_OBJECT_MEMBER_FUNCTION_P (decl))
15797 return;
15799 class_type = DECL_CONTEXT (decl);
15800 if (IDENTIFIER_CTOR_P (DECL_NAME (decl)))
15802 int ctor = copy_fn_p (decl);
15804 if (!DECL_ARTIFICIAL (decl))
15805 TYPE_HAS_USER_CONSTRUCTOR (class_type) = 1;
15807 if (ctor > 0)
15809 /* [class.copy]
15811 A non-template constructor for class X is a copy
15812 constructor if its first parameter is of type X&, const
15813 X&, volatile X& or const volatile X&, and either there
15814 are no other parameters or else all other parameters have
15815 default arguments. */
15816 TYPE_HAS_COPY_CTOR (class_type) = 1;
15817 if (ctor > 1)
15818 TYPE_HAS_CONST_COPY_CTOR (class_type) = 1;
15821 if (sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (decl)))
15822 TYPE_HAS_DEFAULT_CONSTRUCTOR (class_type) = 1;
15824 if (is_list_ctor (decl))
15825 TYPE_HAS_LIST_CTOR (class_type) = 1;
15827 if (maybe_constexpr_fn (decl)
15828 && !ctor && !move_fn_p (decl))
15829 TYPE_HAS_CONSTEXPR_CTOR (class_type) = 1;
15831 else if (DECL_NAME (decl) == assign_op_identifier)
15833 /* [class.copy]
15835 A non-template assignment operator for class X is a copy
15836 assignment operator if its parameter is of type X, X&, const
15837 X&, volatile X& or const volatile X&. */
15839 int assop = copy_fn_p (decl);
15841 if (assop)
15843 TYPE_HAS_COPY_ASSIGN (class_type) = 1;
15844 if (assop != 1)
15845 TYPE_HAS_CONST_COPY_ASSIGN (class_type) = 1;
15848 else if (IDENTIFIER_CONV_OP_P (DECL_NAME (decl)))
15849 TYPE_HAS_CONVERSION (class_type) = true;
15851 /* Destructors are handled in check_methods. */
15854 /* Check a constructor DECL has the correct form. Complains
15855 if the class has a constructor of the form X(X). */
15857 bool
15858 grok_ctor_properties (const_tree ctype, const_tree decl)
15860 int ctor_parm = copy_fn_p (decl);
15862 if (ctor_parm < 0)
15864 /* [class.copy]
15866 A declaration of a constructor for a class X is ill-formed if
15867 its first parameter is of type (optionally cv-qualified) X
15868 and either there are no other parameters or else all other
15869 parameters have default arguments.
15871 We *don't* complain about member template instantiations that
15872 have this form, though; they can occur as we try to decide
15873 what constructor to use during overload resolution. Since
15874 overload resolution will never prefer such a constructor to
15875 the non-template copy constructor (which is either explicitly
15876 or implicitly defined), there's no need to worry about their
15877 existence. Theoretically, they should never even be
15878 instantiated, but that's hard to forestall. */
15879 error_at (DECL_SOURCE_LOCATION (decl),
15880 "invalid constructor; you probably meant %<%T (const %T&)%>",
15881 ctype, ctype);
15882 return false;
15885 return true;
15888 /* DECL is a declaration for an overloaded or conversion operator. If
15889 COMPLAIN is true, errors are issued for invalid declarations. */
15891 bool
15892 grok_op_properties (tree decl, bool complain)
15894 tree argtypes = TYPE_ARG_TYPES (TREE_TYPE (decl));
15895 bool const methodp = DECL_IOBJ_MEMBER_FUNCTION_P (decl);
15896 tree name = DECL_NAME (decl);
15897 location_t loc = DECL_SOURCE_LOCATION (decl);
15899 tree class_type = DECL_CONTEXT (decl);
15900 if (class_type && !CLASS_TYPE_P (class_type))
15901 class_type = NULL_TREE;
15903 tree_code operator_code;
15904 unsigned op_flags;
15905 if (IDENTIFIER_CONV_OP_P (name))
15907 /* Conversion operators are TYPE_EXPR for the purposes of this
15908 function. */
15909 operator_code = TYPE_EXPR;
15910 op_flags = OVL_OP_FLAG_UNARY;
15912 else
15914 const ovl_op_info_t *ovl_op = IDENTIFIER_OVL_OP_INFO (name);
15916 operator_code = ovl_op->tree_code;
15917 op_flags = ovl_op->flags;
15918 gcc_checking_assert (operator_code != ERROR_MARK);
15919 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
15922 if (op_flags & OVL_OP_FLAG_ALLOC)
15924 /* operator new and operator delete are quite special. */
15925 if (class_type)
15926 switch (op_flags)
15928 case OVL_OP_FLAG_ALLOC:
15929 TYPE_HAS_NEW_OPERATOR (class_type) = 1;
15930 break;
15932 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE:
15933 TYPE_GETS_DELETE (class_type) |= 1;
15934 break;
15936 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_VEC:
15937 TYPE_HAS_ARRAY_NEW_OPERATOR (class_type) = 1;
15938 break;
15940 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE | OVL_OP_FLAG_VEC:
15941 TYPE_GETS_DELETE (class_type) |= 2;
15942 break;
15944 default:
15945 gcc_unreachable ();
15948 /* [basic.std.dynamic.allocation]/1:
15950 A program is ill-formed if an allocation function is declared
15951 in a namespace scope other than global scope or declared
15952 static in global scope.
15954 The same also holds true for deallocation functions. */
15955 if (DECL_NAMESPACE_SCOPE_P (decl))
15957 if (CP_DECL_CONTEXT (decl) != global_namespace)
15959 error_at (loc, "%qD may not be declared within a namespace",
15960 decl);
15961 return false;
15964 if (!TREE_PUBLIC (decl))
15966 error_at (loc, "%qD may not be declared as static", decl);
15967 return false;
15971 if (op_flags & OVL_OP_FLAG_DELETE)
15973 DECL_SET_IS_OPERATOR_DELETE (decl, true);
15974 coerce_delete_type (decl, loc);
15976 else
15978 DECL_SET_IS_OPERATOR_NEW (decl, true);
15979 TREE_TYPE (decl) = coerce_new_type (TREE_TYPE (decl), loc);
15982 return true;
15985 /* An operator function must either be a non-static member function
15986 or have at least one parameter of a class, a reference to a class,
15987 an enumeration, or a reference to an enumeration. 13.4.0.6 */
15988 if (!DECL_OBJECT_MEMBER_FUNCTION_P (decl))
15990 if (operator_code == TYPE_EXPR
15991 || operator_code == COMPONENT_REF
15992 || operator_code == NOP_EXPR)
15994 error_at (loc, "%qD must be a non-static member function", decl);
15995 return false;
15998 if (operator_code == CALL_EXPR || operator_code == ARRAY_REF)
16000 if (! DECL_STATIC_FUNCTION_P (decl))
16002 error_at (loc, "%qD must be a member function", decl);
16003 return false;
16005 if (cxx_dialect < cxx23
16006 /* For lambdas we diagnose static lambda specifier elsewhere. */
16007 && (operator_code == ARRAY_REF || ! LAMBDA_FUNCTION_P (decl))
16008 /* For instantiations, we have diagnosed this already. */
16009 && ! DECL_USE_TEMPLATE (decl))
16010 pedwarn (loc, OPT_Wc__23_extensions, "%qD may be a static member "
16011 "function only with %<-std=c++23%> or %<-std=gnu++23%>",
16012 decl);
16013 if (operator_code == ARRAY_REF)
16014 /* static operator[] should have exactly one argument
16015 for C++20 and earlier, so that it isn't multidimensional. */
16016 op_flags = OVL_OP_FLAG_UNARY;
16018 else if (DECL_STATIC_FUNCTION_P (decl))
16020 error_at (loc, "%qD must be either a non-static member "
16021 "function or a non-member function", decl);
16022 return false;
16024 else
16025 for (tree arg = argtypes; ; arg = TREE_CHAIN (arg))
16027 if (!arg || arg == void_list_node)
16029 if (complain)
16030 error_at (loc, "%qD must have an argument of class or "
16031 "enumerated type", decl);
16032 return false;
16035 tree type = non_reference (TREE_VALUE (arg));
16036 if (type == error_mark_node)
16037 return false;
16039 /* MAYBE_CLASS_TYPE_P, rather than CLASS_TYPE_P, is used
16040 because these checks are performed even on template
16041 functions. */
16042 if (MAYBE_CLASS_TYPE_P (type)
16043 || TREE_CODE (type) == ENUMERAL_TYPE)
16044 break;
16048 if (operator_code == CALL_EXPR)
16049 /* There are no further restrictions on the arguments to an overloaded
16050 "operator ()". */
16051 return true;
16053 /* C++23 allows an arbitrary number of parameters and default arguments for
16054 operator[], and none of the other checks below apply. */
16055 if (operator_code == ARRAY_REF && cxx_dialect >= cxx23)
16056 return true;
16058 if (operator_code == COND_EXPR)
16060 /* 13.4.0.3 */
16061 error_at (loc, "ISO C++ prohibits overloading %<operator ?:%>");
16062 return false;
16065 /* Count the number of arguments and check for ellipsis. */
16066 int arity = 0;
16067 for (tree arg = argtypes; arg != void_list_node; arg = TREE_CHAIN (arg))
16069 if (!arg)
16071 error_at (loc, "%qD must not have variable number of arguments",
16072 decl);
16073 return false;
16075 ++arity;
16077 /* FIXME: We need tests for these errors with xobj member functions. */
16078 /* Verify correct number of arguments. */
16079 switch (op_flags)
16081 case OVL_OP_FLAG_AMBIARY:
16082 if (arity == 1)
16084 /* We have a unary instance of an ambi-ary op. Remap to the
16085 unary one. */
16086 unsigned alt = ovl_op_alternate[ovl_op_mapping [operator_code]];
16087 const ovl_op_info_t *ovl_op = &ovl_op_info[false][alt];
16088 gcc_checking_assert (ovl_op->flags == OVL_OP_FLAG_UNARY);
16089 operator_code = ovl_op->tree_code;
16090 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
16092 else if (arity != 2)
16094 /* This was an ambiguous operator but is invalid. */
16095 error_at (loc,
16096 methodp
16097 ? G_("%qD must have either zero or one argument")
16098 : G_("%qD must have either one or two arguments"), decl);
16099 return false;
16101 else if ((operator_code == POSTINCREMENT_EXPR
16102 || operator_code == POSTDECREMENT_EXPR)
16103 && ! processing_template_decl
16104 /* x++ and x--'s second argument must be an int. */
16105 && ! same_type_p (TREE_VALUE (TREE_CHAIN (argtypes)),
16106 integer_type_node))
16108 error_at (loc,
16109 methodp
16110 ? G_("postfix %qD must have %<int%> as its argument")
16111 : G_("postfix %qD must have %<int%> as its second argument"),
16112 decl);
16113 return false;
16115 break;
16117 case OVL_OP_FLAG_UNARY:
16118 if (arity != 1)
16120 error_at (loc,
16121 methodp
16122 ? G_("%qD must have no arguments")
16123 : G_("%qD must have exactly one argument"), decl);
16124 return false;
16126 break;
16128 case OVL_OP_FLAG_BINARY:
16129 if (arity != 2)
16131 error_at (loc,
16132 methodp
16133 ? G_("%qD must have exactly one argument")
16134 : G_("%qD must have exactly two arguments"), decl);
16135 return false;
16137 break;
16139 default:
16140 gcc_unreachable ();
16143 /* There can be no default arguments. */
16144 for (tree arg = argtypes; arg && arg != void_list_node;
16145 arg = TREE_CHAIN (arg))
16146 if (TREE_PURPOSE (arg))
16148 TREE_PURPOSE (arg) = NULL_TREE;
16149 error_at (loc, "%qD cannot have default arguments", decl);
16150 return false;
16153 /* At this point the declaration is well-formed. It may not be
16154 sensible though. */
16156 /* Check member function warnings only on the in-class declaration.
16157 There's no point warning on an out-of-class definition. */
16158 if (class_type && class_type != current_class_type)
16159 return true;
16161 /* Warn about conversion operators that will never be used. */
16162 if (IDENTIFIER_CONV_OP_P (name)
16163 && ! DECL_TEMPLATE_INFO (decl)
16164 && warn_class_conversion)
16166 tree t = TREE_TYPE (name);
16167 int ref = TYPE_REF_P (t);
16169 if (ref)
16170 t = TYPE_MAIN_VARIANT (TREE_TYPE (t));
16172 if (VOID_TYPE_P (t))
16173 warning_at (loc, OPT_Wclass_conversion, "converting %qT to %<void%> "
16174 "will never use a type conversion operator", class_type);
16175 else if (class_type)
16177 if (same_type_ignoring_top_level_qualifiers_p (t, class_type))
16178 warning_at (loc, OPT_Wclass_conversion,
16180 ? G_("converting %qT to a reference to the same type "
16181 "will never use a type conversion operator")
16182 : G_("converting %qT to the same type "
16183 "will never use a type conversion operator"),
16184 class_type);
16185 /* Don't force t to be complete here. */
16186 else if (MAYBE_CLASS_TYPE_P (t)
16187 && COMPLETE_TYPE_P (t)
16188 && DERIVED_FROM_P (t, class_type))
16189 warning_at (loc, OPT_Wclass_conversion,
16191 ? G_("converting %qT to a reference to a base class "
16192 "%qT will never use a type conversion operator")
16193 : G_("converting %qT to a base class %qT "
16194 "will never use a type conversion operator"),
16195 class_type, t);
16199 if (!warn_ecpp)
16200 return true;
16202 /* Effective C++ rules below. */
16204 /* More Effective C++ rule 7. */
16205 if (operator_code == TRUTH_ANDIF_EXPR
16206 || operator_code == TRUTH_ORIF_EXPR
16207 || operator_code == COMPOUND_EXPR)
16208 warning_at (loc, OPT_Weffc__,
16209 "user-defined %qD always evaluates both arguments", decl);
16211 /* More Effective C++ rule 6. */
16212 if (operator_code == POSTINCREMENT_EXPR
16213 || operator_code == POSTDECREMENT_EXPR
16214 || operator_code == PREINCREMENT_EXPR
16215 || operator_code == PREDECREMENT_EXPR)
16217 tree arg = TREE_VALUE (argtypes);
16218 tree ret = TREE_TYPE (TREE_TYPE (decl));
16219 if (methodp || TYPE_REF_P (arg))
16220 arg = TREE_TYPE (arg);
16221 arg = TYPE_MAIN_VARIANT (arg);
16223 if (operator_code == PREINCREMENT_EXPR
16224 || operator_code == PREDECREMENT_EXPR)
16226 if (!TYPE_REF_P (ret)
16227 || !same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (ret)), arg))
16228 warning_at (loc, OPT_Weffc__, "prefix %qD should return %qT", decl,
16229 build_reference_type (arg));
16231 else
16233 if (!same_type_p (TYPE_MAIN_VARIANT (ret), arg))
16234 warning_at (loc, OPT_Weffc__,
16235 "postfix %qD should return %qT", decl, arg);
16239 /* Effective C++ rule 23. */
16240 if (!DECL_ASSIGNMENT_OPERATOR_P (decl)
16241 && (operator_code == PLUS_EXPR
16242 || operator_code == MINUS_EXPR
16243 || operator_code == TRUNC_DIV_EXPR
16244 || operator_code == MULT_EXPR
16245 || operator_code == TRUNC_MOD_EXPR)
16246 && TYPE_REF_P (TREE_TYPE (TREE_TYPE (decl))))
16247 warning_at (loc, OPT_Weffc__, "%qD should return by value", decl);
16249 return true;
16252 /* Return a string giving the keyword associate with CODE. */
16254 static const char *
16255 tag_name (enum tag_types code)
16257 switch (code)
16259 case record_type:
16260 return "struct";
16261 case class_type:
16262 return "class";
16263 case union_type:
16264 return "union";
16265 case enum_type:
16266 return "enum";
16267 case typename_type:
16268 return "typename";
16269 default:
16270 gcc_unreachable ();
16274 /* Name lookup in an elaborated-type-specifier (after the keyword
16275 indicated by TAG_CODE) has found the TYPE_DECL DECL. If the
16276 elaborated-type-specifier is invalid, issue a diagnostic and return
16277 error_mark_node; otherwise, return the *_TYPE to which it referred.
16278 If ALLOW_TEMPLATE_P is true, TYPE may be a class template. */
16280 tree
16281 check_elaborated_type_specifier (enum tag_types tag_code,
16282 tree decl,
16283 bool allow_template_p)
16285 tree type;
16287 /* In the case of:
16289 struct S { struct S *p; };
16291 name lookup will find the TYPE_DECL for the implicit "S::S"
16292 typedef. Adjust for that here. */
16293 if (DECL_SELF_REFERENCE_P (decl))
16294 decl = TYPE_NAME (TREE_TYPE (decl));
16296 type = TREE_TYPE (decl);
16298 /* Check TEMPLATE_TYPE_PARM first because DECL_IMPLICIT_TYPEDEF_P
16299 is false for this case as well. */
16300 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16302 error ("using template type parameter %qT after %qs",
16303 type, tag_name (tag_code));
16304 return error_mark_node;
16306 /* Accept template template parameters. */
16307 else if (allow_template_p
16308 && (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
16309 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM))
16311 /* [dcl.type.elab]
16313 If the identifier resolves to a typedef-name or the
16314 simple-template-id resolves to an alias template
16315 specialization, the elaborated-type-specifier is ill-formed.
16317 In other words, the only legitimate declaration to use in the
16318 elaborated type specifier is the implicit typedef created when
16319 the type is declared. */
16320 else if (!DECL_IMPLICIT_TYPEDEF_P (decl)
16321 && !DECL_SELF_REFERENCE_P (decl)
16322 && tag_code != typename_type)
16324 if (alias_template_specialization_p (type, nt_opaque))
16325 error ("using alias template specialization %qT after %qs",
16326 type, tag_name (tag_code));
16327 else
16328 error ("using typedef-name %qD after %qs", decl, tag_name (tag_code));
16329 inform (DECL_SOURCE_LOCATION (decl),
16330 "%qD has a previous declaration here", decl);
16331 return error_mark_node;
16333 else if (TREE_CODE (type) != RECORD_TYPE
16334 && TREE_CODE (type) != UNION_TYPE
16335 && tag_code != enum_type
16336 && tag_code != typename_type)
16338 error ("%qT referred to as %qs", type, tag_name (tag_code));
16339 inform (location_of (type), "%qT has a previous declaration here", type);
16340 return error_mark_node;
16342 else if (TREE_CODE (type) != ENUMERAL_TYPE
16343 && tag_code == enum_type)
16345 error ("%qT referred to as enum", type);
16346 inform (location_of (type), "%qT has a previous declaration here", type);
16347 return error_mark_node;
16349 else if (!allow_template_p
16350 && TREE_CODE (type) == RECORD_TYPE
16351 && CLASSTYPE_IS_TEMPLATE (type))
16353 /* If a class template appears as elaborated type specifier
16354 without a template header such as:
16356 template <class T> class C {};
16357 void f(class C); // No template header here
16359 then the required template argument is missing. */
16360 error ("template argument required for %<%s %T%>",
16361 tag_name (tag_code),
16362 DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)));
16363 return error_mark_node;
16366 return type;
16369 /* Lookup NAME of an elaborated type specifier according to SCOPE and
16370 issue diagnostics if necessary. Return *_TYPE node upon success,
16371 NULL_TREE when the NAME is not found, and ERROR_MARK_NODE for type
16372 error. */
16374 static tree
16375 lookup_and_check_tag (enum tag_types tag_code, tree name,
16376 TAG_how how, bool template_header_p)
16378 tree decl;
16379 if (how == TAG_how::GLOBAL)
16381 /* First try ordinary name lookup, ignoring hidden class name
16382 injected via friend declaration. */
16383 decl = lookup_name (name, LOOK_want::TYPE);
16384 decl = strip_using_decl (decl);
16385 /* If that fails, the name will be placed in the smallest
16386 non-class, non-function-prototype scope according to 3.3.1/5.
16387 We may already have a hidden name declared as friend in this
16388 scope. So lookup again but not ignoring hidden names.
16389 If we find one, that name will be made visible rather than
16390 creating a new tag. */
16391 if (!decl)
16392 decl = lookup_elaborated_type (name, TAG_how::INNERMOST_NON_CLASS);
16394 else
16395 decl = lookup_elaborated_type (name, how);
16397 if (!decl)
16398 /* We found nothing. */
16399 return NULL_TREE;
16401 if (TREE_CODE (decl) == TREE_LIST)
16403 error ("reference to %qD is ambiguous", name);
16404 print_candidates (decl);
16405 return error_mark_node;
16408 if (DECL_CLASS_TEMPLATE_P (decl)
16409 && !template_header_p
16410 && how == TAG_how::CURRENT_ONLY)
16412 error ("class template %qD redeclared as non-template", name);
16413 inform (location_of (decl), "previous declaration here");
16414 CLASSTYPE_ERRONEOUS (TREE_TYPE (decl)) = true;
16415 return error_mark_node;
16418 if (DECL_CLASS_TEMPLATE_P (decl)
16419 /* If scope is TAG_how::CURRENT_ONLY we're defining a class,
16420 so ignore a template template parameter. */
16421 || (how != TAG_how::CURRENT_ONLY && DECL_TEMPLATE_TEMPLATE_PARM_P (decl)))
16422 decl = DECL_TEMPLATE_RESULT (decl);
16424 if (TREE_CODE (decl) != TYPE_DECL)
16425 /* Found not-a-type. */
16426 return NULL_TREE;
16428 /* Look for invalid nested type:
16429 class C {
16430 class C {};
16431 }; */
16432 if (how == TAG_how::CURRENT_ONLY && DECL_SELF_REFERENCE_P (decl))
16434 error ("%qD has the same name as the class in which it is "
16435 "declared", decl);
16436 return error_mark_node;
16439 /* Two cases we need to consider when deciding if a class
16440 template is allowed as an elaborated type specifier:
16441 1. It is a self reference to its own class.
16442 2. It comes with a template header.
16444 For example:
16446 template <class T> class C {
16447 class C *c1; // DECL_SELF_REFERENCE_P is true
16448 class D;
16450 template <class U> class C; // template_header_p is true
16451 template <class T> class C<T>::D {
16452 class C *c2; // DECL_SELF_REFERENCE_P is true
16453 }; */
16455 tree t = check_elaborated_type_specifier (tag_code, decl,
16456 template_header_p
16457 | DECL_SELF_REFERENCE_P (decl));
16458 if (template_header_p && t && CLASS_TYPE_P (t)
16459 && (!CLASSTYPE_TEMPLATE_INFO (t)
16460 || (!PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))))
16462 error ("%qT is not a template", t);
16463 inform (location_of (t), "previous declaration here");
16464 if (TYPE_CLASS_SCOPE_P (t)
16465 && CLASSTYPE_TEMPLATE_INFO (TYPE_CONTEXT (t)))
16466 inform (input_location,
16467 "perhaps you want to explicitly add %<%T::%>",
16468 TYPE_CONTEXT (t));
16469 return error_mark_node;
16472 return t;
16475 /* Get the struct, enum or union (TAG_CODE says which) with tag NAME.
16476 Define the tag as a forward-reference if it is not defined.
16478 If a declaration is given, process it here, and report an error if
16479 multiple declarations are not identical.
16481 SCOPE is TS_CURRENT when this is also a definition. Only look in
16482 the current frame for the name (since C++ allows new names in any
16483 scope.) It is TS_WITHIN_ENCLOSING_NON_CLASS if this is a friend
16484 declaration. Only look beginning from the current scope outward up
16485 till the nearest non-class scope. Otherwise it is TS_GLOBAL.
16487 TEMPLATE_HEADER_P is true when this declaration is preceded by
16488 a set of template parameters. */
16490 tree
16491 xref_tag (enum tag_types tag_code, tree name,
16492 TAG_how how, bool template_header_p)
16494 enum tree_code code;
16495 tree context = NULL_TREE;
16497 auto_cond_timevar tv (TV_NAME_LOOKUP);
16499 gcc_assert (identifier_p (name));
16501 switch (tag_code)
16503 case record_type:
16504 case class_type:
16505 code = RECORD_TYPE;
16506 break;
16507 case union_type:
16508 code = UNION_TYPE;
16509 break;
16510 case enum_type:
16511 code = ENUMERAL_TYPE;
16512 break;
16513 default:
16514 gcc_unreachable ();
16517 /* In case of anonymous name, xref_tag is only called to
16518 make type node and push name. Name lookup is not required. */
16519 tree t = NULL_TREE;
16520 if (!IDENTIFIER_ANON_P (name))
16521 t = lookup_and_check_tag (tag_code, name, how, template_header_p);
16523 if (t == error_mark_node)
16524 return error_mark_node;
16526 if (how != TAG_how::CURRENT_ONLY && t && current_class_type
16527 && template_class_depth (current_class_type)
16528 && template_header_p)
16530 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
16531 return t;
16533 /* Since HOW is not TAG_how::CURRENT_ONLY, we are not looking at
16534 a definition of this tag. Since, in addition, we are
16535 currently processing a (member) template declaration of a
16536 template class, we must be very careful; consider:
16538 template <class X> struct S1
16540 template <class U> struct S2
16542 template <class V> friend struct S1;
16545 Here, the S2::S1 declaration should not be confused with the
16546 outer declaration. In particular, the inner version should
16547 have a template parameter of level 2, not level 1.
16549 On the other hand, when presented with:
16551 template <class T> struct S1
16553 template <class U> struct S2 {};
16554 template <class U> friend struct S2;
16557 the friend must find S1::S2 eventually. We accomplish this
16558 by making sure that the new type we create to represent this
16559 declaration has the right TYPE_CONTEXT. */
16560 context = TYPE_CONTEXT (t);
16561 t = NULL_TREE;
16564 if (! t)
16566 /* If no such tag is yet defined, create a forward-reference node
16567 and record it as the "definition".
16568 When a real declaration of this type is found,
16569 the forward-reference will be altered into a real type. */
16570 if (code == ENUMERAL_TYPE)
16572 error ("use of enum %q#D without previous declaration", name);
16573 return error_mark_node;
16576 t = make_class_type (code);
16577 TYPE_CONTEXT (t) = context;
16578 if (IDENTIFIER_LAMBDA_P (name))
16579 /* Mark it as a lambda type right now. Our caller will
16580 correct the value. */
16581 CLASSTYPE_LAMBDA_EXPR (t) = error_mark_node;
16582 t = pushtag (name, t, how);
16584 else
16586 if (template_header_p && MAYBE_CLASS_TYPE_P (t))
16588 /* Check that we aren't trying to overload a class with different
16589 constraints. */
16590 if (!redeclare_class_template (t, current_template_parms,
16591 current_template_constraints ()))
16592 return error_mark_node;
16594 else if (!processing_template_decl
16595 && CLASS_TYPE_P (t)
16596 && CLASSTYPE_IS_TEMPLATE (t))
16598 error ("redeclaration of %qT as a non-template", t);
16599 inform (location_of (t), "previous declaration %qD", t);
16600 return error_mark_node;
16603 if (modules_p ()
16604 && how == TAG_how::CURRENT_ONLY)
16606 tree decl = TYPE_NAME (t);
16607 if (!module_may_redeclare (decl))
16609 auto_diagnostic_group d;
16610 error ("cannot declare %qD in a different module", decl);
16611 inform (DECL_SOURCE_LOCATION (decl), "previously declared here");
16612 return error_mark_node;
16615 tree not_tmpl = STRIP_TEMPLATE (decl);
16616 if (DECL_LANG_SPECIFIC (not_tmpl)
16617 && DECL_MODULE_ATTACH_P (not_tmpl)
16618 && !DECL_MODULE_EXPORT_P (not_tmpl)
16619 && module_exporting_p ())
16621 auto_diagnostic_group d;
16622 error ("conflicting exporting for declaration %qD", decl);
16623 inform (DECL_SOURCE_LOCATION (decl),
16624 "previously declared here without exporting");
16627 tree maybe_tmpl = decl;
16628 if (CLASS_TYPE_P (t) && CLASSTYPE_IS_TEMPLATE (t))
16629 maybe_tmpl = CLASSTYPE_TI_TEMPLATE (t);
16631 if (DECL_LANG_SPECIFIC (decl)
16632 && DECL_MODULE_IMPORT_P (decl)
16633 && TREE_CODE (CP_DECL_CONTEXT (decl)) == NAMESPACE_DECL)
16635 /* Push it into this TU's symbol slot. */
16636 gcc_checking_assert (current_namespace == CP_DECL_CONTEXT (decl));
16637 if (maybe_tmpl != decl)
16638 /* We're in the template parm binding level.
16639 Pushtag has logic to slide under that, but we're
16640 not pushing a *new* type. */
16641 push_nested_namespace (CP_DECL_CONTEXT (decl));
16643 pushdecl (maybe_tmpl);
16644 if (maybe_tmpl != decl)
16645 pop_nested_namespace (CP_DECL_CONTEXT (decl));
16648 set_instantiating_module (maybe_tmpl);
16652 return t;
16655 /* Create the binfo hierarchy for REF with (possibly NULL) base list
16656 BASE_LIST. For each element on BASE_LIST the TREE_PURPOSE is an
16657 access_* node, and the TREE_VALUE is the type of the base-class.
16658 Non-NULL TREE_TYPE indicates virtual inheritance. */
16660 void
16661 xref_basetypes (tree ref, tree base_list)
16663 tree *basep;
16664 tree binfo, base_binfo;
16665 unsigned max_vbases = 0; /* Maximum direct & indirect virtual bases. */
16666 unsigned max_bases = 0; /* Maximum direct bases. */
16667 unsigned max_dvbases = 0; /* Maximum direct virtual bases. */
16668 int i;
16669 tree default_access;
16670 tree igo_prev; /* Track Inheritance Graph Order. */
16672 if (ref == error_mark_node)
16673 return;
16675 /* The base of a derived class is private by default, all others are
16676 public. */
16677 default_access = (TREE_CODE (ref) == RECORD_TYPE
16678 && CLASSTYPE_DECLARED_CLASS (ref)
16679 ? access_private_node : access_public_node);
16681 /* First, make sure that any templates in base-classes are
16682 instantiated. This ensures that if we call ourselves recursively
16683 we do not get confused about which classes are marked and which
16684 are not. */
16685 basep = &base_list;
16686 while (*basep)
16688 tree basetype = TREE_VALUE (*basep);
16690 /* The dependent_type_p call below should really be dependent_scope_p
16691 so that we give a hard error about using an incomplete type as a
16692 base, but we allow it with a pedwarn for backward
16693 compatibility. */
16694 if (processing_template_decl
16695 && CLASS_TYPE_P (basetype) && TYPE_BEING_DEFINED (basetype))
16696 cxx_incomplete_type_diagnostic (NULL_TREE, basetype, DK_PEDWARN);
16697 if (!dependent_type_p (basetype)
16698 && !complete_type_or_else (basetype, NULL))
16699 /* An incomplete type. Remove it from the list. */
16700 *basep = TREE_CHAIN (*basep);
16701 else
16703 max_bases++;
16704 if (TREE_TYPE (*basep))
16705 max_dvbases++;
16706 if (CLASS_TYPE_P (basetype))
16707 max_vbases += vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
16708 basep = &TREE_CHAIN (*basep);
16711 max_vbases += max_dvbases;
16713 TYPE_MARKED_P (ref) = 1;
16715 /* The binfo slot should be empty, unless this is an (ill-formed)
16716 redefinition. */
16717 gcc_assert (!TYPE_BINFO (ref) || TYPE_SIZE (ref));
16719 gcc_assert (TYPE_MAIN_VARIANT (ref) == ref);
16721 binfo = make_tree_binfo (max_bases);
16723 TYPE_BINFO (ref) = binfo;
16724 BINFO_OFFSET (binfo) = size_zero_node;
16725 BINFO_TYPE (binfo) = ref;
16727 /* Apply base-class info set up to the variants of this type. */
16728 fixup_type_variants (ref);
16730 if (max_bases)
16732 vec_alloc (BINFO_BASE_ACCESSES (binfo), max_bases);
16733 /* A C++98 POD cannot have base classes. */
16734 CLASSTYPE_NON_LAYOUT_POD_P (ref) = true;
16736 if (TREE_CODE (ref) == UNION_TYPE)
16738 error ("derived union %qT invalid", ref);
16739 return;
16743 if (max_bases > 1)
16744 warning (OPT_Wmultiple_inheritance,
16745 "%qT defined with multiple direct bases", ref);
16747 if (max_vbases)
16749 /* An aggregate can't have virtual base classes. */
16750 CLASSTYPE_NON_AGGREGATE (ref) = true;
16752 vec_alloc (CLASSTYPE_VBASECLASSES (ref), max_vbases);
16754 if (max_dvbases)
16755 warning (OPT_Wvirtual_inheritance,
16756 "%qT defined with direct virtual base", ref);
16759 for (igo_prev = binfo; base_list; base_list = TREE_CHAIN (base_list))
16761 tree access = TREE_PURPOSE (base_list);
16762 int via_virtual = TREE_TYPE (base_list) != NULL_TREE;
16763 tree basetype = TREE_VALUE (base_list);
16765 if (access == access_default_node)
16766 access = default_access;
16768 /* Before C++17, an aggregate cannot have base classes. In C++17, an
16769 aggregate can't have virtual, private, or protected base classes. */
16770 if (cxx_dialect < cxx17
16771 || access != access_public_node
16772 || via_virtual)
16773 CLASSTYPE_NON_AGGREGATE (ref) = true;
16775 if (PACK_EXPANSION_P (basetype))
16776 basetype = PACK_EXPANSION_PATTERN (basetype);
16777 if (TREE_CODE (basetype) == TYPE_DECL)
16778 basetype = TREE_TYPE (basetype);
16779 if (!MAYBE_CLASS_TYPE_P (basetype) || TREE_CODE (basetype) == UNION_TYPE)
16781 error ("base type %qT fails to be a struct or class type",
16782 basetype);
16783 goto dropped_base;
16786 base_binfo = NULL_TREE;
16787 if (CLASS_TYPE_P (basetype) && !dependent_scope_p (basetype))
16789 base_binfo = TYPE_BINFO (basetype);
16790 /* The original basetype could have been a typedef'd type. */
16791 basetype = BINFO_TYPE (base_binfo);
16793 /* Inherit flags from the base. */
16794 TYPE_HAS_NEW_OPERATOR (ref)
16795 |= TYPE_HAS_NEW_OPERATOR (basetype);
16796 TYPE_HAS_ARRAY_NEW_OPERATOR (ref)
16797 |= TYPE_HAS_ARRAY_NEW_OPERATOR (basetype);
16798 TYPE_GETS_DELETE (ref) |= TYPE_GETS_DELETE (basetype);
16799 TYPE_HAS_CONVERSION (ref) |= TYPE_HAS_CONVERSION (basetype);
16800 CLASSTYPE_DIAMOND_SHAPED_P (ref)
16801 |= CLASSTYPE_DIAMOND_SHAPED_P (basetype);
16802 CLASSTYPE_REPEATED_BASE_P (ref)
16803 |= CLASSTYPE_REPEATED_BASE_P (basetype);
16806 /* We must do this test after we've seen through a typedef
16807 type. */
16808 if (TYPE_MARKED_P (basetype))
16810 if (basetype == ref)
16811 error ("recursive type %qT undefined", basetype);
16812 else
16813 error ("duplicate base type %qT invalid", basetype);
16814 goto dropped_base;
16817 if (PACK_EXPANSION_P (TREE_VALUE (base_list)))
16818 /* Regenerate the pack expansion for the bases. */
16819 basetype = make_pack_expansion (basetype);
16821 TYPE_MARKED_P (basetype) = 1;
16823 base_binfo = copy_binfo (base_binfo, basetype, ref,
16824 &igo_prev, via_virtual);
16825 if (!BINFO_INHERITANCE_CHAIN (base_binfo))
16826 BINFO_INHERITANCE_CHAIN (base_binfo) = binfo;
16828 BINFO_BASE_APPEND (binfo, base_binfo);
16829 BINFO_BASE_ACCESS_APPEND (binfo, access);
16830 continue;
16832 dropped_base:
16833 /* Update max_vbases to reflect the reality that we are dropping
16834 this base: if it reaches zero we want to undo the vec_alloc
16835 above to avoid inconsistencies during error-recovery: eg, in
16836 build_special_member_call, CLASSTYPE_VBASECLASSES non null
16837 and vtt null (c++/27952). */
16838 if (via_virtual)
16839 max_vbases--;
16840 if (CLASS_TYPE_P (basetype))
16841 max_vbases
16842 -= vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
16845 if (CLASSTYPE_VBASECLASSES (ref)
16846 && max_vbases == 0)
16847 vec_free (CLASSTYPE_VBASECLASSES (ref));
16849 if (vec_safe_length (CLASSTYPE_VBASECLASSES (ref)) < max_vbases)
16850 /* If we didn't get max_vbases vbases, we must have shared at
16851 least one of them, and are therefore diamond shaped. */
16852 CLASSTYPE_DIAMOND_SHAPED_P (ref) = 1;
16854 /* Unmark all the types. */
16855 for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
16856 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
16857 TYPE_MARKED_P (ref) = 0;
16859 /* Now see if we have a repeated base type. */
16860 if (!CLASSTYPE_REPEATED_BASE_P (ref))
16862 for (base_binfo = binfo; base_binfo;
16863 base_binfo = TREE_CHAIN (base_binfo))
16865 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
16867 CLASSTYPE_REPEATED_BASE_P (ref) = 1;
16868 break;
16870 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 1;
16872 for (base_binfo = binfo; base_binfo;
16873 base_binfo = TREE_CHAIN (base_binfo))
16874 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
16875 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
16876 else
16877 break;
16882 /* Copies the enum-related properties from type SRC to type DST.
16883 Used with the underlying type of an enum and the enum itself. */
16884 static void
16885 copy_type_enum (tree dst, tree src)
16887 tree t;
16888 for (t = dst; t; t = TYPE_NEXT_VARIANT (t))
16890 TYPE_MIN_VALUE (t) = TYPE_MIN_VALUE (src);
16891 TYPE_MAX_VALUE (t) = TYPE_MAX_VALUE (src);
16892 TYPE_SIZE (t) = TYPE_SIZE (src);
16893 TYPE_SIZE_UNIT (t) = TYPE_SIZE_UNIT (src);
16894 SET_TYPE_MODE (dst, TYPE_MODE (src));
16895 TYPE_PRECISION (t) = TYPE_PRECISION (src);
16896 unsigned valign = TYPE_ALIGN (src);
16897 if (TYPE_USER_ALIGN (t))
16898 valign = MAX (valign, TYPE_ALIGN (t));
16899 else
16900 TYPE_USER_ALIGN (t) = TYPE_USER_ALIGN (src);
16901 SET_TYPE_ALIGN (t, valign);
16902 TYPE_UNSIGNED (t) = TYPE_UNSIGNED (src);
16906 /* Begin compiling the definition of an enumeration type.
16907 NAME is its name,
16909 if ENUMTYPE is not NULL_TREE then the type has alredy been found.
16911 UNDERLYING_TYPE is the type that will be used as the storage for
16912 the enumeration type. This should be NULL_TREE if no storage type
16913 was specified.
16915 ATTRIBUTES are any attributes specified after the enum-key.
16917 SCOPED_ENUM_P is true if this is a scoped enumeration type.
16919 if IS_NEW is not NULL, gets TRUE iff a new type is created.
16921 Returns the type object, as yet incomplete.
16922 Also records info about it so that build_enumerator
16923 may be used to declare the individual values as they are read. */
16925 tree
16926 start_enum (tree name, tree enumtype, tree underlying_type,
16927 tree attributes, bool scoped_enum_p, bool *is_new)
16929 tree prevtype = NULL_TREE;
16930 gcc_assert (identifier_p (name));
16932 if (is_new)
16933 *is_new = false;
16934 /* [C++0x dcl.enum]p5:
16936 If not explicitly specified, the underlying type of a scoped
16937 enumeration type is int. */
16938 if (!underlying_type && scoped_enum_p)
16939 underlying_type = integer_type_node;
16941 if (underlying_type)
16942 underlying_type = cv_unqualified (underlying_type);
16944 /* If this is the real definition for a previous forward reference,
16945 fill in the contents in the same object that used to be the
16946 forward reference. */
16947 if (!enumtype)
16948 enumtype = lookup_and_check_tag (enum_type, name,
16949 /*tag_scope=*/TAG_how::CURRENT_ONLY,
16950 /*template_header_p=*/false);
16952 /* In case of a template_decl, the only check that should be deferred
16953 to instantiation time is the comparison of underlying types. */
16954 if (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE)
16956 if (scoped_enum_p != SCOPED_ENUM_P (enumtype))
16958 error_at (input_location, "scoped/unscoped mismatch "
16959 "in enum %q#T", enumtype);
16960 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16961 "previous definition here");
16962 enumtype = error_mark_node;
16964 else if (ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) != !! underlying_type)
16966 error_at (input_location, "underlying type mismatch "
16967 "in enum %q#T", enumtype);
16968 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16969 "previous definition here");
16970 enumtype = error_mark_node;
16972 else if (underlying_type && ENUM_UNDERLYING_TYPE (enumtype)
16973 && !same_type_p (underlying_type,
16974 ENUM_UNDERLYING_TYPE (enumtype)))
16976 error_at (input_location, "different underlying type "
16977 "in enum %q#T", enumtype);
16978 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16979 "previous definition here");
16980 underlying_type = NULL_TREE;
16983 if (modules_p ())
16985 if (!module_may_redeclare (TYPE_NAME (enumtype)))
16987 error ("cannot define %qD in different module",
16988 TYPE_NAME (enumtype));
16989 inform (DECL_SOURCE_LOCATION (TYPE_NAME (enumtype)),
16990 "declared here");
16991 enumtype = error_mark_node;
16993 set_instantiating_module (TYPE_NAME (enumtype));
16997 if (!enumtype || TREE_CODE (enumtype) != ENUMERAL_TYPE
16998 || processing_template_decl)
17000 /* In case of error, make a dummy enum to allow parsing to
17001 continue. */
17002 if (enumtype == error_mark_node)
17004 name = make_anon_name ();
17005 enumtype = NULL_TREE;
17008 /* enumtype may be an ENUMERAL_TYPE if this is a redefinition
17009 of an opaque enum, or an opaque enum of an already defined
17010 enumeration (C++11).
17011 In any other case, it'll be NULL_TREE. */
17012 if (!enumtype)
17014 if (is_new)
17015 *is_new = true;
17017 prevtype = enumtype;
17019 /* Do not push the decl more than once. */
17020 if (!enumtype
17021 || TREE_CODE (enumtype) != ENUMERAL_TYPE)
17023 enumtype = cxx_make_type (ENUMERAL_TYPE);
17024 enumtype = pushtag (name, enumtype);
17026 /* std::byte aliases anything. */
17027 if (enumtype != error_mark_node
17028 && TYPE_CONTEXT (enumtype) == std_node
17029 && !strcmp ("byte", TYPE_NAME_STRING (enumtype)))
17030 TYPE_ALIAS_SET (enumtype) = 0;
17032 else
17033 enumtype = xref_tag (enum_type, name);
17035 if (enumtype == error_mark_node)
17036 return error_mark_node;
17038 /* The enum is considered opaque until the opening '{' of the
17039 enumerator list. */
17040 SET_OPAQUE_ENUM_P (enumtype, true);
17041 ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) = !! underlying_type;
17044 SET_SCOPED_ENUM_P (enumtype, scoped_enum_p);
17046 cplus_decl_attributes (&enumtype, attributes, (int)ATTR_FLAG_TYPE_IN_PLACE);
17048 if (underlying_type)
17050 if (ENUM_UNDERLYING_TYPE (enumtype))
17051 /* We already checked that it matches, don't change it to a different
17052 typedef variant. */;
17053 else if (CP_INTEGRAL_TYPE_P (underlying_type))
17055 copy_type_enum (enumtype, underlying_type);
17056 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
17058 else if (dependent_type_p (underlying_type))
17059 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
17060 else
17062 error ("underlying type %qT of %qT must be an integral type",
17063 underlying_type, enumtype);
17064 ENUM_UNDERLYING_TYPE (enumtype) = integer_type_node;
17068 /* If into a template class, the returned enum is always the first
17069 declaration (opaque or not) seen. This way all the references to
17070 this type will be to the same declaration. The following ones are used
17071 only to check for definition errors. */
17072 if (prevtype && processing_template_decl)
17073 return prevtype;
17074 else
17075 return enumtype;
17078 /* After processing and defining all the values of an enumeration type,
17079 install their decls in the enumeration type.
17080 ENUMTYPE is the type object. */
17082 void
17083 finish_enum_value_list (tree enumtype)
17085 tree values;
17086 tree underlying_type;
17087 tree decl;
17088 tree value;
17089 tree minnode, maxnode;
17090 tree t;
17092 bool fixed_underlying_type_p
17093 = ENUM_UNDERLYING_TYPE (enumtype) != NULL_TREE;
17095 /* We built up the VALUES in reverse order. */
17096 TYPE_VALUES (enumtype) = nreverse (TYPE_VALUES (enumtype));
17098 /* For an enum defined in a template, just set the type of the values;
17099 all further processing is postponed until the template is
17100 instantiated. We need to set the type so that tsubst of a CONST_DECL
17101 works. */
17102 if (processing_template_decl)
17104 for (values = TYPE_VALUES (enumtype);
17105 values;
17106 values = TREE_CHAIN (values))
17107 TREE_TYPE (TREE_VALUE (values)) = enumtype;
17108 return;
17111 /* Determine the minimum and maximum values of the enumerators. */
17112 if (TYPE_VALUES (enumtype))
17114 minnode = maxnode = NULL_TREE;
17116 for (values = TYPE_VALUES (enumtype);
17117 values;
17118 values = TREE_CHAIN (values))
17120 decl = TREE_VALUE (values);
17122 /* [dcl.enum]: Following the closing brace of an enum-specifier,
17123 each enumerator has the type of its enumeration. Prior to the
17124 closing brace, the type of each enumerator is the type of its
17125 initializing value. */
17126 TREE_TYPE (decl) = enumtype;
17128 /* Update the minimum and maximum values, if appropriate. */
17129 value = DECL_INITIAL (decl);
17130 if (TREE_CODE (value) != INTEGER_CST)
17131 value = integer_zero_node;
17132 /* Figure out what the minimum and maximum values of the
17133 enumerators are. */
17134 if (!minnode)
17135 minnode = maxnode = value;
17136 else if (tree_int_cst_lt (maxnode, value))
17137 maxnode = value;
17138 else if (tree_int_cst_lt (value, minnode))
17139 minnode = value;
17142 else
17143 /* [dcl.enum]
17145 If the enumerator-list is empty, the underlying type is as if
17146 the enumeration had a single enumerator with value 0. */
17147 minnode = maxnode = integer_zero_node;
17149 if (!fixed_underlying_type_p)
17151 /* Compute the number of bits require to represent all values of the
17152 enumeration. We must do this before the type of MINNODE and
17153 MAXNODE are transformed, since tree_int_cst_min_precision relies
17154 on the TREE_TYPE of the value it is passed. */
17155 signop sgn = tree_int_cst_sgn (minnode) >= 0 ? UNSIGNED : SIGNED;
17156 int lowprec = tree_int_cst_min_precision (minnode, sgn);
17157 int highprec = tree_int_cst_min_precision (maxnode, sgn);
17158 int precision = MAX (lowprec, highprec);
17159 unsigned int itk;
17160 bool use_short_enum;
17162 /* Determine the underlying type of the enumeration.
17164 [dcl.enum]
17166 The underlying type of an enumeration is an integral type that
17167 can represent all the enumerator values defined in the
17168 enumeration. It is implementation-defined which integral type is
17169 used as the underlying type for an enumeration except that the
17170 underlying type shall not be larger than int unless the value of
17171 an enumerator cannot fit in an int or unsigned int.
17173 We use "int" or an "unsigned int" as the underlying type, even if
17174 a smaller integral type would work, unless the user has
17175 explicitly requested that we use the smallest possible type. The
17176 user can request that for all enumerations with a command line
17177 flag, or for just one enumeration with an attribute. */
17179 use_short_enum = flag_short_enums
17180 || lookup_attribute ("packed", TYPE_ATTRIBUTES (enumtype));
17182 /* If the precision of the type was specified with an attribute and it
17183 was too small, give an error. Otherwise, use it. */
17184 if (TYPE_PRECISION (enumtype))
17186 if (precision > TYPE_PRECISION (enumtype))
17187 error ("specified mode too small for enumerated values");
17188 else
17190 use_short_enum = true;
17191 precision = TYPE_PRECISION (enumtype);
17195 for (itk = (use_short_enum ? itk_char : itk_int);
17196 itk != itk_none;
17197 itk++)
17199 underlying_type = integer_types[itk];
17200 if (underlying_type != NULL_TREE
17201 && TYPE_PRECISION (underlying_type) >= precision
17202 && TYPE_SIGN (underlying_type) == sgn)
17203 break;
17205 if (itk == itk_none)
17207 /* DR 377
17209 IF no integral type can represent all the enumerator values, the
17210 enumeration is ill-formed. */
17211 error ("no integral type can represent all of the enumerator values "
17212 "for %qT", enumtype);
17213 precision = TYPE_PRECISION (long_long_integer_type_node);
17214 underlying_type = integer_types[itk_unsigned_long_long];
17217 /* [dcl.enum]
17219 The value of sizeof() applied to an enumeration type, an object
17220 of an enumeration type, or an enumerator, is the value of sizeof()
17221 applied to the underlying type. */
17222 copy_type_enum (enumtype, underlying_type);
17224 /* Compute the minimum and maximum values for the type.
17226 [dcl.enum]
17228 For an enumeration where emin is the smallest enumerator and emax
17229 is the largest, the values of the enumeration are the values of the
17230 underlying type in the range bmin to bmax, where bmin and bmax are,
17231 respectively, the smallest and largest values of the smallest bit-
17232 field that can store emin and emax. */
17234 /* The middle-end currently assumes that types with TYPE_PRECISION
17235 narrower than their underlying type are suitably zero or sign
17236 extended to fill their mode. Similarly, it assumes that the front
17237 end assures that a value of a particular type must be within
17238 TYPE_MIN_VALUE and TYPE_MAX_VALUE.
17240 We used to set these fields based on bmin and bmax, but that led
17241 to invalid assumptions like optimizing away bounds checking. So
17242 now we just set the TYPE_PRECISION, TYPE_MIN_VALUE, and
17243 TYPE_MAX_VALUE to the values for the mode above and only restrict
17244 the ENUM_UNDERLYING_TYPE for the benefit of diagnostics. */
17245 ENUM_UNDERLYING_TYPE (enumtype)
17246 = build_distinct_type_copy (underlying_type);
17247 TYPE_PRECISION (ENUM_UNDERLYING_TYPE (enumtype)) = precision;
17248 set_min_and_max_values_for_integral_type
17249 (ENUM_UNDERLYING_TYPE (enumtype), precision, sgn);
17251 /* If -fstrict-enums, still constrain TYPE_MIN/MAX_VALUE. */
17252 if (flag_strict_enums)
17253 set_min_and_max_values_for_integral_type (enumtype, precision, sgn);
17255 if (use_short_enum)
17257 TYPE_PACKED (enumtype) = use_short_enum;
17258 fixup_attribute_variants (enumtype);
17261 else
17262 underlying_type = ENUM_UNDERLYING_TYPE (enumtype);
17264 /* If the enum is exported, mark the consts too. */
17265 bool export_p = (UNSCOPED_ENUM_P (enumtype)
17266 && DECL_MODULE_EXPORT_P (TYPE_STUB_DECL (enumtype))
17267 && at_namespace_scope_p ());
17269 /* Convert each of the enumerators to the type of the underlying
17270 type of the enumeration. */
17271 for (values = TYPE_VALUES (enumtype); values; values = TREE_CHAIN (values))
17273 decl = TREE_VALUE (values);
17274 iloc_sentinel ils (DECL_SOURCE_LOCATION (decl));
17275 if (fixed_underlying_type_p)
17276 /* If the enumeration type has a fixed underlying type, we
17277 already checked all of the enumerator values. */
17278 value = DECL_INITIAL (decl);
17279 else
17280 value = perform_implicit_conversion (underlying_type,
17281 DECL_INITIAL (decl),
17282 tf_warning_or_error);
17283 /* Do not clobber shared ints. */
17284 if (value != error_mark_node)
17286 value = copy_node (value);
17288 TREE_TYPE (value) = enumtype;
17290 DECL_INITIAL (decl) = value;
17291 if (export_p)
17292 DECL_MODULE_EXPORT_P (decl) = true;
17295 /* Fix up all variant types of this enum type. */
17296 for (t = TYPE_MAIN_VARIANT (enumtype); t; t = TYPE_NEXT_VARIANT (t))
17297 TYPE_VALUES (t) = TYPE_VALUES (enumtype);
17299 if (at_class_scope_p ()
17300 && COMPLETE_TYPE_P (current_class_type)
17301 && UNSCOPED_ENUM_P (enumtype))
17303 insert_late_enum_def_bindings (current_class_type, enumtype);
17304 /* TYPE_FIELDS needs fixup. */
17305 fixup_type_variants (current_class_type);
17308 /* Finish debugging output for this type. */
17309 rest_of_type_compilation (enumtype, namespace_bindings_p ());
17311 /* Each enumerator now has the type of its enumeration. Clear the cache
17312 so that this change in types doesn't confuse us later on. */
17313 clear_cv_and_fold_caches ();
17316 /* Finishes the enum type. This is called only the first time an
17317 enumeration is seen, be it opaque or odinary.
17318 ENUMTYPE is the type object. */
17320 void
17321 finish_enum (tree enumtype)
17323 if (processing_template_decl)
17325 if (at_function_scope_p ())
17326 add_stmt (build_min (TAG_DEFN, enumtype));
17327 return;
17330 /* If this is a forward declaration, there should not be any variants,
17331 though we can get a variant in the middle of an enum-specifier with
17332 wacky code like 'enum E { e = sizeof(const E*) };' */
17333 gcc_assert (enumtype == TYPE_MAIN_VARIANT (enumtype)
17334 && (TYPE_VALUES (enumtype)
17335 || !TYPE_NEXT_VARIANT (enumtype)));
17338 /* Build and install a CONST_DECL for an enumeration constant of the
17339 enumeration type ENUMTYPE whose NAME and VALUE (if any) are provided.
17340 Apply ATTRIBUTES if available. LOC is the location of NAME.
17341 Assignment of sequential values by default is handled here. */
17343 tree
17344 build_enumerator (tree name, tree value, tree enumtype, tree attributes,
17345 location_t loc)
17347 tree decl;
17348 tree context;
17349 tree type;
17351 /* scalar_constant_value will pull out this expression, so make sure
17352 it's folded as appropriate. */
17353 if (processing_template_decl)
17354 value = fold_non_dependent_expr (value);
17356 /* If the VALUE was erroneous, pretend it wasn't there; that will
17357 result in the enum being assigned the next value in sequence. */
17358 if (value == error_mark_node)
17359 value = NULL_TREE;
17361 /* Remove no-op casts from the value. */
17362 if (value)
17363 STRIP_TYPE_NOPS (value);
17365 if (! processing_template_decl)
17367 /* Validate and default VALUE. */
17368 if (value != NULL_TREE)
17370 if (!ENUM_UNDERLYING_TYPE (enumtype))
17372 tree tmp_value = build_expr_type_conversion (WANT_INT | WANT_ENUM,
17373 value, true);
17374 if (tmp_value)
17375 value = tmp_value;
17377 else if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
17378 (TREE_TYPE (value)))
17379 value = perform_implicit_conversion_flags
17380 (ENUM_UNDERLYING_TYPE (enumtype), value, tf_warning_or_error,
17381 LOOKUP_IMPLICIT | LOOKUP_NO_NARROWING);
17383 if (value == error_mark_node)
17384 value = NULL_TREE;
17386 if (value != NULL_TREE)
17388 if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
17389 (TREE_TYPE (value)))
17391 error_at (cp_expr_loc_or_input_loc (value),
17392 "enumerator value for %qD must have integral or "
17393 "unscoped enumeration type", name);
17394 value = NULL_TREE;
17396 else
17398 value = cxx_constant_value (value);
17400 if (TREE_CODE (value) != INTEGER_CST)
17402 error ("enumerator value for %qD is not an integer "
17403 "constant", name);
17404 value = NULL_TREE;
17410 /* Default based on previous value. */
17411 if (value == NULL_TREE)
17413 if (TYPE_VALUES (enumtype))
17415 tree prev_value;
17417 /* C++03 7.2/4: If no initializer is specified for the first
17418 enumerator, the type is an unspecified integral
17419 type. Otherwise the type is the same as the type of the
17420 initializing value of the preceding enumerator unless the
17421 incremented value is not representable in that type, in
17422 which case the type is an unspecified integral type
17423 sufficient to contain the incremented value. */
17424 prev_value = DECL_INITIAL (TREE_VALUE (TYPE_VALUES (enumtype)));
17425 if (TREE_CODE (prev_value) != INTEGER_CST)
17426 value = error_mark_node;
17427 else
17429 wi::overflow_type overflowed;
17430 tree type = TREE_TYPE (prev_value);
17431 signop sgn = TYPE_SIGN (type);
17432 widest_int wi = wi::add (wi::to_widest (prev_value), 1, sgn,
17433 &overflowed);
17434 if (!overflowed)
17436 bool pos = !wi::neg_p (wi, sgn);
17437 if (!wi::fits_to_tree_p (wi, type))
17439 unsigned int itk;
17440 for (itk = itk_int; itk != itk_none; itk++)
17442 type = integer_types[itk];
17443 if (type != NULL_TREE
17444 && (pos || !TYPE_UNSIGNED (type))
17445 && wi::fits_to_tree_p (wi, type))
17446 break;
17448 if (type && cxx_dialect < cxx11
17449 && itk > itk_unsigned_long)
17450 pedwarn (input_location, OPT_Wlong_long,
17451 pos ? G_("\
17452 incremented enumerator value is too large for %<unsigned long%>") : G_("\
17453 incremented enumerator value is too large for %<long%>"));
17455 if (type == NULL_TREE)
17456 overflowed = wi::OVF_UNKNOWN;
17457 else
17458 value = wide_int_to_tree (type, wi);
17461 if (overflowed)
17463 error ("overflow in enumeration values at %qD", name);
17464 value = error_mark_node;
17468 else
17469 value = integer_zero_node;
17472 /* Remove no-op casts from the value. */
17473 STRIP_TYPE_NOPS (value);
17475 /* If the underlying type of the enum is fixed, check whether
17476 the enumerator values fits in the underlying type. If it
17477 does not fit, the program is ill-formed [C++0x dcl.enum]. */
17478 if (ENUM_UNDERLYING_TYPE (enumtype)
17479 && value
17480 && TREE_CODE (value) == INTEGER_CST)
17482 if (!int_fits_type_p (value, ENUM_UNDERLYING_TYPE (enumtype)))
17483 error ("enumerator value %qE is outside the range of underlying "
17484 "type %qT", value, ENUM_UNDERLYING_TYPE (enumtype));
17486 /* Convert the value to the appropriate type. */
17487 value = fold_convert (ENUM_UNDERLYING_TYPE (enumtype), value);
17491 /* C++ associates enums with global, function, or class declarations. */
17492 context = current_scope ();
17494 /* Build the actual enumeration constant. Note that the enumeration
17495 constants have the underlying type of the enum (if it is fixed)
17496 or the type of their initializer (if the underlying type of the
17497 enum is not fixed):
17499 [ C++0x dcl.enum ]
17501 If the underlying type is fixed, the type of each enumerator
17502 prior to the closing brace is the underlying type; if the
17503 initializing value of an enumerator cannot be represented by
17504 the underlying type, the program is ill-formed. If the
17505 underlying type is not fixed, the type of each enumerator is
17506 the type of its initializing value.
17508 If the underlying type is not fixed, it will be computed by
17509 finish_enum and we will reset the type of this enumerator. Of
17510 course, if we're processing a template, there may be no value. */
17511 type = value ? TREE_TYPE (value) : NULL_TREE;
17513 decl = build_decl (loc, CONST_DECL, name, type);
17515 DECL_CONTEXT (decl) = enumtype;
17516 TREE_CONSTANT (decl) = 1;
17517 TREE_READONLY (decl) = 1;
17518 DECL_INITIAL (decl) = value;
17520 if (attributes)
17521 cplus_decl_attributes (&decl, attributes, 0);
17523 if (context && context == current_class_type && !SCOPED_ENUM_P (enumtype))
17525 /* In something like `struct S { enum E { i = 7 }; };' we put `i'
17526 on the TYPE_FIELDS list for `S'. (That's so that you can say
17527 things like `S::i' later.) */
17529 /* The enumerator may be getting declared outside of its enclosing
17530 class, like so:
17532 class S { public: enum E : int; }; enum S::E : int { i = 7; };
17534 For which case we need to make sure that the access of `S::i'
17535 matches the access of `S::E'. */
17536 auto cas = make_temp_override (current_access_specifier);
17537 set_current_access_from_decl (TYPE_NAME (enumtype));
17538 finish_member_declaration (decl);
17540 else
17541 pushdecl (decl);
17543 /* Add this enumeration constant to the list for this type. */
17544 TYPE_VALUES (enumtype) = tree_cons (name, decl, TYPE_VALUES (enumtype));
17546 return decl;
17549 /* Look for an enumerator with the given NAME within the enumeration
17550 type ENUMTYPE. This routine is used primarily for qualified name
17551 lookup into an enumerator in C++0x, e.g.,
17553 enum class Color { Red, Green, Blue };
17555 Color color = Color::Red;
17557 Returns the value corresponding to the enumerator, or
17558 NULL_TREE if no such enumerator was found. */
17559 tree
17560 lookup_enumerator (tree enumtype, tree name)
17562 tree e;
17563 gcc_assert (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE);
17565 e = purpose_member (name, TYPE_VALUES (enumtype));
17566 return e? TREE_VALUE (e) : NULL_TREE;
17569 /* Implement LANG_HOOKS_SIMULATE_ENUM_DECL. */
17571 tree
17572 cxx_simulate_enum_decl (location_t loc, const char *name,
17573 vec<string_int_pair> *values)
17575 location_t saved_loc = input_location;
17576 input_location = loc;
17578 tree enumtype = start_enum (get_identifier (name), NULL_TREE, NULL_TREE,
17579 NULL_TREE, false, NULL);
17580 if (!OPAQUE_ENUM_P (enumtype))
17582 error_at (loc, "multiple definition of %q#T", enumtype);
17583 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
17584 "previous definition here");
17585 return enumtype;
17587 SET_OPAQUE_ENUM_P (enumtype, false);
17588 DECL_SOURCE_LOCATION (TYPE_NAME (enumtype)) = loc;
17590 for (const string_int_pair &value : values)
17591 build_enumerator (get_identifier (value.first),
17592 build_int_cst (integer_type_node, value.second),
17593 enumtype, NULL_TREE, loc);
17595 finish_enum_value_list (enumtype);
17596 finish_enum (enumtype);
17598 input_location = saved_loc;
17599 return enumtype;
17602 /* Implement LANG_HOOKS_SIMULATE_RECORD_DECL. */
17604 tree
17605 cxx_simulate_record_decl (location_t loc, const char *name,
17606 array_slice<const tree> fields)
17608 iloc_sentinel ils (loc);
17610 tree ident = get_identifier (name);
17611 tree type = xref_tag (/*tag_code=*/record_type, ident);
17612 if (type != error_mark_node
17613 && (TREE_CODE (type) != RECORD_TYPE || COMPLETE_TYPE_P (type)))
17615 error ("redefinition of %q#T", type);
17616 type = error_mark_node;
17618 if (type == error_mark_node)
17619 return lhd_simulate_record_decl (loc, name, fields);
17621 xref_basetypes (type, NULL_TREE);
17622 type = begin_class_definition (type);
17623 if (type == error_mark_node)
17624 return lhd_simulate_record_decl (loc, name, fields);
17626 for (tree field : fields)
17627 finish_member_declaration (field);
17629 type = finish_struct (type, NULL_TREE);
17631 tree decl = build_decl (loc, TYPE_DECL, ident, type);
17632 set_underlying_type (decl);
17633 lang_hooks.decls.pushdecl (decl);
17635 return type;
17638 /* We're defining DECL. Make sure that its type is OK. */
17640 static void
17641 check_function_type (tree decl, tree current_function_parms)
17643 tree fntype = TREE_TYPE (decl);
17644 tree return_type = complete_type (TREE_TYPE (fntype));
17646 /* In a function definition, arg types must be complete. */
17647 require_complete_types_for_parms (current_function_parms);
17649 if (dependent_type_p (return_type)
17650 || type_uses_auto (return_type))
17651 return;
17652 if (!COMPLETE_OR_VOID_TYPE_P (return_type))
17654 tree args = TYPE_ARG_TYPES (fntype);
17656 error ("return type %q#T is incomplete", return_type);
17658 /* Make it return void instead. */
17659 if (TREE_CODE (fntype) == METHOD_TYPE)
17660 fntype = build_method_type_directly (TREE_TYPE (TREE_VALUE (args)),
17661 void_type_node,
17662 TREE_CHAIN (args));
17663 else
17664 fntype = build_function_type (void_type_node, args);
17665 fntype = (cp_build_type_attribute_variant
17666 (fntype, TYPE_ATTRIBUTES (TREE_TYPE (decl))));
17667 fntype = cxx_copy_lang_qualifiers (fntype, TREE_TYPE (decl));
17668 TREE_TYPE (decl) = fntype;
17670 else
17672 abstract_virtuals_error (decl, TREE_TYPE (fntype));
17673 maybe_warn_parm_abi (TREE_TYPE (fntype),
17674 DECL_SOURCE_LOCATION (decl));
17678 /* True iff FN is an implicitly-defined default constructor. */
17680 static bool
17681 implicit_default_ctor_p (tree fn)
17683 return (DECL_CONSTRUCTOR_P (fn)
17684 && !user_provided_p (fn)
17685 && sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (fn)));
17688 /* Clobber the contents of *this to let the back end know that the object
17689 storage is dead when we enter the constructor or leave the destructor. */
17691 static tree
17692 build_clobber_this (clobber_kind kind)
17694 /* Clobbering an empty base is pointless, and harmful if its one byte
17695 TYPE_SIZE overlays real data. */
17696 if (is_empty_class (current_class_type))
17697 return void_node;
17699 /* If we have virtual bases, clobber the whole object, but only if we're in
17700 charge. If we don't have virtual bases, clobber the as-base type so we
17701 don't mess with tail padding. */
17702 bool vbases = CLASSTYPE_VBASECLASSES (current_class_type);
17704 tree ctype = current_class_type;
17705 if (!vbases)
17706 ctype = CLASSTYPE_AS_BASE (ctype);
17708 tree clobber = build_clobber (ctype, kind);
17710 tree thisref = current_class_ref;
17711 if (ctype != current_class_type)
17713 thisref = build_nop (build_reference_type (ctype), current_class_ptr);
17714 thisref = convert_from_reference (thisref);
17717 tree exprstmt = build2 (MODIFY_EXPR, void_type_node, thisref, clobber);
17718 if (vbases)
17719 exprstmt = build_if_in_charge (exprstmt);
17721 return exprstmt;
17724 /* Create the FUNCTION_DECL for a function definition.
17725 DECLSPECS and DECLARATOR are the parts of the declaration;
17726 they describe the function's name and the type it returns,
17727 but twisted together in a fashion that parallels the syntax of C.
17729 FLAGS is a bitwise or of SF_PRE_PARSED (indicating that the
17730 DECLARATOR is really the DECL for the function we are about to
17731 process and that DECLSPECS should be ignored), SF_INCLASS_INLINE
17732 indicating that the function is an inline defined in-class.
17734 This function creates a binding context for the function body
17735 as well as setting up the FUNCTION_DECL in current_function_decl.
17737 For C++, we must first check whether that datum makes any sense.
17738 For example, "class A local_a(1,2);" means that variable local_a
17739 is an aggregate of type A, which should have a constructor
17740 applied to it with the argument list [1, 2].
17742 On entry, DECL_INITIAL (decl1) should be NULL_TREE or error_mark_node,
17743 or may be a BLOCK if the function has been defined previously
17744 in this translation unit. On exit, DECL_INITIAL (decl1) will be
17745 error_mark_node if the function has never been defined, or
17746 a BLOCK if the function has been defined somewhere. */
17748 bool
17749 start_preparsed_function (tree decl1, tree attrs, int flags)
17751 tree ctype = NULL_TREE;
17752 bool doing_friend = false;
17754 /* Sanity check. */
17755 gcc_assert (VOID_TYPE_P (TREE_VALUE (void_list_node)));
17756 gcc_assert (TREE_CHAIN (void_list_node) == NULL_TREE);
17758 tree fntype = TREE_TYPE (decl1);
17759 if (DECL_CLASS_SCOPE_P (decl1))
17760 ctype = DECL_CONTEXT (decl1);
17761 else
17763 ctype = DECL_FRIEND_CONTEXT (decl1);
17765 if (ctype)
17766 doing_friend = true;
17769 if (DECL_DECLARED_INLINE_P (decl1)
17770 && lookup_attribute ("noinline", attrs))
17771 warning_at (DECL_SOURCE_LOCATION (decl1), 0,
17772 "inline function %qD given attribute %qs", decl1, "noinline");
17774 /* Handle gnu_inline attribute. */
17775 if (GNU_INLINE_P (decl1))
17777 DECL_EXTERNAL (decl1) = 1;
17778 DECL_NOT_REALLY_EXTERN (decl1) = 0;
17779 DECL_INTERFACE_KNOWN (decl1) = 1;
17780 DECL_DISREGARD_INLINE_LIMITS (decl1) = 1;
17783 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl1))
17784 /* This is a constructor, we must ensure that any default args
17785 introduced by this definition are propagated to the clones
17786 now. The clones are used directly in overload resolution. */
17787 adjust_clone_args (decl1);
17789 /* Sometimes we don't notice that a function is a static member, and
17790 build a METHOD_TYPE for it. Fix that up now. */
17791 gcc_assert (!(DECL_STATIC_FUNCTION_P (decl1)
17792 && TREE_CODE (TREE_TYPE (decl1)) == METHOD_TYPE));
17794 /* Set up current_class_type, and enter the scope of the class, if
17795 appropriate. */
17796 if (ctype)
17797 push_nested_class (ctype);
17799 /* Now that we have entered the scope of the class, we must restore
17800 the bindings for any template parameters surrounding DECL1, if it
17801 is an inline member template. (Order is important; consider the
17802 case where a template parameter has the same name as a field of
17803 the class.) It is not until after this point that
17804 PROCESSING_TEMPLATE_DECL is guaranteed to be set up correctly. */
17805 if (flags & SF_INCLASS_INLINE)
17806 maybe_begin_member_template_processing (decl1);
17808 /* Effective C++ rule 15. */
17809 if (warn_ecpp
17810 && DECL_ASSIGNMENT_OPERATOR_P (decl1)
17811 && DECL_OVERLOADED_OPERATOR_IS (decl1, NOP_EXPR)
17812 && VOID_TYPE_P (TREE_TYPE (fntype)))
17813 warning (OPT_Weffc__,
17814 "%<operator=%> should return a reference to %<*this%>");
17816 /* Make the init_value nonzero so pushdecl knows this is not tentative.
17817 error_mark_node is replaced below (in poplevel) with the BLOCK. */
17818 if (!DECL_INITIAL (decl1))
17819 DECL_INITIAL (decl1) = error_mark_node;
17821 /* This function exists in static storage.
17822 (This does not mean `static' in the C sense!) */
17823 TREE_STATIC (decl1) = 1;
17825 /* We must call push_template_decl after current_class_type is set
17826 up. (If we are processing inline definitions after exiting a
17827 class scope, current_class_type will be NULL_TREE until set above
17828 by push_nested_class.) */
17829 if (processing_template_decl)
17831 tree newdecl1 = push_template_decl (decl1, doing_friend);
17832 if (newdecl1 == error_mark_node)
17834 if (ctype)
17835 pop_nested_class ();
17836 return false;
17838 decl1 = newdecl1;
17841 /* Make sure the parameter and return types are reasonable. When
17842 you declare a function, these types can be incomplete, but they
17843 must be complete when you define the function. */
17844 check_function_type (decl1, DECL_ARGUMENTS (decl1));
17846 /* Build the return declaration for the function. */
17847 tree restype = TREE_TYPE (fntype);
17849 if (DECL_RESULT (decl1) == NULL_TREE)
17851 /* In a template instantiation, copy the return type location. When
17852 parsing, the location will be set in grokdeclarator. */
17853 location_t loc = input_location;
17854 if (DECL_TEMPLATE_INSTANTIATION (decl1))
17856 tree tmpl = template_for_substitution (decl1);
17857 if (tree res = DECL_RESULT (DECL_TEMPLATE_RESULT (tmpl)))
17858 loc = DECL_SOURCE_LOCATION (res);
17861 tree resdecl = build_decl (loc, RESULT_DECL, 0, restype);
17862 DECL_ARTIFICIAL (resdecl) = 1;
17863 DECL_IGNORED_P (resdecl) = 1;
17864 DECL_RESULT (decl1) = resdecl;
17866 cp_apply_type_quals_to_decl (cp_type_quals (restype), resdecl);
17869 /* Record the decl so that the function name is defined.
17870 If we already have a decl for this name, and it is a FUNCTION_DECL,
17871 use the old decl. */
17872 if (!processing_template_decl && !(flags & SF_PRE_PARSED))
17874 /* A specialization is not used to guide overload resolution. */
17875 if (!DECL_FUNCTION_MEMBER_P (decl1)
17876 && !(DECL_USE_TEMPLATE (decl1) &&
17877 PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl1))))
17879 tree olddecl = pushdecl (decl1);
17881 if (olddecl == error_mark_node)
17882 /* If something went wrong when registering the declaration,
17883 use DECL1; we have to have a FUNCTION_DECL to use when
17884 parsing the body of the function. */
17886 else
17888 /* Otherwise, OLDDECL is either a previous declaration
17889 of the same function or DECL1 itself. */
17891 if (warn_missing_declarations
17892 && olddecl == decl1
17893 && !DECL_MAIN_P (decl1)
17894 && TREE_PUBLIC (decl1)
17895 && !DECL_DECLARED_INLINE_P (decl1))
17897 tree context;
17899 /* Check whether DECL1 is in an anonymous
17900 namespace. */
17901 for (context = DECL_CONTEXT (decl1);
17902 context;
17903 context = DECL_CONTEXT (context))
17905 if (TREE_CODE (context) == NAMESPACE_DECL
17906 && DECL_NAME (context) == NULL_TREE)
17907 break;
17910 if (context == NULL)
17911 warning_at (DECL_SOURCE_LOCATION (decl1),
17912 OPT_Wmissing_declarations,
17913 "no previous declaration for %qD", decl1);
17916 decl1 = olddecl;
17919 else
17921 /* We need to set the DECL_CONTEXT. */
17922 if (!DECL_CONTEXT (decl1) && DECL_TEMPLATE_INFO (decl1))
17923 DECL_CONTEXT (decl1) = DECL_CONTEXT (DECL_TI_TEMPLATE (decl1));
17925 fntype = TREE_TYPE (decl1);
17926 restype = TREE_TYPE (fntype);
17928 /* If #pragma weak applies, mark the decl appropriately now.
17929 The pragma only applies to global functions. Because
17930 determining whether or not the #pragma applies involves
17931 computing the mangled name for the declaration, we cannot
17932 apply the pragma until after we have merged this declaration
17933 with any previous declarations; if the original declaration
17934 has a linkage specification, that specification applies to
17935 the definition as well, and may affect the mangled name. */
17936 if (DECL_FILE_SCOPE_P (decl1))
17937 maybe_apply_pragma_weak (decl1);
17940 /* We are now in the scope of the function being defined. */
17941 current_function_decl = decl1;
17943 /* Save the parm names or decls from this function's declarator
17944 where store_parm_decls will find them. */
17945 tree current_function_parms = DECL_ARGUMENTS (decl1);
17947 /* Let the user know we're compiling this function. */
17948 announce_function (decl1);
17950 gcc_assert (DECL_INITIAL (decl1));
17952 /* This function may already have been parsed, in which case just
17953 return; our caller will skip over the body without parsing. */
17954 if (DECL_INITIAL (decl1) != error_mark_node)
17955 return true;
17957 /* Initialize RTL machinery. We cannot do this until
17958 CURRENT_FUNCTION_DECL and DECL_RESULT are set up. We do this
17959 even when processing a template; this is how we get
17960 CFUN set up, and our per-function variables initialized.
17961 FIXME factor out the non-RTL stuff. */
17962 cp_binding_level *bl = current_binding_level;
17963 allocate_struct_function (decl1, processing_template_decl);
17965 /* Initialize the language data structures. Whenever we start
17966 a new function, we destroy temporaries in the usual way. */
17967 cfun->language = ggc_cleared_alloc<language_function> ();
17968 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
17969 current_binding_level = bl;
17971 /* If we are (erroneously) defining a function that we have already
17972 defined before, wipe out what we knew before. */
17973 gcc_checking_assert (!DECL_PENDING_INLINE_P (decl1));
17974 FNDECL_USED_AUTO (decl1) = false;
17975 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = NULL;
17977 if (!processing_template_decl && type_uses_auto (restype))
17979 FNDECL_USED_AUTO (decl1) = true;
17980 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = restype;
17983 /* Start the statement-tree, start the tree now. */
17984 DECL_SAVED_TREE (decl1) = push_stmt_list ();
17986 if (DECL_IOBJ_MEMBER_FUNCTION_P (decl1))
17988 /* We know that this was set up by `grokclassfn'. We do not
17989 wait until `store_parm_decls', since evil parse errors may
17990 never get us to that point. Here we keep the consistency
17991 between `current_class_type' and `current_class_ptr'. */
17992 tree t = DECL_ARGUMENTS (decl1);
17994 gcc_assert (t != NULL_TREE && TREE_CODE (t) == PARM_DECL);
17995 gcc_assert (TYPE_PTR_P (TREE_TYPE (t)));
17997 cp_function_chain->x_current_class_ref
17998 = cp_build_fold_indirect_ref (t);
17999 /* Set this second to avoid shortcut in cp_build_indirect_ref. */
18000 cp_function_chain->x_current_class_ptr = t;
18002 /* Constructors and destructors need to know whether they're "in
18003 charge" of initializing virtual base classes. */
18004 t = DECL_CHAIN (t);
18005 if (DECL_HAS_IN_CHARGE_PARM_P (decl1))
18007 current_in_charge_parm = t;
18008 t = DECL_CHAIN (t);
18010 if (DECL_HAS_VTT_PARM_P (decl1))
18012 gcc_assert (DECL_NAME (t) == vtt_parm_identifier);
18013 current_vtt_parm = t;
18017 bool honor_interface = (!DECL_TEMPLATE_INSTANTIATION (decl1)
18018 /* Implicitly-defined methods (like the
18019 destructor for a class in which no destructor
18020 is explicitly declared) must not be defined
18021 until their definition is needed. So, we
18022 ignore interface specifications for
18023 compiler-generated functions. */
18024 && !DECL_ARTIFICIAL (decl1));
18025 struct c_fileinfo *finfo
18026 = get_fileinfo (LOCATION_FILE (DECL_SOURCE_LOCATION (decl1)));
18028 if (processing_template_decl)
18029 /* Don't mess with interface flags. */;
18030 else if (DECL_INTERFACE_KNOWN (decl1))
18032 tree ctx = decl_function_context (decl1);
18034 if (DECL_NOT_REALLY_EXTERN (decl1))
18035 DECL_EXTERNAL (decl1) = 0;
18037 if (ctx != NULL_TREE && vague_linkage_p (ctx))
18038 /* This is a function in a local class in an extern inline
18039 or template function. */
18040 comdat_linkage (decl1);
18042 /* If this function belongs to an interface, it is public.
18043 If it belongs to someone else's interface, it is also external.
18044 This only affects inlines and template instantiations. */
18045 else if (!finfo->interface_unknown && honor_interface)
18047 if (DECL_DECLARED_INLINE_P (decl1)
18048 || DECL_TEMPLATE_INSTANTIATION (decl1))
18050 DECL_EXTERNAL (decl1)
18051 = (finfo->interface_only
18052 || (DECL_DECLARED_INLINE_P (decl1)
18053 && ! flag_implement_inlines
18054 && !DECL_VINDEX (decl1)));
18056 /* For WIN32 we also want to put these in linkonce sections. */
18057 maybe_make_one_only (decl1);
18059 else
18060 DECL_EXTERNAL (decl1) = 0;
18061 DECL_INTERFACE_KNOWN (decl1) = 1;
18062 /* If this function is in an interface implemented in this file,
18063 make sure that the back end knows to emit this function
18064 here. */
18065 if (!DECL_EXTERNAL (decl1))
18066 mark_needed (decl1);
18068 else if (finfo->interface_unknown && finfo->interface_only
18069 && honor_interface)
18071 /* If MULTIPLE_SYMBOL_SPACES is defined and we saw a #pragma
18072 interface, we will have both finfo->interface_unknown and
18073 finfo->interface_only set. In that case, we don't want to
18074 use the normal heuristics because someone will supply a
18075 #pragma implementation elsewhere, and deducing it here would
18076 produce a conflict. */
18077 comdat_linkage (decl1);
18078 DECL_EXTERNAL (decl1) = 0;
18079 DECL_INTERFACE_KNOWN (decl1) = 1;
18080 DECL_DEFER_OUTPUT (decl1) = 1;
18082 else
18084 /* This is a definition, not a reference.
18085 So clear DECL_EXTERNAL, unless this is a GNU extern inline. */
18086 if (!GNU_INLINE_P (decl1))
18087 DECL_EXTERNAL (decl1) = 0;
18089 if ((DECL_DECLARED_INLINE_P (decl1)
18090 || DECL_TEMPLATE_INSTANTIATION (decl1))
18091 && ! DECL_INTERFACE_KNOWN (decl1))
18092 DECL_DEFER_OUTPUT (decl1) = 1;
18093 else
18094 DECL_INTERFACE_KNOWN (decl1) = 1;
18097 /* Determine the ELF visibility attribute for the function. We must not
18098 do this before calling "pushdecl", as we must allow "duplicate_decls"
18099 to merge any attributes appropriately. We also need to wait until
18100 linkage is set. */
18101 if (!DECL_CLONED_FUNCTION_P (decl1))
18102 determine_visibility (decl1);
18104 if (!processing_template_decl)
18105 maybe_instantiate_noexcept (decl1);
18107 begin_scope (sk_function_parms, decl1);
18109 ++function_depth;
18111 start_fname_decls ();
18113 store_parm_decls (current_function_parms);
18115 start_function_contracts (decl1);
18117 if (!processing_template_decl
18118 && (flag_lifetime_dse > 1)
18119 && DECL_CONSTRUCTOR_P (decl1)
18120 && !DECL_CLONED_FUNCTION_P (decl1)
18121 /* Clobbering an empty base is harmful if it overlays real data. */
18122 && !is_empty_class (current_class_type)
18123 /* We can't clobber safely for an implicitly-defined default constructor
18124 because part of the initialization might happen before we enter the
18125 constructor, via AGGR_INIT_ZERO_FIRST (c++/68006). */
18126 && !implicit_default_ctor_p (decl1))
18127 finish_expr_stmt (build_clobber_this (CLOBBER_OBJECT_BEGIN));
18129 if (!processing_template_decl
18130 && DECL_CONSTRUCTOR_P (decl1)
18131 && sanitize_flags_p (SANITIZE_VPTR)
18132 && !DECL_CLONED_FUNCTION_P (decl1)
18133 && !implicit_default_ctor_p (decl1))
18134 cp_ubsan_maybe_initialize_vtbl_ptrs (current_class_ptr);
18136 if (!DECL_OMP_DECLARE_REDUCTION_P (decl1))
18137 start_lambda_scope (decl1);
18139 return true;
18143 /* Like start_preparsed_function, except that instead of a
18144 FUNCTION_DECL, this function takes DECLSPECS and DECLARATOR.
18146 Returns true on success. If the DECLARATOR is not suitable
18147 for a function, we return false, which tells the parser to
18148 skip the entire function. */
18150 bool
18151 start_function (cp_decl_specifier_seq *declspecs,
18152 const cp_declarator *declarator,
18153 tree attrs)
18155 tree decl1;
18157 decl1 = grokdeclarator (declarator, declspecs, FUNCDEF, 1, &attrs);
18158 invoke_plugin_callbacks (PLUGIN_START_PARSE_FUNCTION, decl1);
18159 if (decl1 == error_mark_node)
18160 return false;
18162 if (DECL_MAIN_P (decl1))
18163 /* main must return int. grokfndecl should have corrected it
18164 (and issued a diagnostic) if the user got it wrong. */
18165 gcc_assert (same_type_p (TREE_TYPE (TREE_TYPE (decl1)),
18166 integer_type_node));
18168 return start_preparsed_function (decl1, attrs, /*flags=*/SF_DEFAULT);
18171 /* Returns true iff an EH_SPEC_BLOCK should be created in the body of
18172 FN. */
18174 static bool
18175 use_eh_spec_block (tree fn)
18177 return (flag_exceptions && flag_enforce_eh_specs
18178 && !processing_template_decl
18179 /* We insert the EH_SPEC_BLOCK only in the original
18180 function; then, it is copied automatically to the
18181 clones. */
18182 && !DECL_CLONED_FUNCTION_P (fn)
18183 /* Implicitly-generated constructors and destructors have
18184 exception specifications. However, those specifications
18185 are the union of the possible exceptions specified by the
18186 constructors/destructors for bases and members, so no
18187 unallowed exception will ever reach this function. By
18188 not creating the EH_SPEC_BLOCK we save a little memory,
18189 and we avoid spurious warnings about unreachable
18190 code. */
18191 && !DECL_DEFAULTED_FN (fn)
18192 && !type_throw_all_p (TREE_TYPE (fn)));
18195 /* Helper function to push ARGS into the current lexical scope. DECL
18196 is the function declaration. NONPARMS is used to handle enum
18197 constants. */
18199 void
18200 do_push_parm_decls (tree decl, tree args, tree *nonparms)
18202 /* If we're doing semantic analysis, then we'll call pushdecl
18203 for each of these. We must do them in reverse order so that
18204 they end in the correct forward order. */
18205 args = nreverse (args);
18207 tree next;
18208 for (tree parm = args; parm; parm = next)
18210 next = DECL_CHAIN (parm);
18211 if (TREE_CODE (parm) == PARM_DECL)
18212 pushdecl (parm);
18213 else if (nonparms)
18215 /* If we find an enum constant or a type tag, put it aside for
18216 the moment. */
18217 TREE_CHAIN (parm) = NULL_TREE;
18218 *nonparms = chainon (*nonparms, parm);
18222 /* Get the decls in their original chain order and record in the
18223 function. This is all and only the PARM_DECLs that were
18224 pushed into scope by the loop above. */
18225 DECL_ARGUMENTS (decl) = get_local_decls ();
18228 /* Store the parameter declarations into the current function declaration.
18229 This is called after parsing the parameter declarations, before
18230 digesting the body of the function.
18232 Also install to binding contour return value identifier, if any. */
18234 static void
18235 store_parm_decls (tree current_function_parms)
18237 tree fndecl = current_function_decl;
18239 /* This is a chain of any other decls that came in among the parm
18240 declarations. If a parm is declared with enum {foo, bar} x;
18241 then CONST_DECLs for foo and bar are put here. */
18242 tree nonparms = NULL_TREE;
18244 if (current_function_parms)
18246 /* This case is when the function was defined with an ANSI prototype.
18247 The parms already have decls, so we need not do anything here
18248 except record them as in effect
18249 and complain if any redundant old-style parm decls were written. */
18251 tree specparms = current_function_parms;
18253 /* Must clear this because it might contain TYPE_DECLs declared
18254 at class level. */
18255 current_binding_level->names = NULL;
18257 do_push_parm_decls (fndecl, specparms, &nonparms);
18259 else
18260 DECL_ARGUMENTS (fndecl) = NULL_TREE;
18262 /* Now store the final chain of decls for the arguments
18263 as the decl-chain of the current lexical scope.
18264 Put the enumerators in as well, at the front so that
18265 DECL_ARGUMENTS is not modified. */
18266 current_binding_level->names = chainon (nonparms, DECL_ARGUMENTS (fndecl));
18268 if (use_eh_spec_block (current_function_decl))
18269 current_eh_spec_block = begin_eh_spec_block ();
18273 /* Mark CDTOR's implicit THIS argument for returning, if required by
18274 the ABI.. Return the decl for THIS, if it is to be returned, and
18275 NULL otherwise. */
18277 tree
18278 maybe_prepare_return_this (tree cdtor)
18280 if (targetm.cxx.cdtor_returns_this ())
18281 if (tree val = DECL_ARGUMENTS (cdtor))
18283 suppress_warning (val, OPT_Wuse_after_free);
18284 return val;
18287 return NULL_TREE;
18290 /* Set the return value of the [cd]tor if the ABI wants that. */
18292 void
18293 maybe_return_this ()
18295 if (tree val = maybe_prepare_return_this (current_function_decl))
18297 /* Return the address of the object. */
18298 val = fold_convert (TREE_TYPE (DECL_RESULT (current_function_decl)), val);
18299 val = build2 (MODIFY_EXPR, TREE_TYPE (val),
18300 DECL_RESULT (current_function_decl), val);
18301 tree exprstmt = build_stmt (input_location, RETURN_EXPR, val);
18302 add_stmt (exprstmt);
18306 /* Do all the processing for the beginning of a destructor; set up the
18307 vtable pointers and cleanups for bases and members. */
18309 static void
18310 begin_destructor_body (void)
18312 tree compound_stmt;
18314 /* If the CURRENT_CLASS_TYPE is incomplete, we will have already
18315 issued an error message. We still want to try to process the
18316 body of the function, but initialize_vtbl_ptrs will crash if
18317 TYPE_BINFO is NULL. */
18318 if (COMPLETE_TYPE_P (current_class_type))
18320 compound_stmt = begin_compound_stmt (0);
18321 /* Make all virtual function table pointers in non-virtual base
18322 classes point to CURRENT_CLASS_TYPE's virtual function
18323 tables. */
18324 initialize_vtbl_ptrs (current_class_ptr);
18325 finish_compound_stmt (compound_stmt);
18327 if (flag_lifetime_dse
18328 /* Clobbering an empty base is harmful if it overlays real data. */
18329 && !is_empty_class (current_class_type))
18331 if (sanitize_flags_p (SANITIZE_VPTR)
18332 && (flag_sanitize_recover & SANITIZE_VPTR) == 0
18333 && TYPE_CONTAINS_VPTR_P (current_class_type))
18335 tree binfo = TYPE_BINFO (current_class_type);
18336 tree ref
18337 = cp_build_fold_indirect_ref (current_class_ptr);
18339 tree vtbl_ptr = build_vfield_ref (ref, TREE_TYPE (binfo));
18340 tree vtbl = build_zero_cst (TREE_TYPE (vtbl_ptr));
18341 tree stmt = cp_build_modify_expr (input_location, vtbl_ptr,
18342 NOP_EXPR, vtbl,
18343 tf_warning_or_error);
18344 /* If the vptr is shared with some virtual nearly empty base,
18345 don't clear it if not in charge, the dtor of the virtual
18346 nearly empty base will do that later. */
18347 if (CLASSTYPE_VBASECLASSES (current_class_type))
18349 tree c = current_class_type;
18350 while (CLASSTYPE_PRIMARY_BINFO (c))
18352 if (BINFO_VIRTUAL_P (CLASSTYPE_PRIMARY_BINFO (c)))
18354 stmt = convert_to_void (stmt, ICV_STATEMENT,
18355 tf_warning_or_error);
18356 stmt = build_if_in_charge (stmt);
18357 break;
18359 c = BINFO_TYPE (CLASSTYPE_PRIMARY_BINFO (c));
18362 finish_decl_cleanup (NULL_TREE, stmt);
18364 else
18365 finish_decl_cleanup (NULL_TREE,
18366 build_clobber_this (CLOBBER_OBJECT_END));
18369 /* And insert cleanups for our bases and members so that they
18370 will be properly destroyed if we throw. */
18371 push_base_cleanups ();
18375 /* Do the necessary processing for the beginning of a function body, which
18376 in this case includes member-initializers, but not the catch clauses of
18377 a function-try-block. Currently, this means opening a binding level
18378 for the member-initializers (in a ctor), member cleanups (in a dtor),
18379 and capture proxies (in a lambda operator()). */
18381 tree
18382 begin_function_body (void)
18384 if (! FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
18385 return NULL_TREE;
18387 if (processing_template_decl)
18388 /* Do nothing now. */;
18389 else
18390 /* Always keep the BLOCK node associated with the outermost pair of
18391 curly braces of a function. These are needed for correct
18392 operation of dwarfout.c. */
18393 keep_next_level (true);
18395 tree stmt = begin_compound_stmt (BCS_FN_BODY);
18396 current_binding_level->artificial = 1;
18398 if (processing_template_decl)
18399 /* Do nothing now. */;
18400 else if (DECL_DESTRUCTOR_P (current_function_decl))
18401 begin_destructor_body ();
18403 return stmt;
18406 /* Do the processing for the end of a function body. Currently, this means
18407 closing out the cleanups for fully-constructed bases and members, and in
18408 the case of the destructor, deleting the object if desired. Again, this
18409 is only meaningful for [cd]tors, since they are the only functions where
18410 there is a significant distinction between the main body and any
18411 function catch clauses. Handling, say, main() return semantics here
18412 would be wrong, as flowing off the end of a function catch clause for
18413 main() would also need to return 0. */
18415 void
18416 finish_function_body (tree compstmt)
18418 if (compstmt == NULL_TREE)
18419 return;
18421 /* Close the block. */
18422 finish_compound_stmt (compstmt);
18424 if (processing_template_decl)
18425 /* Do nothing now. */;
18426 else if (DECL_CONSTRUCTOR_P (current_function_decl)
18427 || DECL_DESTRUCTOR_P (current_function_decl))
18428 maybe_return_this ();
18431 /* Given a function, returns the BLOCK corresponding to the outermost level
18432 of curly braces, skipping the artificial block created for constructor
18433 initializers. */
18435 tree
18436 outer_curly_brace_block (tree fndecl)
18438 tree block = DECL_INITIAL (fndecl);
18439 if (BLOCK_OUTER_CURLY_BRACE_P (block))
18440 return block;
18441 block = BLOCK_SUBBLOCKS (block);
18442 if (BLOCK_OUTER_CURLY_BRACE_P (block))
18443 return block;
18444 block = BLOCK_SUBBLOCKS (block);
18445 gcc_assert (BLOCK_OUTER_CURLY_BRACE_P (block));
18446 return block;
18449 /* If FNDECL is a class's key method, add the class to the list of
18450 keyed classes that should be emitted. */
18452 static void
18453 record_key_method_defined (tree fndecl)
18455 if (DECL_OBJECT_MEMBER_FUNCTION_P (fndecl)
18456 && DECL_VIRTUAL_P (fndecl)
18457 && !processing_template_decl)
18459 tree fnclass = DECL_CONTEXT (fndecl);
18460 if (fndecl == CLASSTYPE_KEY_METHOD (fnclass))
18461 vec_safe_push (keyed_classes, fnclass);
18465 /* Attempt to add a fix-it hint to RICHLOC suggesting the insertion
18466 of "return *this;" immediately before its location, using FNDECL's
18467 first statement (if any) to give the indentation, if appropriate. */
18469 static void
18470 add_return_star_this_fixit (gcc_rich_location *richloc, tree fndecl)
18472 location_t indent = UNKNOWN_LOCATION;
18473 tree stmts = expr_first (DECL_SAVED_TREE (fndecl));
18474 if (stmts)
18475 indent = EXPR_LOCATION (stmts);
18476 richloc->add_fixit_insert_formatted ("return *this;",
18477 richloc->get_loc (),
18478 indent);
18481 /* This function carries out the subset of finish_function operations needed
18482 to emit the compiler-generated outlined helper functions used by the
18483 coroutines implementation. */
18485 static void
18486 emit_coro_helper (tree helper)
18488 /* This is a partial set of the operations done by finish_function()
18489 plus emitting the result. */
18490 set_cfun (NULL);
18491 current_function_decl = helper;
18492 begin_scope (sk_function_parms, NULL);
18493 store_parm_decls (DECL_ARGUMENTS (helper));
18494 announce_function (helper);
18495 allocate_struct_function (helper, false);
18496 cfun->language = ggc_cleared_alloc<language_function> ();
18497 poplevel (1, 0, 1);
18498 maybe_save_constexpr_fundef (helper);
18499 /* We must start each function with a clear fold cache. */
18500 clear_fold_cache ();
18501 cp_fold_function (helper);
18502 DECL_CONTEXT (DECL_RESULT (helper)) = helper;
18503 BLOCK_SUPERCONTEXT (DECL_INITIAL (helper)) = helper;
18504 /* This function has coroutine IFNs that we should handle in middle
18505 end lowering. */
18506 cfun->coroutine_component = true;
18507 cp_genericize (helper);
18508 expand_or_defer_fn (helper);
18511 /* Finish up a function declaration and compile that function
18512 all the way to assembler language output. The free the storage
18513 for the function definition. INLINE_P is TRUE if we just
18514 finished processing the body of an in-class inline function
18515 definition. (This processing will have taken place after the
18516 class definition is complete.) */
18518 tree
18519 finish_function (bool inline_p)
18521 tree fndecl = current_function_decl;
18522 tree fntype, ctype = NULL_TREE;
18523 tree resumer = NULL_TREE, destroyer = NULL_TREE;
18524 bool coro_p = flag_coroutines
18525 && !processing_template_decl
18526 && DECL_COROUTINE_P (fndecl);
18527 bool coro_emit_helpers = false;
18529 /* When we get some parse errors, we can end up without a
18530 current_function_decl, so cope. */
18531 if (fndecl == NULL_TREE)
18532 return error_mark_node;
18534 if (!DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18535 finish_lambda_scope ();
18537 if (c_dialect_objc ())
18538 objc_finish_function ();
18540 record_key_method_defined (fndecl);
18542 fntype = TREE_TYPE (fndecl);
18544 /* TREE_READONLY (fndecl) = 1;
18545 This caused &foo to be of type ptr-to-const-function
18546 which then got a warning when stored in a ptr-to-function variable. */
18548 gcc_assert (building_stmt_list_p ());
18549 /* The current function is being defined, so its DECL_INITIAL should
18550 be set, and unless there's a multiple definition, it should be
18551 error_mark_node. */
18552 gcc_assert (DECL_INITIAL (fndecl) == error_mark_node);
18554 if (coro_p)
18556 /* Only try to emit the coroutine outlined helper functions if the
18557 transforms succeeded. Otherwise, treat errors in the same way as
18558 a regular function. */
18559 coro_emit_helpers = morph_fn_to_coro (fndecl, &resumer, &destroyer);
18561 /* We should handle coroutine IFNs in middle end lowering. */
18562 cfun->coroutine_component = true;
18564 /* Do not try to process the ramp's EH unless outlining succeeded. */
18565 if (coro_emit_helpers && use_eh_spec_block (fndecl))
18566 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
18567 (TREE_TYPE (fndecl)),
18568 current_eh_spec_block);
18570 else
18571 /* For a cloned function, we've already got all the code we need;
18572 there's no need to add any extra bits. */
18573 if (!DECL_CLONED_FUNCTION_P (fndecl))
18575 /* Make it so that `main' always returns 0 by default. */
18576 if (DECL_MAIN_FREESTANDING_P (current_function_decl)
18577 && !TREE_THIS_VOLATILE (current_function_decl))
18578 finish_return_stmt (integer_zero_node);
18580 if (use_eh_spec_block (current_function_decl))
18581 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
18582 (TREE_TYPE (current_function_decl)),
18583 current_eh_spec_block);
18586 /* If we're saving up tree structure, tie off the function now. */
18587 DECL_SAVED_TREE (fndecl) = pop_stmt_list (DECL_SAVED_TREE (fndecl));
18589 finish_fname_decls ();
18591 /* This must come after expand_function_end because cleanups might
18592 have declarations (from inline functions) that need to go into
18593 this function's blocks. */
18595 /* If the current binding level isn't the outermost binding level
18596 for this function, either there is a bug, or we have experienced
18597 syntax errors and the statement tree is malformed. */
18598 if (current_binding_level->kind != sk_function_parms)
18600 /* Make sure we have already experienced errors. */
18601 gcc_assert (errorcount);
18603 /* Throw away the broken statement tree and extra binding
18604 levels. */
18605 DECL_SAVED_TREE (fndecl) = alloc_stmt_list ();
18607 while (current_binding_level->kind != sk_function_parms)
18609 if (current_binding_level->kind == sk_class)
18610 pop_nested_class ();
18611 else
18612 poplevel (0, 0, 0);
18615 poplevel (1, 0, 1);
18617 /* Statements should always be full-expressions at the outermost set
18618 of curly braces for a function. */
18619 gcc_assert (stmts_are_full_exprs_p ());
18621 /* If there are no return statements in a function with auto return type,
18622 the return type is void. But if the declared type is something like
18623 auto*, this is an error. */
18624 if (!processing_template_decl && FNDECL_USED_AUTO (fndecl)
18625 && TREE_TYPE (fntype) == DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
18627 if (is_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
18628 && !current_function_returns_value
18629 && !current_function_returns_null)
18631 /* We haven't applied return type deduction because we haven't
18632 seen any return statements. Do that now. */
18633 tree node = type_uses_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
18634 do_auto_deduction (DECL_SAVED_AUTO_RETURN_TYPE (fndecl),
18635 void_node, node, tf_warning_or_error,
18636 adc_return_type);
18638 apply_deduced_return_type (fndecl, void_type_node);
18639 fntype = TREE_TYPE (fndecl);
18641 else if (!current_function_returns_value
18642 && !current_function_returns_null)
18644 error ("no return statements in function returning %qT",
18645 DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
18646 inform (input_location, "only plain %<auto%> return type can be "
18647 "deduced to %<void%>");
18651 /* Remember that we were in class scope. */
18652 if (current_class_name)
18653 ctype = current_class_type;
18655 if (DECL_DELETED_FN (fndecl))
18657 DECL_INITIAL (fndecl) = error_mark_node;
18658 DECL_SAVED_TREE (fndecl) = NULL_TREE;
18659 goto cleanup;
18662 // If this is a concept, check that the definition is reasonable.
18663 if (DECL_DECLARED_CONCEPT_P (fndecl))
18664 check_function_concept (fndecl);
18666 if (flag_openmp)
18667 if (tree attr = lookup_attribute ("omp declare variant base",
18668 DECL_ATTRIBUTES (fndecl)))
18669 omp_declare_variant_finalize (fndecl, attr);
18671 /* Complain if there's just no return statement. */
18672 if ((warn_return_type
18673 || (cxx_dialect >= cxx14
18674 && DECL_DECLARED_CONSTEXPR_P (fndecl)))
18675 && !VOID_TYPE_P (TREE_TYPE (fntype))
18676 && !dependent_type_p (TREE_TYPE (fntype))
18677 && !current_function_returns_value && !current_function_returns_null
18678 /* Don't complain if we abort or throw. */
18679 && !current_function_returns_abnormally
18680 /* Don't complain if there's an infinite loop. */
18681 && !current_function_infinite_loop
18682 /* Don't complain if we are declared noreturn. */
18683 && !TREE_THIS_VOLATILE (fndecl)
18684 && !DECL_NAME (DECL_RESULT (fndecl))
18685 && !warning_suppressed_p (fndecl, OPT_Wreturn_type)
18686 /* Structor return values (if any) are set by the compiler. */
18687 && !DECL_CONSTRUCTOR_P (fndecl)
18688 && !DECL_DESTRUCTOR_P (fndecl)
18689 && targetm.warn_func_return (fndecl))
18691 gcc_rich_location richloc (input_location);
18692 /* Potentially add a "return *this;" fix-it hint for
18693 assignment operators. */
18694 if (IDENTIFIER_ASSIGN_OP_P (DECL_NAME (fndecl)))
18696 tree valtype = TREE_TYPE (DECL_RESULT (fndecl));
18697 if (TREE_CODE (valtype) == REFERENCE_TYPE
18698 && current_class_ref
18699 && same_type_ignoring_top_level_qualifiers_p
18700 (TREE_TYPE (valtype), TREE_TYPE (current_class_ref))
18701 && global_dc->option_enabled_p (OPT_Wreturn_type))
18702 add_return_star_this_fixit (&richloc, fndecl);
18704 if (cxx_dialect >= cxx14
18705 && DECL_DECLARED_CONSTEXPR_P (fndecl))
18706 error_at (&richloc, "no return statement in %<constexpr%> function "
18707 "returning non-void");
18708 else if (warning_at (&richloc, OPT_Wreturn_type,
18709 "no return statement in function returning "
18710 "non-void"))
18711 suppress_warning (fndecl, OPT_Wreturn_type);
18714 /* Lambda closure members are implicitly constexpr if possible. */
18715 if (cxx_dialect >= cxx17
18716 && LAMBDA_TYPE_P (CP_DECL_CONTEXT (fndecl)))
18717 DECL_DECLARED_CONSTEXPR_P (fndecl)
18718 = ((processing_template_decl
18719 || is_valid_constexpr_fn (fndecl, /*complain*/false))
18720 && potential_constant_expression (DECL_SAVED_TREE (fndecl)));
18722 /* Save constexpr function body before it gets munged by
18723 the NRV transformation. */
18724 maybe_save_constexpr_fundef (fndecl);
18726 /* Invoke the pre-genericize plugin before we start munging things. */
18727 if (!processing_template_decl)
18728 invoke_plugin_callbacks (PLUGIN_PRE_GENERICIZE, fndecl);
18730 /* Perform delayed folding before NRV transformation. */
18731 if (!processing_template_decl
18732 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
18733 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18734 cp_fold_function (fndecl);
18736 /* Set up the named return value optimization, if we can. Candidate
18737 variables are selected in check_return_expr. */
18738 if (tree r = current_function_return_value)
18740 if (r != error_mark_node)
18741 finalize_nrv (fndecl, r);
18742 current_function_return_value = NULL_TREE;
18745 /* Must mark the RESULT_DECL as being in this function. */
18746 DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
18748 /* Set the BLOCK_SUPERCONTEXT of the outermost function scope to point
18749 to the FUNCTION_DECL node itself. */
18750 BLOCK_SUPERCONTEXT (DECL_INITIAL (fndecl)) = fndecl;
18752 /* Store the end of the function, so that we get good line number
18753 info for the epilogue. */
18754 cfun->function_end_locus = input_location;
18756 /* Complain about parameters that are only set, but never otherwise used. */
18757 if (warn_unused_but_set_parameter
18758 && !processing_template_decl
18759 && errorcount == unused_but_set_errorcount
18760 && !DECL_CLONED_FUNCTION_P (fndecl))
18762 tree decl;
18764 for (decl = DECL_ARGUMENTS (fndecl);
18765 decl;
18766 decl = DECL_CHAIN (decl))
18767 if (TREE_USED (decl)
18768 && TREE_CODE (decl) == PARM_DECL
18769 && !DECL_READ_P (decl)
18770 && DECL_NAME (decl)
18771 && !DECL_ARTIFICIAL (decl)
18772 && !warning_suppressed_p (decl,OPT_Wunused_but_set_parameter)
18773 && !DECL_IN_SYSTEM_HEADER (decl)
18774 && TREE_TYPE (decl) != error_mark_node
18775 && !TYPE_REF_P (TREE_TYPE (decl))
18776 && (!CLASS_TYPE_P (TREE_TYPE (decl))
18777 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl))))
18778 warning_at (DECL_SOURCE_LOCATION (decl),
18779 OPT_Wunused_but_set_parameter,
18780 "parameter %qD set but not used", decl);
18781 unused_but_set_errorcount = errorcount;
18784 /* Complain about locally defined typedefs that are not used in this
18785 function. */
18786 maybe_warn_unused_local_typedefs ();
18788 /* Possibly warn about unused parameters. */
18789 if (warn_unused_parameter
18790 && !processing_template_decl
18791 && !DECL_CLONED_FUNCTION_P (fndecl))
18792 do_warn_unused_parameter (fndecl);
18794 /* Genericize before inlining. */
18795 if (!processing_template_decl
18796 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
18797 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18798 cp_genericize (fndecl);
18800 /* If this function can't throw any exceptions, remember that. */
18801 if (!processing_template_decl
18802 && !cp_function_chain->can_throw
18803 && !flag_non_call_exceptions
18804 && !decl_replaceable_p (fndecl,
18805 opt_for_fn (fndecl, flag_semantic_interposition)))
18806 TREE_NOTHROW (fndecl) = 1;
18808 /* Emit the resumer and destroyer functions now, providing that we have
18809 not encountered some fatal error. */
18810 if (coro_emit_helpers)
18812 emit_coro_helper (resumer);
18813 emit_coro_helper (destroyer);
18816 cleanup:
18817 /* We're leaving the context of this function, so zap cfun. It's still in
18818 DECL_STRUCT_FUNCTION, and we'll restore it in tree_rest_of_compilation. */
18819 set_cfun (NULL);
18820 current_function_decl = NULL;
18822 /* If this is an in-class inline definition, we may have to pop the
18823 bindings for the template parameters that we added in
18824 maybe_begin_member_template_processing when start_function was
18825 called. */
18826 if (inline_p)
18827 maybe_end_member_template_processing ();
18829 /* Leave the scope of the class. */
18830 if (ctype)
18831 pop_nested_class ();
18833 --function_depth;
18835 /* Clean up. */
18836 current_function_decl = NULL_TREE;
18838 invoke_plugin_callbacks (PLUGIN_FINISH_PARSE_FUNCTION, fndecl);
18840 finish_function_contracts (fndecl);
18842 return fndecl;
18845 /* Create the FUNCTION_DECL for a function definition.
18846 DECLSPECS and DECLARATOR are the parts of the declaration;
18847 they describe the return type and the name of the function,
18848 but twisted together in a fashion that parallels the syntax of C.
18850 This function creates a binding context for the function body
18851 as well as setting up the FUNCTION_DECL in current_function_decl.
18853 Returns a FUNCTION_DECL on success.
18855 If the DECLARATOR is not suitable for a function (it defines a datum
18856 instead), we return 0, which tells yyparse to report a parse error.
18858 May return void_type_node indicating that this method is actually
18859 a friend. See grokfield for more details.
18861 Came here with a `.pushlevel' .
18863 DO NOT MAKE ANY CHANGES TO THIS CODE WITHOUT MAKING CORRESPONDING
18864 CHANGES TO CODE IN `grokfield'. */
18866 tree
18867 grokmethod (cp_decl_specifier_seq *declspecs,
18868 const cp_declarator *declarator, tree attrlist)
18870 tree fndecl = grokdeclarator (declarator, declspecs, MEMFUNCDEF, 0,
18871 &attrlist);
18873 if (fndecl == error_mark_node)
18874 return error_mark_node;
18876 if (attrlist)
18877 cplus_decl_attributes (&fndecl, attrlist, 0);
18879 /* Pass friends other than inline friend functions back. */
18880 if (fndecl == void_type_node)
18881 return fndecl;
18883 if (DECL_IN_AGGR_P (fndecl))
18885 if (DECL_CLASS_SCOPE_P (fndecl))
18886 error ("%qD is already defined in class %qT", fndecl,
18887 DECL_CONTEXT (fndecl));
18888 return error_mark_node;
18891 check_template_shadow (fndecl);
18893 /* p1779 ABI-Isolation makes inline not a default for in-class
18894 definitions in named module purview. If the user explicitly
18895 made it inline, grokdeclarator will already have done the right
18896 things. */
18897 if ((!named_module_purview_p ()
18898 || flag_module_implicit_inline
18899 /* Lambda's operator function remains inline. */
18900 || LAMBDA_TYPE_P (DECL_CONTEXT (fndecl)))
18901 /* If the user explicitly asked for this to be inline, we don't
18902 need to do more, but more importantly we want to warn if we
18903 can't inline it. */
18904 && !DECL_DECLARED_INLINE_P (fndecl))
18906 if (TREE_PUBLIC (fndecl))
18907 DECL_COMDAT (fndecl) = 1;
18908 DECL_DECLARED_INLINE_P (fndecl) = 1;
18909 /* It's ok if we can't inline this. */
18910 DECL_NO_INLINE_WARNING_P (fndecl) = 1;
18913 /* We process method specializations in finish_struct_1. */
18914 if (processing_template_decl && !DECL_TEMPLATE_SPECIALIZATION (fndecl))
18916 /* Avoid calling decl_spec_seq... until we have to. */
18917 bool friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
18918 fndecl = push_template_decl (fndecl, friendp);
18919 if (fndecl == error_mark_node)
18920 return fndecl;
18923 if (DECL_CHAIN (fndecl) && !decl_spec_seq_has_spec_p (declspecs, ds_friend))
18925 fndecl = copy_node (fndecl);
18926 TREE_CHAIN (fndecl) = NULL_TREE;
18929 cp_finish_decl (fndecl, NULL_TREE, false, NULL_TREE, 0);
18931 DECL_IN_AGGR_P (fndecl) = 1;
18932 return fndecl;
18936 /* VAR is a VAR_DECL. If its type is incomplete, remember VAR so that
18937 we can lay it out later, when and if its type becomes complete.
18939 Also handle constexpr variables where the initializer involves
18940 an unlowered PTRMEM_CST because the class isn't complete yet. */
18942 void
18943 maybe_register_incomplete_var (tree var)
18945 gcc_assert (VAR_P (var));
18947 /* Keep track of variables with incomplete types. */
18948 if (!processing_template_decl && TREE_TYPE (var) != error_mark_node
18949 && DECL_EXTERNAL (var))
18951 tree inner_type = TREE_TYPE (var);
18953 while (TREE_CODE (inner_type) == ARRAY_TYPE)
18954 inner_type = TREE_TYPE (inner_type);
18955 inner_type = TYPE_MAIN_VARIANT (inner_type);
18957 if ((!COMPLETE_TYPE_P (inner_type) && CLASS_TYPE_P (inner_type))
18958 /* RTTI TD entries are created while defining the type_info. */
18959 || (TYPE_LANG_SPECIFIC (inner_type)
18960 && TYPE_BEING_DEFINED (inner_type)))
18962 incomplete_var iv = {var, inner_type};
18963 vec_safe_push (incomplete_vars, iv);
18965 else if (!(DECL_LANG_SPECIFIC (var) && DECL_TEMPLATE_INFO (var))
18966 && decl_constant_var_p (var)
18967 && (TYPE_PTRMEM_P (inner_type) || CLASS_TYPE_P (inner_type)))
18969 /* When the outermost open class is complete we can resolve any
18970 pointers-to-members. */
18971 tree context = outermost_open_class ();
18972 incomplete_var iv = {var, context};
18973 vec_safe_push (incomplete_vars, iv);
18978 /* Called when a class type (given by TYPE) is defined. If there are
18979 any existing VAR_DECLs whose type has been completed by this
18980 declaration, update them now. */
18982 void
18983 complete_vars (tree type)
18985 unsigned ix;
18986 incomplete_var *iv;
18988 for (ix = 0; vec_safe_iterate (incomplete_vars, ix, &iv); )
18990 if (same_type_p (type, iv->incomplete_type))
18992 tree var = iv->decl;
18993 tree type = TREE_TYPE (var);
18995 if (type != error_mark_node
18996 && (TYPE_MAIN_VARIANT (strip_array_types (type))
18997 == iv->incomplete_type))
18999 /* Complete the type of the variable. */
19000 complete_type (type);
19001 cp_apply_type_quals_to_decl (cp_type_quals (type), var);
19002 if (COMPLETE_TYPE_P (type))
19003 layout_var_decl (var);
19006 /* Remove this entry from the list. */
19007 incomplete_vars->unordered_remove (ix);
19009 else
19010 ix++;
19014 /* If DECL is of a type which needs a cleanup, build and return an
19015 expression to perform that cleanup here. Return NULL_TREE if no
19016 cleanup need be done. DECL can also be a _REF when called from
19017 split_nonconstant_init_1. */
19019 tree
19020 cxx_maybe_build_cleanup (tree decl, tsubst_flags_t complain)
19022 tree type;
19023 tree attr;
19024 tree cleanup;
19026 /* Assume no cleanup is required. */
19027 cleanup = NULL_TREE;
19029 if (error_operand_p (decl))
19030 return cleanup;
19032 /* Handle "__attribute__((cleanup))". We run the cleanup function
19033 before the destructor since the destructor is what actually
19034 terminates the lifetime of the object. */
19035 if (DECL_P (decl))
19036 attr = lookup_attribute ("cleanup", DECL_ATTRIBUTES (decl));
19037 else
19038 attr = NULL_TREE;
19039 if (attr)
19041 tree id;
19042 tree fn;
19043 tree arg;
19045 /* Get the name specified by the user for the cleanup function. */
19046 id = TREE_VALUE (TREE_VALUE (attr));
19047 /* Look up the name to find the cleanup function to call. It is
19048 important to use lookup_name here because that is what is
19049 used in c-common.cc:handle_cleanup_attribute when performing
19050 initial checks on the attribute. Note that those checks
19051 include ensuring that the function found is not an overloaded
19052 function, or an object with an overloaded call operator,
19053 etc.; we can rely on the fact that the function found is an
19054 ordinary FUNCTION_DECL. */
19055 fn = lookup_name (id);
19056 arg = build_address (decl);
19057 if (!mark_used (decl, complain) && !(complain & tf_error))
19058 return error_mark_node;
19059 cleanup = cp_build_function_call_nary (fn, complain, arg, NULL_TREE);
19060 if (cleanup == error_mark_node)
19061 return error_mark_node;
19063 /* Handle ordinary C++ destructors. */
19064 type = TREE_TYPE (decl);
19065 if (type_build_dtor_call (type))
19067 int flags = LOOKUP_NORMAL|LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR;
19068 tree addr;
19069 tree call;
19071 if (TREE_CODE (type) == ARRAY_TYPE)
19072 addr = decl;
19073 else
19074 addr = build_address (decl);
19076 call = build_delete (input_location, TREE_TYPE (addr), addr,
19077 sfk_complete_destructor, flags, 0, complain);
19078 if (call == error_mark_node)
19079 cleanup = error_mark_node;
19080 else if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
19081 /* Discard the call. */;
19082 else if (decl_maybe_constant_destruction (decl, type)
19083 && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
19084 cxx_constant_dtor (call, decl);
19085 else if (cleanup)
19086 cleanup = cp_build_compound_expr (cleanup, call, complain);
19087 else
19088 cleanup = call;
19091 /* build_delete sets the location of the destructor call to the
19092 current location, even though the destructor is going to be
19093 called later, at the end of the current scope. This can lead to
19094 a "jumpy" behavior for users of debuggers when they step around
19095 the end of the block. So let's unset the location of the
19096 destructor call instead. */
19097 protected_set_expr_location (cleanup, UNKNOWN_LOCATION);
19098 if (cleanup && CONVERT_EXPR_P (cleanup))
19099 protected_set_expr_location (TREE_OPERAND (cleanup, 0), UNKNOWN_LOCATION);
19101 if (cleanup
19102 && DECL_P (decl)
19103 && !lookup_attribute ("warn_unused", TYPE_ATTRIBUTES (TREE_TYPE (decl)))
19104 /* Treat objects with destructors as used; the destructor may do
19105 something substantive. */
19106 && !mark_used (decl, complain) && !(complain & tf_error))
19107 return error_mark_node;
19109 if (cleanup && cfun && !processing_template_decl
19110 && !expr_noexcept_p (cleanup, tf_none))
19111 cp_function_chain->throwing_cleanup = true;
19113 return cleanup;
19117 /* Return the FUNCTION_TYPE that corresponds to MEMFNTYPE, which can be a
19118 FUNCTION_DECL, METHOD_TYPE, FUNCTION_TYPE, pointer or reference to
19119 METHOD_TYPE or FUNCTION_TYPE, or pointer to member function. */
19121 tree
19122 static_fn_type (tree memfntype)
19124 tree fntype;
19125 tree args;
19127 if (TYPE_PTRMEMFUNC_P (memfntype))
19128 memfntype = TYPE_PTRMEMFUNC_FN_TYPE (memfntype);
19129 if (INDIRECT_TYPE_P (memfntype)
19130 || TREE_CODE (memfntype) == FUNCTION_DECL)
19131 memfntype = TREE_TYPE (memfntype);
19132 if (TREE_CODE (memfntype) == FUNCTION_TYPE)
19133 return memfntype;
19134 gcc_assert (TREE_CODE (memfntype) == METHOD_TYPE);
19135 args = TYPE_ARG_TYPES (memfntype);
19136 fntype = build_function_type (TREE_TYPE (memfntype), TREE_CHAIN (args));
19137 fntype = apply_memfn_quals (fntype, type_memfn_quals (memfntype));
19138 fntype = (cp_build_type_attribute_variant
19139 (fntype, TYPE_ATTRIBUTES (memfntype)));
19140 fntype = cxx_copy_lang_qualifiers (fntype, memfntype);
19141 return fntype;
19144 /* DECL was originally constructed as a non-static member function,
19145 but turned out to be static. Update it accordingly. */
19147 void
19148 revert_static_member_fn (tree decl)
19150 tree stype = static_fn_type (decl);
19151 cp_cv_quals quals = type_memfn_quals (stype);
19152 cp_ref_qualifier rqual = type_memfn_rqual (stype);
19154 if (quals != TYPE_UNQUALIFIED || rqual != REF_QUAL_NONE)
19155 stype = apply_memfn_quals (stype, TYPE_UNQUALIFIED, REF_QUAL_NONE);
19157 TREE_TYPE (decl) = stype;
19159 if (DECL_ARGUMENTS (decl))
19160 DECL_ARGUMENTS (decl) = DECL_CHAIN (DECL_ARGUMENTS (decl));
19161 DECL_STATIC_FUNCTION_P (decl) = 1;
19164 /* Return which tree structure is used by T, or TS_CP_GENERIC if T is
19165 one of the language-independent trees. */
19167 enum cp_tree_node_structure_enum
19168 cp_tree_node_structure (union lang_tree_node * t)
19170 switch (TREE_CODE (&t->generic))
19172 case ARGUMENT_PACK_SELECT: return TS_CP_ARGUMENT_PACK_SELECT;
19173 case BASELINK: return TS_CP_BASELINK;
19174 case CONSTRAINT_INFO: return TS_CP_CONSTRAINT_INFO;
19175 case DEFERRED_NOEXCEPT: return TS_CP_DEFERRED_NOEXCEPT;
19176 case DEFERRED_PARSE: return TS_CP_DEFERRED_PARSE;
19177 case IDENTIFIER_NODE: return TS_CP_IDENTIFIER;
19178 case LAMBDA_EXPR: return TS_CP_LAMBDA_EXPR;
19179 case BINDING_VECTOR: return TS_CP_BINDING_VECTOR;
19180 case OVERLOAD: return TS_CP_OVERLOAD;
19181 case PTRMEM_CST: return TS_CP_PTRMEM;
19182 case STATIC_ASSERT: return TS_CP_STATIC_ASSERT;
19183 case TEMPLATE_DECL: return TS_CP_TEMPLATE_DECL;
19184 case TEMPLATE_INFO: return TS_CP_TEMPLATE_INFO;
19185 case TEMPLATE_PARM_INDEX: return TS_CP_TPI;
19186 case TRAIT_EXPR: return TS_CP_TRAIT_EXPR;
19187 case USERDEF_LITERAL: return TS_CP_USERDEF_LITERAL;
19188 default: return TS_CP_GENERIC;
19192 bool
19193 cp_missing_noreturn_ok_p (tree decl)
19195 /* A missing noreturn is ok for the `main' function. */
19196 return DECL_MAIN_P (decl);
19199 /* Return the decl used to identify the COMDAT group into which DECL should
19200 be placed. */
19202 tree
19203 cxx_comdat_group (tree decl)
19205 /* Virtual tables, construction virtual tables, and virtual table
19206 tables all go in a single COMDAT group, named after the primary
19207 virtual table. */
19208 if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
19209 decl = CLASSTYPE_VTABLES (DECL_CONTEXT (decl));
19210 /* For all other DECLs, the COMDAT group is the mangled name of the
19211 declaration itself. */
19212 else
19214 while (DECL_THUNK_P (decl))
19216 /* If TARGET_USE_LOCAL_THUNK_ALIAS_P, use_thunk puts the thunk
19217 into the same section as the target function. In that case
19218 we must return target's name. */
19219 tree target = THUNK_TARGET (decl);
19220 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (target)
19221 && DECL_SECTION_NAME (target) != NULL
19222 && DECL_ONE_ONLY (target))
19223 decl = target;
19224 else
19225 break;
19229 return decl;
19232 /* Returns the return type for FN as written by the user, which may include
19233 a placeholder for a deduced return type. */
19235 tree
19236 fndecl_declared_return_type (tree fn)
19238 fn = STRIP_TEMPLATE (fn);
19239 if (FNDECL_USED_AUTO (fn))
19240 return DECL_SAVED_AUTO_RETURN_TYPE (fn);
19242 return TREE_TYPE (TREE_TYPE (fn));
19245 /* Returns true iff DECL is a variable or function declared with an auto type
19246 that has not yet been deduced to a real type. */
19248 bool
19249 undeduced_auto_decl (tree decl)
19251 if (cxx_dialect < cxx11)
19252 return false;
19253 STRIP_ANY_LOCATION_WRAPPER (decl);
19254 return ((VAR_OR_FUNCTION_DECL_P (decl)
19255 || TREE_CODE (decl) == TEMPLATE_DECL)
19256 && type_uses_auto (TREE_TYPE (decl)));
19259 /* Complain if DECL has an undeduced return type. */
19261 bool
19262 require_deduced_type (tree decl, tsubst_flags_t complain)
19264 if (undeduced_auto_decl (decl))
19266 if (TREE_CODE (decl) == FUNCTION_DECL
19267 && fndecl_built_in_p (decl, BUILT_IN_FRONTEND)
19268 && DECL_FE_FUNCTION_CODE (decl) == CP_BUILT_IN_SOURCE_LOCATION)
19270 /* Set the return type of __builtin_source_location. */
19271 tree type = get_source_location_impl_type ();
19272 if (type == error_mark_node)
19274 inform (input_location, "using %qs", "__builtin_source_location");
19275 return false;
19277 type = cp_build_qualified_type (type, TYPE_QUAL_CONST);
19278 type = build_pointer_type (type);
19279 apply_deduced_return_type (decl, type);
19280 return true;
19283 if (warning_suppressed_p (decl) && seen_error ())
19284 /* We probably already complained about deduction failure. */;
19285 else if (complain & tf_error)
19286 error ("use of %qD before deduction of %<auto%>", decl);
19287 note_failed_type_completion_for_satisfaction (decl);
19288 return false;
19290 return true;
19293 /* Create a representation of the explicit-specifier with
19294 constant-expression of EXPR. COMPLAIN is as for tsubst. */
19296 tree
19297 build_explicit_specifier (tree expr, tsubst_flags_t complain)
19299 if (check_for_bare_parameter_packs (expr))
19300 return error_mark_node;
19302 if (instantiation_dependent_expression_p (expr))
19303 /* Wait for instantiation, tsubst_function_decl will handle it. */
19304 return expr;
19306 expr = build_converted_constant_bool_expr (expr, complain);
19307 expr = instantiate_non_dependent_expr (expr, complain);
19308 expr = cxx_constant_value (expr, complain);
19309 return expr;
19312 #include "gt-cp-decl.h"