Require target lra in gcc.c-torture/compile/asmgoto-6.c
[official-gcc.git] / gcc / cp / decl.cc
blob792ab330dd056e90cd4df1b59386045ded988430
1 /* Process declarations and variables for -*- C++ -*- compiler.
2 Copyright (C) 1988-2023 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*);
109 /* The following symbols are subsumed in the cp_global_trees array, and
110 listed here individually for documentation purposes.
112 C++ extensions
113 tree wchar_decl_node;
115 tree vtable_entry_type;
116 tree delta_type_node;
117 tree __t_desc_type_node;
119 tree class_type_node;
120 tree unknown_type_node;
122 Array type `vtable_entry_type[]'
124 tree vtbl_type_node;
125 tree vtbl_ptr_type_node;
127 Namespaces,
129 tree std_node;
130 tree abi_node;
132 A FUNCTION_DECL which can call `abort'. Not necessarily the
133 one that the user will declare, but sufficient to be called
134 by routines that want to abort the program.
136 tree abort_fndecl;
138 Used by RTTI
139 tree type_info_type_node, tinfo_decl_id, tinfo_decl_type;
140 tree tinfo_var_id; */
142 tree cp_global_trees[CPTI_MAX];
144 /* A list of objects which have constructors or destructors
145 which reside in namespace scope. The decl is stored in
146 the TREE_VALUE slot and the initializer is stored
147 in the TREE_PURPOSE slot. */
148 tree static_aggregates;
150 /* Like static_aggregates, but for thread_local variables. */
151 tree tls_aggregates;
153 /* A hash-map mapping from variable decls to the dynamic initializer for
154 the decl. This is currently only used by OpenMP. */
155 decl_tree_map *dynamic_initializers;
157 /* -- end of C++ */
159 /* A node for the integer constant 2. */
161 tree integer_two_node;
163 /* vector of static decls. */
164 vec<tree, va_gc> *static_decls;
166 /* vector of keyed classes. */
167 vec<tree, va_gc> *keyed_classes;
169 /* Used only for jumps to as-yet undefined labels, since jumps to
170 defined labels can have their validity checked immediately. */
172 struct GTY((chain_next ("%h.next"))) named_label_use_entry {
173 struct named_label_use_entry *next;
174 /* The binding level to which this entry is *currently* attached.
175 This is initially the binding level in which the goto appeared,
176 but is modified as scopes are closed. */
177 cp_binding_level *binding_level;
178 /* The head of the names list that was current when the goto appeared,
179 or the inner scope popped. These are the decls that will *not* be
180 skipped when jumping to the label. */
181 tree names_in_scope;
182 /* The location of the goto, for error reporting. */
183 location_t o_goto_locus;
184 /* True if an OpenMP structured block scope has been closed since
185 the goto appeared. This means that the branch from the label will
186 illegally exit an OpenMP scope. */
187 bool in_omp_scope;
190 /* A list of all LABEL_DECLs in the function that have names. Here so
191 we can clear out their names' definitions at the end of the
192 function, and so we can check the validity of jumps to these labels. */
194 struct GTY((for_user)) named_label_entry {
196 tree name; /* Name of decl. */
198 tree label_decl; /* LABEL_DECL, unless deleted local label. */
200 named_label_entry *outer; /* Outer shadowed chain. */
202 /* The binding level to which the label is *currently* attached.
203 This is initially set to the binding level in which the label
204 is defined, but is modified as scopes are closed. */
205 cp_binding_level *binding_level;
207 /* The head of the names list that was current when the label was
208 defined, or the inner scope popped. These are the decls that will
209 be skipped when jumping to the label. */
210 tree names_in_scope;
212 /* A vector of all decls from all binding levels that would be
213 crossed by a backward branch to the label. */
214 vec<tree, va_gc> *bad_decls;
216 /* A list of uses of the label, before the label is defined. */
217 named_label_use_entry *uses;
219 /* The following bits are set after the label is defined, and are
220 updated as scopes are popped. They indicate that a jump to the
221 label will illegally enter a scope of the given flavor. */
222 bool in_try_scope;
223 bool in_catch_scope;
224 bool in_omp_scope;
225 bool in_transaction_scope;
226 bool in_constexpr_if;
227 bool in_consteval_if;
228 bool in_stmt_expr;
231 #define named_labels cp_function_chain->x_named_labels
233 /* The number of function bodies which we are currently processing.
234 (Zero if we are at namespace scope, one inside the body of a
235 function, two inside the body of a function in a local class, etc.) */
236 int function_depth;
238 /* Whether the exception-specifier is part of a function type (i.e. C++17). */
239 bool flag_noexcept_type;
241 /* States indicating how grokdeclarator() should handle declspecs marked
242 with __attribute__((deprecated)). An object declared as
243 __attribute__((deprecated)) suppresses warnings of uses of other
244 deprecated items. */
245 enum deprecated_states deprecated_state = DEPRECATED_NORMAL;
248 /* A list of VAR_DECLs whose type was incomplete at the time the
249 variable was declared. */
251 struct GTY(()) incomplete_var {
252 tree decl;
253 tree incomplete_type;
257 static GTY(()) vec<incomplete_var, va_gc> *incomplete_vars;
259 /* Returns the kind of template specialization we are currently
260 processing, given that it's declaration contained N_CLASS_SCOPES
261 explicit scope qualifications. */
263 tmpl_spec_kind
264 current_tmpl_spec_kind (int n_class_scopes)
266 int n_template_parm_scopes = 0;
267 int seen_specialization_p = 0;
268 int innermost_specialization_p = 0;
269 cp_binding_level *b;
271 /* Scan through the template parameter scopes. */
272 for (b = current_binding_level;
273 b->kind == sk_template_parms;
274 b = b->level_chain)
276 /* If we see a specialization scope inside a parameter scope,
277 then something is wrong. That corresponds to a declaration
278 like:
280 template <class T> template <> ...
282 which is always invalid since [temp.expl.spec] forbids the
283 specialization of a class member template if the enclosing
284 class templates are not explicitly specialized as well. */
285 if (b->explicit_spec_p)
287 if (n_template_parm_scopes == 0)
288 innermost_specialization_p = 1;
289 else
290 seen_specialization_p = 1;
292 else if (seen_specialization_p == 1)
293 return tsk_invalid_member_spec;
295 ++n_template_parm_scopes;
298 /* Handle explicit instantiations. */
299 if (processing_explicit_instantiation)
301 if (n_template_parm_scopes != 0)
302 /* We've seen a template parameter list during an explicit
303 instantiation. For example:
305 template <class T> template void f(int);
307 This is erroneous. */
308 return tsk_invalid_expl_inst;
309 else
310 return tsk_expl_inst;
313 if (n_template_parm_scopes < n_class_scopes)
314 /* We've not seen enough template headers to match all the
315 specialized classes present. For example:
317 template <class T> void R<T>::S<T>::f(int);
319 This is invalid; there needs to be one set of template
320 parameters for each class. */
321 return tsk_insufficient_parms;
322 else if (n_template_parm_scopes == n_class_scopes)
323 /* We're processing a non-template declaration (even though it may
324 be a member of a template class.) For example:
326 template <class T> void S<T>::f(int);
328 The `class T' matches the `S<T>', leaving no template headers
329 corresponding to the `f'. */
330 return tsk_none;
331 else if (n_template_parm_scopes > n_class_scopes + 1)
332 /* We've got too many template headers. For example:
334 template <> template <class T> void f (T);
336 There need to be more enclosing classes. */
337 return tsk_excessive_parms;
338 else
339 /* This must be a template. It's of the form:
341 template <class T> template <class U> void S<T>::f(U);
343 This is a specialization if the innermost level was a
344 specialization; otherwise it's just a definition of the
345 template. */
346 return innermost_specialization_p ? tsk_expl_spec : tsk_template;
349 /* Exit the current scope. */
351 void
352 finish_scope (void)
354 poplevel (0, 0, 0);
357 /* When a label goes out of scope, check to see if that label was used
358 in a valid manner, and issue any appropriate warnings or errors. */
360 static void
361 check_label_used (tree label)
363 if (!processing_template_decl)
365 if (DECL_INITIAL (label) == NULL_TREE)
367 location_t location;
369 error ("label %q+D used but not defined", label);
370 location = input_location;
371 /* FIXME want (LOCATION_FILE (input_location), (line)0) */
372 /* Avoid crashing later. */
373 define_label (location, DECL_NAME (label));
375 else
376 warn_for_unused_label (label);
380 /* Helper function to sort named label entries in a vector by DECL_UID. */
382 static int
383 sort_labels (const void *a, const void *b)
385 tree label1 = *(tree const *) a;
386 tree label2 = *(tree const *) b;
388 /* DECL_UIDs can never be equal. */
389 return DECL_UID (label1) > DECL_UID (label2) ? -1 : +1;
392 /* At the end of a function, all labels declared within the function
393 go out of scope. BLOCK is the top-level block for the
394 function. */
396 static void
397 pop_labels (tree block)
399 if (!named_labels)
400 return;
402 /* We need to add the labels to the block chain, so debug
403 information is emitted. But, we want the order to be stable so
404 need to sort them first. Otherwise the debug output could be
405 randomly ordered. I guess it's mostly stable, unless the hash
406 table implementation changes. */
407 auto_vec<tree, 32> labels (named_labels->elements ());
408 hash_table<named_label_hash>::iterator end (named_labels->end ());
409 for (hash_table<named_label_hash>::iterator iter
410 (named_labels->begin ()); iter != end; ++iter)
412 named_label_entry *ent = *iter;
414 gcc_checking_assert (!ent->outer);
415 if (ent->label_decl)
416 labels.quick_push (ent->label_decl);
417 ggc_free (ent);
419 named_labels = NULL;
420 labels.qsort (sort_labels);
422 while (labels.length ())
424 tree label = labels.pop ();
426 DECL_CHAIN (label) = BLOCK_VARS (block);
427 BLOCK_VARS (block) = label;
429 check_label_used (label);
433 /* At the end of a block with local labels, restore the outer definition. */
435 static void
436 pop_local_label (tree id, tree label)
438 check_label_used (label);
439 named_label_entry **slot = named_labels->find_slot_with_hash
440 (id, IDENTIFIER_HASH_VALUE (id), NO_INSERT);
441 named_label_entry *ent = *slot;
443 if (ent->outer)
444 ent = ent->outer;
445 else
447 ent = ggc_cleared_alloc<named_label_entry> ();
448 ent->name = id;
450 *slot = ent;
453 /* The following two routines are used to interface to Objective-C++.
454 The binding level is purposely treated as an opaque type. */
456 void *
457 objc_get_current_scope (void)
459 return current_binding_level;
462 /* The following routine is used by the NeXT-style SJLJ exceptions;
463 variables get marked 'volatile' so as to not be clobbered by
464 _setjmp()/_longjmp() calls. All variables in the current scope,
465 as well as parent scopes up to (but not including) ENCLOSING_BLK
466 shall be thusly marked. */
468 void
469 objc_mark_locals_volatile (void *enclosing_blk)
471 cp_binding_level *scope;
473 for (scope = current_binding_level;
474 scope && scope != enclosing_blk;
475 scope = scope->level_chain)
477 tree decl;
479 for (decl = scope->names; decl; decl = TREE_CHAIN (decl))
480 objc_volatilize_decl (decl);
482 /* Do not climb up past the current function. */
483 if (scope->kind == sk_function_parms)
484 break;
488 /* True if B is the level for the condition of a constexpr if. */
490 static bool
491 level_for_constexpr_if (cp_binding_level *b)
493 return (b->kind == sk_cond && b->this_entity
494 && TREE_CODE (b->this_entity) == IF_STMT
495 && IF_STMT_CONSTEXPR_P (b->this_entity));
498 /* True if B is the level for the condition of a consteval if. */
500 static bool
501 level_for_consteval_if (cp_binding_level *b)
503 return (b->kind == sk_cond && b->this_entity
504 && TREE_CODE (b->this_entity) == IF_STMT
505 && IF_STMT_CONSTEVAL_P (b->this_entity));
508 /* Update data for defined and undefined labels when leaving a scope. */
511 poplevel_named_label_1 (named_label_entry **slot, cp_binding_level *bl)
513 named_label_entry *ent = *slot;
514 cp_binding_level *obl = bl->level_chain;
516 if (ent->binding_level == bl)
518 tree decl;
520 /* ENT->NAMES_IN_SCOPE may contain a mixture of DECLs and
521 TREE_LISTs representing OVERLOADs, so be careful. */
522 for (decl = ent->names_in_scope; decl; decl = (DECL_P (decl)
523 ? DECL_CHAIN (decl)
524 : TREE_CHAIN (decl)))
525 if (decl_jump_unsafe (decl))
526 vec_safe_push (ent->bad_decls, decl);
528 ent->binding_level = obl;
529 ent->names_in_scope = obl->names;
530 switch (bl->kind)
532 case sk_try:
533 ent->in_try_scope = true;
534 break;
535 case sk_catch:
536 ent->in_catch_scope = true;
537 break;
538 case sk_omp:
539 ent->in_omp_scope = true;
540 break;
541 case sk_transaction:
542 ent->in_transaction_scope = true;
543 break;
544 case sk_stmt_expr:
545 ent->in_stmt_expr = true;
546 break;
547 case sk_block:
548 if (level_for_constexpr_if (bl->level_chain))
549 ent->in_constexpr_if = true;
550 else if (level_for_consteval_if (bl->level_chain))
551 ent->in_consteval_if = true;
552 break;
553 default:
554 break;
557 else if (ent->uses)
559 struct named_label_use_entry *use;
561 for (use = ent->uses; use ; use = use->next)
562 if (use->binding_level == bl)
564 use->binding_level = obl;
565 use->names_in_scope = obl->names;
566 if (bl->kind == sk_omp)
567 use->in_omp_scope = true;
571 return 1;
574 /* Saved errorcount to avoid -Wunused-but-set-{parameter,variable} warnings
575 when errors were reported, except for -Werror-unused-but-set-*. */
576 static int unused_but_set_errorcount;
578 /* Exit a binding level.
579 Pop the level off, and restore the state of the identifier-decl mappings
580 that were in effect when this level was entered.
582 If KEEP == 1, this level had explicit declarations, so
583 and create a "block" (a BLOCK node) for the level
584 to record its declarations and subblocks for symbol table output.
586 If FUNCTIONBODY is nonzero, this level is the body of a function,
587 so create a block as if KEEP were set and also clear out all
588 label names.
590 If REVERSE is nonzero, reverse the order of decls before putting
591 them into the BLOCK. */
593 tree
594 poplevel (int keep, int reverse, int functionbody)
596 tree link;
597 /* The chain of decls was accumulated in reverse order.
598 Put it into forward order, just for cleanliness. */
599 tree decls;
600 tree subblocks;
601 tree block;
602 tree decl;
603 scope_kind kind;
605 auto_cond_timevar tv (TV_NAME_LOOKUP);
606 restart:
608 block = NULL_TREE;
610 gcc_assert (current_binding_level->kind != sk_class
611 && current_binding_level->kind != sk_namespace);
613 if (current_binding_level->kind == sk_cleanup)
614 functionbody = 0;
615 subblocks = functionbody >= 0 ? current_binding_level->blocks : 0;
617 gcc_assert (!vec_safe_length (current_binding_level->class_shadowed));
619 /* We used to use KEEP == 2 to indicate that the new block should go
620 at the beginning of the list of blocks at this binding level,
621 rather than the end. This hack is no longer used. */
622 gcc_assert (keep == 0 || keep == 1);
624 if (current_binding_level->keep)
625 keep = 1;
627 /* Any uses of undefined labels, and any defined labels, now operate
628 under constraints of next binding contour. */
629 if (cfun && !functionbody && named_labels)
630 named_labels->traverse<cp_binding_level *, poplevel_named_label_1>
631 (current_binding_level);
633 /* Get the decls in the order they were written.
634 Usually current_binding_level->names is in reverse order.
635 But parameter decls were previously put in forward order. */
637 decls = current_binding_level->names;
638 if (reverse)
640 decls = nreverse (decls);
641 current_binding_level->names = decls;
644 /* If there were any declarations or structure tags in that level,
645 or if this level is a function body,
646 create a BLOCK to record them for the life of this function. */
647 block = NULL_TREE;
648 /* Avoid function body block if possible. */
649 if (functionbody && subblocks && BLOCK_CHAIN (subblocks) == NULL_TREE)
650 keep = 0;
651 else if (keep == 1 || functionbody)
652 block = make_node (BLOCK);
653 if (block != NULL_TREE)
655 BLOCK_VARS (block) = decls;
656 BLOCK_SUBBLOCKS (block) = subblocks;
659 /* In each subblock, record that this is its superior. */
660 if (keep >= 0)
661 for (link = subblocks; link; link = BLOCK_CHAIN (link))
662 BLOCK_SUPERCONTEXT (link) = block;
664 /* Before we remove the declarations first check for unused variables. */
665 if ((warn_unused_variable || warn_unused_but_set_variable)
666 && current_binding_level->kind != sk_template_parms
667 && !processing_template_decl)
668 for (tree d = get_local_decls (); d; d = TREE_CHAIN (d))
670 /* There are cases where D itself is a TREE_LIST. See in
671 push_local_binding where the list of decls returned by
672 getdecls is built. */
673 decl = TREE_CODE (d) == TREE_LIST ? TREE_VALUE (d) : d;
675 tree type = TREE_TYPE (decl);
676 if (VAR_P (decl)
677 && (! TREE_USED (decl) || !DECL_READ_P (decl))
678 && ! DECL_IN_SYSTEM_HEADER (decl)
679 /* For structured bindings, consider only real variables, not
680 subobjects. */
681 && (DECL_DECOMPOSITION_P (decl) ? !DECL_DECOMP_BASE (decl)
682 : (DECL_NAME (decl) && !DECL_ARTIFICIAL (decl)))
683 && type != error_mark_node
684 && (!CLASS_TYPE_P (type)
685 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
686 || lookup_attribute ("warn_unused",
687 TYPE_ATTRIBUTES (TREE_TYPE (decl)))))
689 if (! TREE_USED (decl))
691 if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
692 warning_at (DECL_SOURCE_LOCATION (decl),
693 OPT_Wunused_variable,
694 "unused structured binding declaration");
695 else
696 warning_at (DECL_SOURCE_LOCATION (decl),
697 OPT_Wunused_variable, "unused variable %qD", decl);
698 suppress_warning (decl, OPT_Wunused_variable);
700 else if (DECL_CONTEXT (decl) == current_function_decl
701 // For -Wunused-but-set-variable leave references alone.
702 && !TYPE_REF_P (TREE_TYPE (decl))
703 && errorcount == unused_but_set_errorcount)
705 if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
706 warning_at (DECL_SOURCE_LOCATION (decl),
707 OPT_Wunused_but_set_variable, "structured "
708 "binding declaration set but not used");
709 else
710 warning_at (DECL_SOURCE_LOCATION (decl),
711 OPT_Wunused_but_set_variable,
712 "variable %qD set but not used", decl);
713 unused_but_set_errorcount = errorcount;
718 /* Remove declarations for all the DECLs in this level. */
719 for (link = decls; link; link = TREE_CHAIN (link))
721 tree name;
722 if (TREE_CODE (link) == TREE_LIST)
724 decl = TREE_VALUE (link);
725 name = TREE_PURPOSE (link);
726 gcc_checking_assert (name);
728 else
730 decl = link;
731 name = DECL_NAME (decl);
734 /* Remove the binding. */
735 if (TREE_CODE (decl) == LABEL_DECL)
736 pop_local_label (name, decl);
737 else
738 pop_local_binding (name, decl);
741 /* Restore the IDENTIFIER_TYPE_VALUEs. */
742 for (link = current_binding_level->type_shadowed;
743 link; link = TREE_CHAIN (link))
744 SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (link), TREE_VALUE (link));
746 /* There may be OVERLOADs (wrapped in TREE_LISTs) on the BLOCK_VARs
747 list if a `using' declaration put them there. The debugging
748 back ends won't understand OVERLOAD, so we remove them here.
749 Because the BLOCK_VARS are (temporarily) shared with
750 CURRENT_BINDING_LEVEL->NAMES we must do this fixup after we have
751 popped all the bindings. Also remove undeduced 'auto' decls,
752 which LTO doesn't understand, and can't have been used by anything. */
753 if (block)
755 tree* d;
757 for (d = &BLOCK_VARS (block); *d; )
759 if (TREE_CODE (*d) == TREE_LIST
760 || (!processing_template_decl
761 && undeduced_auto_decl (*d)))
762 *d = TREE_CHAIN (*d);
763 else
764 d = &DECL_CHAIN (*d);
768 /* If the level being exited is the top level of a function,
769 check over all the labels. */
770 if (functionbody)
772 if (block)
774 /* Since this is the top level block of a function, the vars are
775 the function's parameters. Don't leave them in the BLOCK
776 because they are found in the FUNCTION_DECL instead. */
777 BLOCK_VARS (block) = 0;
778 pop_labels (block);
780 else
781 pop_labels (subblocks);
784 kind = current_binding_level->kind;
785 if (kind == sk_cleanup)
787 tree stmt;
789 /* If this is a temporary binding created for a cleanup, then we'll
790 have pushed a statement list level. Pop that, create a new
791 BIND_EXPR for the block, and insert it into the stream. */
792 stmt = pop_stmt_list (current_binding_level->statement_list);
793 stmt = c_build_bind_expr (input_location, block, stmt);
794 add_stmt (stmt);
797 leave_scope ();
798 if (functionbody)
800 /* The current function is being defined, so its DECL_INITIAL
801 should be error_mark_node. */
802 gcc_assert (DECL_INITIAL (current_function_decl) == error_mark_node);
803 DECL_INITIAL (current_function_decl) = block ? block : subblocks;
804 if (subblocks)
806 if (FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
808 if (BLOCK_SUBBLOCKS (subblocks))
809 BLOCK_OUTER_CURLY_BRACE_P (BLOCK_SUBBLOCKS (subblocks)) = 1;
811 else
812 BLOCK_OUTER_CURLY_BRACE_P (subblocks) = 1;
815 else if (block)
816 current_binding_level->blocks
817 = block_chainon (current_binding_level->blocks, block);
819 /* If we did not make a block for the level just exited,
820 any blocks made for inner levels
821 (since they cannot be recorded as subblocks in that level)
822 must be carried forward so they will later become subblocks
823 of something else. */
824 else if (subblocks)
825 current_binding_level->blocks
826 = block_chainon (current_binding_level->blocks, subblocks);
828 /* Each and every BLOCK node created here in `poplevel' is important
829 (e.g. for proper debugging information) so if we created one
830 earlier, mark it as "used". */
831 if (block)
832 TREE_USED (block) = 1;
834 /* All temporary bindings created for cleanups are popped silently. */
835 if (kind == sk_cleanup)
836 goto restart;
838 return block;
841 /* Call wrapup_globals_declarations for the globals in NAMESPACE. */
842 /* Diagnose odr-used extern inline variables without definitions
843 in the current TU. */
846 wrapup_namespace_globals ()
848 if (vec<tree, va_gc> *statics = static_decls)
850 for (tree decl : *statics)
852 if (warn_unused_function
853 && TREE_CODE (decl) == FUNCTION_DECL
854 && DECL_INITIAL (decl) == 0
855 && DECL_EXTERNAL (decl)
856 && !TREE_PUBLIC (decl)
857 && !DECL_ARTIFICIAL (decl)
858 && !DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
859 && !warning_suppressed_p (decl, OPT_Wunused_function))
860 warning_at (DECL_SOURCE_LOCATION (decl),
861 OPT_Wunused_function,
862 "%qF declared %<static%> but never defined", decl);
864 if (VAR_P (decl)
865 && DECL_EXTERNAL (decl)
866 && DECL_INLINE_VAR_P (decl)
867 && DECL_ODR_USED (decl))
868 error_at (DECL_SOURCE_LOCATION (decl),
869 "odr-used inline variable %qD is not defined", decl);
872 /* Clear out the list, so we don't rescan next time. */
873 static_decls = NULL;
875 /* Write out any globals that need to be output. */
876 return wrapup_global_declarations (statics->address (),
877 statics->length ());
879 return 0;
882 /* In C++, you don't have to write `struct S' to refer to `S'; you
883 can just use `S'. We accomplish this by creating a TYPE_DECL as
884 if the user had written `typedef struct S S'. Create and return
885 the TYPE_DECL for TYPE. */
887 tree
888 create_implicit_typedef (tree name, tree type)
890 tree decl;
892 decl = build_decl (input_location, TYPE_DECL, name, type);
893 DECL_ARTIFICIAL (decl) = 1;
894 /* There are other implicit type declarations, like the one *within*
895 a class that allows you to write `S::S'. We must distinguish
896 amongst these. */
897 SET_DECL_IMPLICIT_TYPEDEF_P (decl);
898 TYPE_NAME (type) = decl;
899 TYPE_STUB_DECL (type) = decl;
901 return decl;
904 /* Function-scope local entities that need discriminators. Each entry
905 is a {decl,name} pair. VAR_DECLs for anon unions get their name
906 smashed, so we cannot rely on DECL_NAME. */
908 static GTY((deletable)) vec<tree, va_gc> *local_entities;
910 /* Determine the mangling discriminator of local DECL. There are
911 generally very few of these in any particular function. */
913 void
914 determine_local_discriminator (tree decl)
916 auto_cond_timevar tv (TV_NAME_LOOKUP);
917 retrofit_lang_decl (decl);
918 tree ctx = DECL_CONTEXT (decl);
919 tree name = (TREE_CODE (decl) == TYPE_DECL
920 && TYPE_UNNAMED_P (TREE_TYPE (decl))
921 ? NULL_TREE : DECL_NAME (decl));
922 size_t nelts = vec_safe_length (local_entities);
923 for (size_t i = 0; i < nelts; i += 2)
925 tree *pair = &(*local_entities)[i];
926 tree d = pair[0];
927 tree n = pair[1];
928 gcc_checking_assert (d != decl);
929 if (name == n
930 && TREE_CODE (decl) == TREE_CODE (d)
931 && ctx == DECL_CONTEXT (d))
933 tree disc = integer_one_node;
934 if (DECL_DISCRIMINATOR (d))
935 disc = build_int_cst (TREE_TYPE (disc),
936 TREE_INT_CST_LOW (DECL_DISCRIMINATOR (d)) + 1);
937 DECL_DISCRIMINATOR (decl) = disc;
938 /* Replace the saved decl. */
939 pair[0] = decl;
940 decl = NULL_TREE;
941 break;
945 if (decl)
947 vec_safe_reserve (local_entities, 2);
948 local_entities->quick_push (decl);
949 local_entities->quick_push (name);
955 /* Returns true if functions FN1 and FN2 have equivalent trailing
956 requires clauses. */
958 static bool
959 function_requirements_equivalent_p (tree newfn, tree oldfn)
961 /* In the concepts TS, the combined constraints are compared. */
962 if (cxx_dialect < cxx20)
964 tree ci1 = get_constraints (oldfn);
965 tree ci2 = get_constraints (newfn);
966 tree req1 = ci1 ? CI_ASSOCIATED_CONSTRAINTS (ci1) : NULL_TREE;
967 tree req2 = ci2 ? CI_ASSOCIATED_CONSTRAINTS (ci2) : NULL_TREE;
968 return cp_tree_equal (req1, req2);
971 /* Compare only trailing requirements. */
972 tree reqs1 = get_trailing_function_requirements (newfn);
973 tree reqs2 = get_trailing_function_requirements (oldfn);
974 if ((reqs1 != NULL_TREE) != (reqs2 != NULL_TREE))
975 return false;
977 /* Substitution is needed when friends are involved. */
978 reqs1 = maybe_substitute_reqs_for (reqs1, newfn);
979 reqs2 = maybe_substitute_reqs_for (reqs2, oldfn);
981 return cp_tree_equal (reqs1, reqs2);
984 /* Two functions of the same name correspond [basic.scope.scope] if
986 + both declare functions with the same non-object-parameter-type-list,
987 equivalent ([temp.over.link]) trailing requires-clauses (if any, except as
988 specified in [temp.friend]), and, if both are non-static members, they have
989 corresponding object parameters, or
991 + both declare function templates with equivalent
992 non-object-parameter-type-lists, return types (if any), template-heads, and
993 trailing requires-clauses (if any), and, if both are non-static members,
994 they have corresponding object parameters.
996 This is a subset of decls_match: it identifies declarations that cannot be
997 overloaded with one another. This function does not consider DECL_NAME. */
999 bool
1000 fns_correspond (tree newdecl, tree olddecl)
1002 if (TREE_CODE (newdecl) != TREE_CODE (olddecl))
1003 return false;
1005 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1007 if (!template_heads_equivalent_p (newdecl, olddecl))
1008 return 0;
1009 newdecl = DECL_TEMPLATE_RESULT (newdecl);
1010 olddecl = DECL_TEMPLATE_RESULT (olddecl);
1013 tree f1 = TREE_TYPE (newdecl);
1014 tree f2 = TREE_TYPE (olddecl);
1016 int rq1 = type_memfn_rqual (f1);
1017 int rq2 = type_memfn_rqual (f2);
1019 /* If only one is a non-static member function, ignore ref-quals. */
1020 if (TREE_CODE (f1) != TREE_CODE (f2))
1021 rq1 = rq2;
1022 /* Two non-static member functions have corresponding object parameters if:
1023 + exactly one is an implicit object member function with no ref-qualifier
1024 and the types of their object parameters ([dcl.fct]), after removing
1025 top-level references, are the same, or
1026 + their object parameters have the same type. */
1027 /* ??? We treat member functions of different classes as corresponding even
1028 though that means the object parameters have different types. */
1029 else if ((rq1 == REF_QUAL_NONE) != (rq2 == REF_QUAL_NONE))
1030 rq1 = rq2;
1032 bool types_match = rq1 == rq2;
1034 if (types_match)
1036 tree p1 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1037 tree p2 = FUNCTION_FIRST_USER_PARMTYPE (olddecl);
1038 types_match = compparms (p1, p2);
1041 /* Two function declarations match if either has a requires-clause
1042 then both have a requires-clause and their constraints-expressions
1043 are equivalent. */
1044 if (types_match && flag_concepts)
1045 types_match = function_requirements_equivalent_p (newdecl, olddecl);
1047 return types_match;
1050 /* Subroutine of duplicate_decls: return truthvalue of whether
1051 or not types of these decls match.
1053 For C++, we must compare the parameter list so that `int' can match
1054 `int&' in a parameter position, but `int&' is not confused with
1055 `const int&'. */
1058 decls_match (tree newdecl, tree olddecl, bool record_versions /* = true */)
1060 int types_match;
1062 if (newdecl == olddecl)
1063 return 1;
1065 if (TREE_CODE (newdecl) != TREE_CODE (olddecl))
1066 /* If the two DECLs are not even the same kind of thing, we're not
1067 interested in their types. */
1068 return 0;
1070 gcc_assert (DECL_P (newdecl));
1072 if (TREE_CODE (newdecl) == FUNCTION_DECL)
1074 /* Specializations of different templates are different functions
1075 even if they have the same type. */
1076 tree t1 = (DECL_USE_TEMPLATE (newdecl)
1077 ? DECL_TI_TEMPLATE (newdecl)
1078 : NULL_TREE);
1079 tree t2 = (DECL_USE_TEMPLATE (olddecl)
1080 ? DECL_TI_TEMPLATE (olddecl)
1081 : NULL_TREE);
1082 if (t1 != t2)
1083 return 0;
1085 if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1086 && ! (DECL_EXTERN_C_P (newdecl)
1087 && DECL_EXTERN_C_P (olddecl)))
1088 return 0;
1090 /* A new declaration doesn't match a built-in one unless it
1091 is also extern "C". */
1092 if (DECL_IS_UNDECLARED_BUILTIN (olddecl)
1093 && DECL_EXTERN_C_P (olddecl) && !DECL_EXTERN_C_P (newdecl))
1094 return 0;
1096 tree f1 = TREE_TYPE (newdecl);
1097 tree f2 = TREE_TYPE (olddecl);
1098 if (TREE_CODE (f1) != TREE_CODE (f2))
1099 return 0;
1101 /* A declaration with deduced return type should use its pre-deduction
1102 type for declaration matching. */
1103 tree r2 = fndecl_declared_return_type (olddecl);
1104 tree r1 = fndecl_declared_return_type (newdecl);
1106 tree p1 = TYPE_ARG_TYPES (f1);
1107 tree p2 = TYPE_ARG_TYPES (f2);
1109 if (same_type_p (r1, r2))
1111 if (!prototype_p (f2) && DECL_EXTERN_C_P (olddecl)
1112 && fndecl_built_in_p (olddecl))
1114 types_match = self_promoting_args_p (p1);
1115 if (p1 == void_list_node)
1116 TREE_TYPE (newdecl) = TREE_TYPE (olddecl);
1118 else
1119 types_match =
1120 compparms (p1, p2)
1121 && type_memfn_rqual (f1) == type_memfn_rqual (f2)
1122 && (TYPE_ATTRIBUTES (TREE_TYPE (newdecl)) == NULL_TREE
1123 || comp_type_attributes (TREE_TYPE (newdecl),
1124 TREE_TYPE (olddecl)) != 0);
1126 else
1127 types_match = 0;
1129 /* Two function declarations match if either has a requires-clause
1130 then both have a requires-clause and their constraints-expressions
1131 are equivalent. */
1132 if (types_match && flag_concepts)
1133 types_match = function_requirements_equivalent_p (newdecl, olddecl);
1135 /* The decls dont match if they correspond to two different versions
1136 of the same function. Disallow extern "C" functions to be
1137 versions for now. */
1138 if (types_match
1139 && !DECL_EXTERN_C_P (newdecl)
1140 && !DECL_EXTERN_C_P (olddecl)
1141 && targetm.target_option.function_versions (newdecl, olddecl))
1143 if (record_versions)
1144 maybe_version_functions (newdecl, olddecl,
1145 (!DECL_FUNCTION_VERSIONED (newdecl)
1146 || !DECL_FUNCTION_VERSIONED (olddecl)));
1147 return 0;
1150 else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1152 if (!template_heads_equivalent_p (newdecl, olddecl))
1153 return 0;
1155 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1156 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1158 if (TREE_CODE (newres) != TREE_CODE (oldres))
1159 return 0;
1161 /* Two template types match if they are the same. Otherwise, compare
1162 the underlying declarations. */
1163 if (TREE_CODE (newres) == TYPE_DECL)
1164 types_match = same_type_p (TREE_TYPE (newres), TREE_TYPE (oldres));
1165 else
1166 types_match = decls_match (newres, oldres);
1168 else
1170 /* Need to check scope for variable declaration (VAR_DECL).
1171 For typedef (TYPE_DECL), scope is ignored. */
1172 if (VAR_P (newdecl)
1173 && CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1174 /* [dcl.link]
1175 Two declarations for an object with C language linkage
1176 with the same name (ignoring the namespace that qualify
1177 it) that appear in different namespace scopes refer to
1178 the same object. */
1179 && !(DECL_EXTERN_C_P (olddecl) && DECL_EXTERN_C_P (newdecl)))
1180 return 0;
1182 if (TREE_TYPE (newdecl) == error_mark_node)
1183 types_match = TREE_TYPE (olddecl) == error_mark_node;
1184 else if (TREE_TYPE (olddecl) == NULL_TREE)
1185 types_match = TREE_TYPE (newdecl) == NULL_TREE;
1186 else if (TREE_TYPE (newdecl) == NULL_TREE)
1187 types_match = 0;
1188 else
1189 types_match = comptypes (TREE_TYPE (newdecl),
1190 TREE_TYPE (olddecl),
1191 COMPARE_REDECLARATION);
1194 return types_match;
1197 /* Mark DECL as versioned if it isn't already. */
1199 static void
1200 maybe_mark_function_versioned (tree decl)
1202 if (!DECL_FUNCTION_VERSIONED (decl))
1204 DECL_FUNCTION_VERSIONED (decl) = 1;
1205 /* If DECL_ASSEMBLER_NAME has already been set, re-mangle
1206 to include the version marker. */
1207 if (DECL_ASSEMBLER_NAME_SET_P (decl))
1208 mangle_decl (decl);
1212 /* NEWDECL and OLDDECL have identical signatures. If they are
1213 different versions adjust them and return true.
1214 If RECORD is set to true, record function versions. */
1216 bool
1217 maybe_version_functions (tree newdecl, tree olddecl, bool record)
1219 if (!targetm.target_option.function_versions (newdecl, olddecl))
1220 return false;
1222 maybe_mark_function_versioned (olddecl);
1223 if (DECL_LOCAL_DECL_P (olddecl))
1225 olddecl = DECL_LOCAL_DECL_ALIAS (olddecl);
1226 maybe_mark_function_versioned (olddecl);
1229 maybe_mark_function_versioned (newdecl);
1230 if (DECL_LOCAL_DECL_P (newdecl))
1232 /* Unfortunately, we can get here before pushdecl naturally calls
1233 push_local_extern_decl_alias, so we need to call it directly. */
1234 if (!DECL_LOCAL_DECL_ALIAS (newdecl))
1235 push_local_extern_decl_alias (newdecl);
1236 newdecl = DECL_LOCAL_DECL_ALIAS (newdecl);
1237 maybe_mark_function_versioned (newdecl);
1240 if (record)
1241 cgraph_node::record_function_versions (olddecl, newdecl);
1243 return true;
1246 /* If NEWDECL is `static' and an `extern' was seen previously,
1247 warn about it. OLDDECL is the previous declaration.
1249 Note that this does not apply to the C++ case of declaring
1250 a variable `extern const' and then later `const'.
1252 Don't complain about built-in functions, since they are beyond
1253 the user's control. */
1255 void
1256 warn_extern_redeclared_static (tree newdecl, tree olddecl)
1258 if (TREE_CODE (newdecl) == TYPE_DECL
1259 || TREE_CODE (newdecl) == TEMPLATE_DECL
1260 || TREE_CODE (newdecl) == CONST_DECL
1261 || TREE_CODE (newdecl) == NAMESPACE_DECL)
1262 return;
1264 /* Don't get confused by static member functions; that's a different
1265 use of `static'. */
1266 if (TREE_CODE (newdecl) == FUNCTION_DECL
1267 && DECL_STATIC_FUNCTION_P (newdecl))
1268 return;
1270 /* If the old declaration was `static', or the new one isn't, then
1271 everything is OK. */
1272 if (DECL_THIS_STATIC (olddecl) || !DECL_THIS_STATIC (newdecl))
1273 return;
1275 /* It's OK to declare a builtin function as `static'. */
1276 if (TREE_CODE (olddecl) == FUNCTION_DECL
1277 && DECL_ARTIFICIAL (olddecl))
1278 return;
1280 auto_diagnostic_group d;
1281 if (permerror (DECL_SOURCE_LOCATION (newdecl),
1282 "%qD was declared %<extern%> and later %<static%>", newdecl))
1283 inform (DECL_SOURCE_LOCATION (olddecl),
1284 "previous declaration of %qD", olddecl);
1287 /* NEW_DECL is a redeclaration of OLD_DECL; both are functions or
1288 function templates. If their exception specifications do not
1289 match, issue a diagnostic. */
1291 static void
1292 check_redeclaration_exception_specification (tree new_decl,
1293 tree old_decl)
1295 tree new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1296 tree old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1298 /* Two default specs are equivalent, don't force evaluation. */
1299 if (UNEVALUATED_NOEXCEPT_SPEC_P (new_exceptions)
1300 && UNEVALUATED_NOEXCEPT_SPEC_P (old_exceptions))
1301 return;
1303 if (!type_dependent_expression_p (old_decl))
1305 maybe_instantiate_noexcept (new_decl);
1306 maybe_instantiate_noexcept (old_decl);
1308 new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1309 old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1311 /* [except.spec]
1313 If any declaration of a function has an exception-specification,
1314 all declarations, including the definition and an explicit
1315 specialization, of that function shall have an
1316 exception-specification with the same set of type-ids. */
1317 if (!DECL_IS_UNDECLARED_BUILTIN (old_decl)
1318 && !DECL_IS_UNDECLARED_BUILTIN (new_decl)
1319 && !comp_except_specs (new_exceptions, old_exceptions, ce_normal))
1321 const char *const msg
1322 = G_("declaration of %qF has a different exception specifier");
1323 bool complained = true;
1324 location_t new_loc = DECL_SOURCE_LOCATION (new_decl);
1325 auto_diagnostic_group d;
1326 if (DECL_IN_SYSTEM_HEADER (old_decl))
1327 complained = pedwarn (new_loc, OPT_Wsystem_headers, msg, new_decl);
1328 else if (!flag_exceptions)
1329 /* We used to silently permit mismatched eh specs with
1330 -fno-exceptions, so make them a pedwarn now. */
1331 complained = pedwarn (new_loc, OPT_Wpedantic, msg, new_decl);
1332 else
1333 error_at (new_loc, msg, new_decl);
1334 if (complained)
1335 inform (DECL_SOURCE_LOCATION (old_decl),
1336 "from previous declaration %qF", old_decl);
1340 /* Return true if OLD_DECL and NEW_DECL agree on constexprness.
1341 Otherwise issue diagnostics. */
1343 static bool
1344 validate_constexpr_redeclaration (tree old_decl, tree new_decl)
1346 old_decl = STRIP_TEMPLATE (old_decl);
1347 new_decl = STRIP_TEMPLATE (new_decl);
1348 if (!VAR_OR_FUNCTION_DECL_P (old_decl)
1349 || !VAR_OR_FUNCTION_DECL_P (new_decl))
1350 return true;
1351 if (DECL_DECLARED_CONSTEXPR_P (old_decl)
1352 == DECL_DECLARED_CONSTEXPR_P (new_decl))
1354 if (TREE_CODE (old_decl) != FUNCTION_DECL)
1355 return true;
1356 if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1357 == DECL_IMMEDIATE_FUNCTION_P (new_decl))
1358 return true;
1360 if (TREE_CODE (old_decl) == FUNCTION_DECL)
1362 /* With -fimplicit-constexpr, ignore changes in the constexpr
1363 keyword. */
1364 if (flag_implicit_constexpr
1365 && (DECL_IMMEDIATE_FUNCTION_P (new_decl)
1366 == DECL_IMMEDIATE_FUNCTION_P (old_decl)))
1367 return true;
1368 if (fndecl_built_in_p (old_decl))
1370 /* Hide a built-in declaration. */
1371 DECL_DECLARED_CONSTEXPR_P (old_decl)
1372 = DECL_DECLARED_CONSTEXPR_P (new_decl);
1373 if (DECL_IMMEDIATE_FUNCTION_P (new_decl))
1374 SET_DECL_IMMEDIATE_FUNCTION_P (old_decl);
1375 return true;
1377 /* 7.1.5 [dcl.constexpr]
1378 Note: An explicit specialization can differ from the template
1379 declaration with respect to the constexpr specifier. */
1380 if (! DECL_TEMPLATE_SPECIALIZATION (old_decl)
1381 && DECL_TEMPLATE_SPECIALIZATION (new_decl))
1382 return true;
1384 const char *kind = "constexpr";
1385 if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1386 || DECL_IMMEDIATE_FUNCTION_P (new_decl))
1387 kind = "consteval";
1388 error_at (DECL_SOURCE_LOCATION (new_decl),
1389 "redeclaration %qD differs in %qs "
1390 "from previous declaration", new_decl,
1391 kind);
1392 inform (DECL_SOURCE_LOCATION (old_decl),
1393 "previous declaration %qD", old_decl);
1394 return false;
1396 return true;
1399 // If OLDDECL and NEWDECL are concept declarations with the same type
1400 // (i.e., and template parameters), but different requirements,
1401 // emit diagnostics and return true. Otherwise, return false.
1402 static inline bool
1403 check_concept_refinement (tree olddecl, tree newdecl)
1405 if (!DECL_DECLARED_CONCEPT_P (olddecl) || !DECL_DECLARED_CONCEPT_P (newdecl))
1406 return false;
1408 tree d1 = DECL_TEMPLATE_RESULT (olddecl);
1409 tree d2 = DECL_TEMPLATE_RESULT (newdecl);
1410 if (TREE_CODE (d1) != TREE_CODE (d2))
1411 return false;
1413 tree t1 = TREE_TYPE (d1);
1414 tree t2 = TREE_TYPE (d2);
1415 if (TREE_CODE (d1) == FUNCTION_DECL)
1417 if (compparms (TYPE_ARG_TYPES (t1), TYPE_ARG_TYPES (t2))
1418 && comp_template_parms (DECL_TEMPLATE_PARMS (olddecl),
1419 DECL_TEMPLATE_PARMS (newdecl))
1420 && !equivalently_constrained (olddecl, newdecl))
1422 error ("cannot specialize concept %q#D", olddecl);
1423 return true;
1426 return false;
1429 /* DECL is a redeclaration of a function or function template. If
1430 it does have default arguments issue a diagnostic. Note: this
1431 function is used to enforce the requirements in C++11 8.3.6 about
1432 no default arguments in redeclarations. */
1434 static void
1435 check_redeclaration_no_default_args (tree decl)
1437 gcc_assert (DECL_DECLARES_FUNCTION_P (decl));
1439 for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
1440 t && t != void_list_node; t = TREE_CHAIN (t))
1441 if (TREE_PURPOSE (t))
1443 permerror (DECL_SOURCE_LOCATION (decl),
1444 "redeclaration of %q#D may not have default "
1445 "arguments", decl);
1446 return;
1450 /* NEWDECL is a redeclaration of a function or function template OLDDECL,
1451 in any case represented as FUNCTION_DECLs (the DECL_TEMPLATE_RESULTs of
1452 the TEMPLATE_DECLs in case of function templates). This function is used
1453 to enforce the final part of C++17 11.3.6/4, about a single declaration:
1454 "If a friend declaration specifies a default argument expression, that
1455 declaration shall be a definition and shall be the only declaration of
1456 the function or function template in the translation unit." */
1458 static void
1459 check_no_redeclaration_friend_default_args (tree olddecl, tree newdecl)
1461 if (!DECL_UNIQUE_FRIEND_P (olddecl) && !DECL_UNIQUE_FRIEND_P (newdecl))
1462 return;
1464 for (tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl),
1465 t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1466 t1 && t1 != void_list_node;
1467 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1468 if ((DECL_UNIQUE_FRIEND_P (olddecl) && TREE_PURPOSE (t1))
1469 || (DECL_UNIQUE_FRIEND_P (newdecl) && TREE_PURPOSE (t2)))
1471 auto_diagnostic_group d;
1472 if (permerror (DECL_SOURCE_LOCATION (newdecl),
1473 "friend declaration of %q#D specifies default "
1474 "arguments and isn%'t the only declaration", newdecl))
1475 inform (DECL_SOURCE_LOCATION (olddecl),
1476 "previous declaration of %q#D", olddecl);
1477 return;
1481 /* Merge tree bits that correspond to attributes noreturn, nothrow,
1482 const, malloc, and pure from NEWDECL with those of OLDDECL. */
1484 static void
1485 merge_attribute_bits (tree newdecl, tree olddecl)
1487 TREE_THIS_VOLATILE (newdecl) |= TREE_THIS_VOLATILE (olddecl);
1488 TREE_THIS_VOLATILE (olddecl) |= TREE_THIS_VOLATILE (newdecl);
1489 TREE_NOTHROW (newdecl) |= TREE_NOTHROW (olddecl);
1490 TREE_NOTHROW (olddecl) |= TREE_NOTHROW (newdecl);
1491 TREE_READONLY (newdecl) |= TREE_READONLY (olddecl);
1492 TREE_READONLY (olddecl) |= TREE_READONLY (newdecl);
1493 DECL_IS_MALLOC (newdecl) |= DECL_IS_MALLOC (olddecl);
1494 DECL_IS_MALLOC (olddecl) |= DECL_IS_MALLOC (newdecl);
1495 DECL_PURE_P (newdecl) |= DECL_PURE_P (olddecl);
1496 DECL_PURE_P (olddecl) |= DECL_PURE_P (newdecl);
1497 DECL_UNINLINABLE (newdecl) |= DECL_UNINLINABLE (olddecl);
1498 DECL_UNINLINABLE (olddecl) |= DECL_UNINLINABLE (newdecl);
1501 #define GNU_INLINE_P(fn) (DECL_DECLARED_INLINE_P (fn) \
1502 && lookup_attribute ("gnu_inline", \
1503 DECL_ATTRIBUTES (fn)))
1505 /* A subroutine of duplicate_decls. Emits a diagnostic when newdecl
1506 ambiguates olddecl. Returns true if an error occurs. */
1508 static bool
1509 duplicate_function_template_decls (tree newdecl, tree olddecl)
1512 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1513 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1514 /* Function template declarations can be differentiated by parameter
1515 and return type. */
1516 if (compparms (TYPE_ARG_TYPES (TREE_TYPE (oldres)),
1517 TYPE_ARG_TYPES (TREE_TYPE (newres)))
1518 && same_type_p (TREE_TYPE (TREE_TYPE (newdecl)),
1519 TREE_TYPE (TREE_TYPE (olddecl))))
1521 /* ... and also by their template-heads and requires-clauses. */
1522 if (template_heads_equivalent_p (newdecl, olddecl)
1523 && function_requirements_equivalent_p (newres, oldres))
1525 error ("ambiguating new declaration %q+#D", newdecl);
1526 inform (DECL_SOURCE_LOCATION (olddecl),
1527 "old declaration %q#D", olddecl);
1528 return true;
1531 /* FIXME: The types are the same but the are differences
1532 in either the template heads or function requirements.
1533 We should be able to diagnose a set of common errors
1534 stemming from these declarations. For example:
1536 template<typename T> requires C void f(...);
1537 template<typename T> void f(...) requires C;
1539 These are functionally equivalent but not equivalent. */
1542 return false;
1545 /* OLD_PARMS is the innermost set of template parameters for some template
1546 declaration, and NEW_PARMS is the corresponding set of template parameters
1547 for a redeclaration of that template. Merge the default arguments within
1548 these two sets of parameters. CLASS_P is true iff the template in
1549 question is a class template. */
1551 bool
1552 merge_default_template_args (tree new_parms, tree old_parms, bool class_p)
1554 gcc_checking_assert (TREE_VEC_LENGTH (new_parms)
1555 == TREE_VEC_LENGTH (old_parms));
1556 for (int i = 0; i < TREE_VEC_LENGTH (new_parms); i++)
1558 tree new_parm = TREE_VALUE (TREE_VEC_ELT (new_parms, i));
1559 tree old_parm = TREE_VALUE (TREE_VEC_ELT (old_parms, i));
1560 tree& new_default = TREE_PURPOSE (TREE_VEC_ELT (new_parms, i));
1561 tree& old_default = TREE_PURPOSE (TREE_VEC_ELT (old_parms, i));
1562 if (error_operand_p (new_parm) || error_operand_p (old_parm))
1563 return false;
1564 if (new_default != NULL_TREE && old_default != NULL_TREE)
1566 auto_diagnostic_group d;
1567 error ("redefinition of default argument for %q+#D", new_parm);
1568 inform (DECL_SOURCE_LOCATION (old_parm),
1569 "original definition appeared here");
1570 return false;
1572 else if (new_default != NULL_TREE)
1573 /* Update the previous template parameters (which are the ones
1574 that will really count) with the new default value. */
1575 old_default = new_default;
1576 else if (class_p && old_default != NULL_TREE)
1577 /* Update the new parameters, too; they'll be used as the
1578 parameters for any members. */
1579 new_default = old_default;
1581 return true;
1584 /* If NEWDECL is a redeclaration of OLDDECL, merge the declarations.
1585 If the redeclaration is invalid, a diagnostic is issued, and the
1586 error_mark_node is returned. Otherwise, OLDDECL is returned.
1588 If NEWDECL is not a redeclaration of OLDDECL, NULL_TREE is
1589 returned.
1591 HIDING is true if the new decl is being hidden. WAS_HIDDEN is true
1592 if the old decl was hidden.
1594 Hidden decls can be anticipated builtins, injected friends, or
1595 (coming soon) injected from a local-extern decl. */
1597 tree
1598 duplicate_decls (tree newdecl, tree olddecl, bool hiding, bool was_hidden)
1600 unsigned olddecl_uid = DECL_UID (olddecl);
1601 int types_match = 0;
1602 int new_defines_function = 0;
1603 tree new_template_info;
1604 location_t olddecl_loc = DECL_SOURCE_LOCATION (olddecl);
1605 location_t newdecl_loc = DECL_SOURCE_LOCATION (newdecl);
1607 if (newdecl == olddecl)
1608 return olddecl;
1610 types_match = decls_match (newdecl, olddecl);
1612 /* If either the type of the new decl or the type of the old decl is an
1613 error_mark_node, then that implies that we have already issued an
1614 error (earlier) for some bogus type specification, and in that case,
1615 it is rather pointless to harass the user with yet more error message
1616 about the same declaration, so just pretend the types match here. */
1617 if (TREE_TYPE (newdecl) == error_mark_node
1618 || TREE_TYPE (olddecl) == error_mark_node)
1619 return error_mark_node;
1621 /* Check for redeclaration and other discrepancies. */
1622 if (TREE_CODE (olddecl) == FUNCTION_DECL
1623 && DECL_IS_UNDECLARED_BUILTIN (olddecl))
1625 if (TREE_CODE (newdecl) != FUNCTION_DECL)
1627 /* Avoid warnings redeclaring built-ins which have not been
1628 explicitly declared. */
1629 if (was_hidden)
1631 if (TREE_PUBLIC (newdecl)
1632 && CP_DECL_CONTEXT (newdecl) == global_namespace)
1633 warning_at (newdecl_loc,
1634 OPT_Wbuiltin_declaration_mismatch,
1635 "built-in function %qD declared as non-function",
1636 newdecl);
1637 return NULL_TREE;
1640 /* If you declare a built-in or predefined function name as static,
1641 the old definition is overridden, but optionally warn this was a
1642 bad choice of name. */
1643 if (! TREE_PUBLIC (newdecl))
1645 warning_at (newdecl_loc,
1646 OPT_Wshadow,
1647 fndecl_built_in_p (olddecl)
1648 ? G_("shadowing built-in function %q#D")
1649 : G_("shadowing library function %q#D"), olddecl);
1650 /* Discard the old built-in function. */
1651 return NULL_TREE;
1653 /* If the built-in is not ansi, then programs can override
1654 it even globally without an error. */
1655 else if (! fndecl_built_in_p (olddecl))
1656 warning_at (newdecl_loc, 0,
1657 "library function %q#D redeclared as non-function %q#D",
1658 olddecl, newdecl);
1659 else
1660 error_at (newdecl_loc,
1661 "declaration of %q#D conflicts with built-in "
1662 "declaration %q#D", newdecl, olddecl);
1663 return NULL_TREE;
1665 else if (!types_match)
1667 /* Avoid warnings redeclaring built-ins which have not been
1668 explicitly declared. */
1669 if (was_hidden)
1671 tree t1, t2;
1673 /* A new declaration doesn't match a built-in one unless it
1674 is also extern "C". */
1675 gcc_assert (DECL_IS_UNDECLARED_BUILTIN (olddecl));
1676 gcc_assert (DECL_EXTERN_C_P (olddecl));
1677 if (!DECL_EXTERN_C_P (newdecl))
1678 return NULL_TREE;
1680 for (t1 = TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1681 t2 = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1682 t1 || t2;
1683 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1685 if (!t1 || !t2)
1686 break;
1687 /* FILE, tm types are not known at the time
1688 we create the builtins. */
1689 for (unsigned i = 0;
1690 i < sizeof (builtin_structptr_types)
1691 / sizeof (builtin_structptr_type);
1692 ++i)
1693 if (TREE_VALUE (t2) == builtin_structptr_types[i].node)
1695 tree t = TREE_VALUE (t1);
1697 if (TYPE_PTR_P (t)
1698 && TYPE_IDENTIFIER (TREE_TYPE (t))
1699 == get_identifier (builtin_structptr_types[i].str)
1700 && compparms (TREE_CHAIN (t1), TREE_CHAIN (t2)))
1702 tree oldargs = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1704 TYPE_ARG_TYPES (TREE_TYPE (olddecl))
1705 = TYPE_ARG_TYPES (TREE_TYPE (newdecl));
1706 types_match = decls_match (newdecl, olddecl);
1707 if (types_match)
1708 return duplicate_decls (newdecl, olddecl,
1709 hiding, was_hidden);
1710 TYPE_ARG_TYPES (TREE_TYPE (olddecl)) = oldargs;
1712 goto next_arg;
1715 if (! same_type_p (TREE_VALUE (t1), TREE_VALUE (t2)))
1716 break;
1717 next_arg:;
1720 warning_at (newdecl_loc,
1721 OPT_Wbuiltin_declaration_mismatch,
1722 "declaration of %q#D conflicts with built-in "
1723 "declaration %q#D", newdecl, olddecl);
1725 else if ((DECL_EXTERN_C_P (newdecl)
1726 && DECL_EXTERN_C_P (olddecl))
1727 || compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1728 TYPE_ARG_TYPES (TREE_TYPE (olddecl))))
1730 /* Don't really override olddecl for __* prefixed builtins
1731 except for __[^b]*_chk, the compiler might be using those
1732 explicitly. */
1733 if (fndecl_built_in_p (olddecl))
1735 tree id = DECL_NAME (olddecl);
1736 const char *name = IDENTIFIER_POINTER (id);
1737 size_t len;
1739 if (name[0] == '_'
1740 && name[1] == '_'
1741 && (startswith (name + 2, "builtin_")
1742 || (len = strlen (name)) <= strlen ("___chk")
1743 || memcmp (name + len - strlen ("_chk"),
1744 "_chk", strlen ("_chk") + 1) != 0))
1746 if (DECL_INITIAL (newdecl))
1748 error_at (newdecl_loc,
1749 "definition of %q#D ambiguates built-in "
1750 "declaration %q#D", newdecl, olddecl);
1751 return error_mark_node;
1753 auto_diagnostic_group d;
1754 if (permerror (newdecl_loc,
1755 "new declaration %q#D ambiguates built-in"
1756 " declaration %q#D", newdecl, olddecl)
1757 && flag_permissive)
1758 inform (newdecl_loc,
1759 "ignoring the %q#D declaration", newdecl);
1760 return flag_permissive ? olddecl : error_mark_node;
1764 /* A near match; override the builtin. */
1766 if (TREE_PUBLIC (newdecl))
1767 warning_at (newdecl_loc,
1768 OPT_Wbuiltin_declaration_mismatch,
1769 "new declaration %q#D ambiguates built-in "
1770 "declaration %q#D", newdecl, olddecl);
1771 else
1772 warning (OPT_Wshadow,
1773 fndecl_built_in_p (olddecl)
1774 ? G_("shadowing built-in function %q#D")
1775 : G_("shadowing library function %q#D"), olddecl);
1777 else
1778 /* Discard the old built-in function. */
1779 return NULL_TREE;
1781 /* Replace the old RTL to avoid problems with inlining. */
1782 COPY_DECL_RTL (newdecl, olddecl);
1784 else
1786 /* Even if the types match, prefer the new declarations type
1787 for built-ins which have not been explicitly declared,
1788 for exception lists, etc... */
1789 tree type = TREE_TYPE (newdecl);
1790 tree attribs = (*targetm.merge_type_attributes)
1791 (TREE_TYPE (olddecl), type);
1793 type = cp_build_type_attribute_variant (type, attribs);
1794 TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = type;
1797 /* If a function is explicitly declared "throw ()", propagate that to
1798 the corresponding builtin. */
1799 if (DECL_BUILT_IN_CLASS (olddecl) == BUILT_IN_NORMAL
1800 && was_hidden
1801 && TREE_NOTHROW (newdecl)
1802 && !TREE_NOTHROW (olddecl))
1804 enum built_in_function fncode = DECL_FUNCTION_CODE (olddecl);
1805 tree tmpdecl = builtin_decl_explicit (fncode);
1806 if (tmpdecl && tmpdecl != olddecl && types_match)
1807 TREE_NOTHROW (tmpdecl) = 1;
1810 /* Whether or not the builtin can throw exceptions has no
1811 bearing on this declarator. */
1812 TREE_NOTHROW (olddecl) = 0;
1814 if (DECL_THIS_STATIC (newdecl) && !DECL_THIS_STATIC (olddecl))
1816 /* If a builtin function is redeclared as `static', merge
1817 the declarations, but make the original one static. */
1818 DECL_THIS_STATIC (olddecl) = 1;
1819 TREE_PUBLIC (olddecl) = 0;
1821 /* Make the old declaration consistent with the new one so
1822 that all remnants of the builtin-ness of this function
1823 will be banished. */
1824 SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
1825 COPY_DECL_RTL (newdecl, olddecl);
1828 else if (TREE_CODE (olddecl) != TREE_CODE (newdecl))
1830 /* C++ Standard, 3.3, clause 4:
1831 "[Note: a namespace name or a class template name must be unique
1832 in its declarative region (7.3.2, clause 14). ]" */
1833 if (TREE_CODE (olddecl) == NAMESPACE_DECL
1834 || TREE_CODE (newdecl) == NAMESPACE_DECL)
1835 /* Namespace conflicts with not namespace. */;
1836 else if (DECL_TYPE_TEMPLATE_P (olddecl)
1837 || DECL_TYPE_TEMPLATE_P (newdecl))
1838 /* Class template conflicts. */;
1839 else if ((TREE_CODE (olddecl) == TEMPLATE_DECL
1840 && DECL_TEMPLATE_RESULT (olddecl)
1841 && TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)) == VAR_DECL)
1842 || (TREE_CODE (newdecl) == TEMPLATE_DECL
1843 && DECL_TEMPLATE_RESULT (newdecl)
1844 && TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == VAR_DECL))
1845 /* Variable template conflicts. */;
1846 else if (concept_definition_p (olddecl)
1847 || concept_definition_p (newdecl))
1848 /* Concept conflicts. */;
1849 else if ((TREE_CODE (newdecl) == FUNCTION_DECL
1850 && DECL_FUNCTION_TEMPLATE_P (olddecl))
1851 || (TREE_CODE (olddecl) == FUNCTION_DECL
1852 && DECL_FUNCTION_TEMPLATE_P (newdecl)))
1854 /* One is a function and the other is a template
1855 function. */
1856 if (!UDLIT_OPER_P (DECL_NAME (newdecl)))
1857 return NULL_TREE;
1859 /* There can only be one! */
1860 if (TREE_CODE (newdecl) == TEMPLATE_DECL
1861 && check_raw_literal_operator (olddecl))
1862 error_at (newdecl_loc,
1863 "literal operator %q#D conflicts with"
1864 " raw literal operator", newdecl);
1865 else if (check_raw_literal_operator (newdecl))
1866 error_at (newdecl_loc,
1867 "raw literal operator %q#D conflicts with"
1868 " literal operator template", newdecl);
1869 else
1870 return NULL_TREE;
1872 inform (olddecl_loc, "previous declaration %q#D", olddecl);
1873 return error_mark_node;
1875 else if ((VAR_P (olddecl) && DECL_DECOMPOSITION_P (olddecl))
1876 || (VAR_P (newdecl) && DECL_DECOMPOSITION_P (newdecl)))
1877 /* A structured binding must be unique in its declarative region. */;
1878 else if (DECL_IMPLICIT_TYPEDEF_P (olddecl)
1879 || DECL_IMPLICIT_TYPEDEF_P (newdecl))
1880 /* One is an implicit typedef, that's ok. */
1881 return NULL_TREE;
1883 error ("%q#D redeclared as different kind of entity", newdecl);
1884 inform (olddecl_loc, "previous declaration %q#D", olddecl);
1886 return error_mark_node;
1888 else if (!types_match)
1890 if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl))
1891 /* These are certainly not duplicate declarations; they're
1892 from different scopes. */
1893 return NULL_TREE;
1895 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1897 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1898 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1900 /* The name of a class template may not be declared to refer to
1901 any other template, class, function, object, namespace, value,
1902 or type in the same scope. */
1903 if (TREE_CODE (oldres) == TYPE_DECL
1904 || TREE_CODE (newres) == TYPE_DECL)
1906 error_at (newdecl_loc,
1907 "conflicting declaration of template %q#D", newdecl);
1908 inform (olddecl_loc,
1909 "previous declaration %q#D", olddecl);
1910 return error_mark_node;
1913 else if (TREE_CODE (oldres) == FUNCTION_DECL
1914 && TREE_CODE (newres) == FUNCTION_DECL)
1916 if (duplicate_function_template_decls (newdecl, olddecl))
1917 return error_mark_node;
1918 return NULL_TREE;
1920 else if (check_concept_refinement (olddecl, newdecl))
1921 return error_mark_node;
1922 return NULL_TREE;
1924 if (TREE_CODE (newdecl) == FUNCTION_DECL)
1926 if (DECL_EXTERN_C_P (newdecl) && DECL_EXTERN_C_P (olddecl))
1928 error_at (newdecl_loc,
1929 "conflicting declaration of C function %q#D",
1930 newdecl);
1931 inform (olddecl_loc,
1932 "previous declaration %q#D", olddecl);
1933 return error_mark_node;
1935 /* For function versions, params and types match, but they
1936 are not ambiguous. */
1937 else if ((!DECL_FUNCTION_VERSIONED (newdecl)
1938 && !DECL_FUNCTION_VERSIONED (olddecl))
1939 // The functions have the same parameter types.
1940 && compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1941 TYPE_ARG_TYPES (TREE_TYPE (olddecl)))
1942 // And the same constraints.
1943 && equivalently_constrained (newdecl, olddecl))
1945 error_at (newdecl_loc,
1946 "ambiguating new declaration of %q#D", newdecl);
1947 inform (olddecl_loc,
1948 "old declaration %q#D", olddecl);
1949 return error_mark_node;
1951 else
1952 return NULL_TREE;
1954 else
1956 error_at (newdecl_loc, "conflicting declaration %q#D", newdecl);
1957 inform (olddecl_loc,
1958 "previous declaration as %q#D", olddecl);
1959 return error_mark_node;
1962 else if (TREE_CODE (newdecl) == FUNCTION_DECL
1963 && DECL_OMP_DECLARE_REDUCTION_P (newdecl))
1965 /* OMP UDRs are never duplicates. */
1966 gcc_assert (DECL_OMP_DECLARE_REDUCTION_P (olddecl));
1967 error_at (newdecl_loc,
1968 "redeclaration of %<pragma omp declare reduction%>");
1969 inform (olddecl_loc,
1970 "previous %<pragma omp declare reduction%> declaration");
1971 return error_mark_node;
1973 else if (TREE_CODE (newdecl) == FUNCTION_DECL
1974 && ((DECL_TEMPLATE_SPECIALIZATION (olddecl)
1975 && (!DECL_TEMPLATE_INFO (newdecl)
1976 || (DECL_TI_TEMPLATE (newdecl)
1977 != DECL_TI_TEMPLATE (olddecl))))
1978 || (DECL_TEMPLATE_SPECIALIZATION (newdecl)
1979 && (!DECL_TEMPLATE_INFO (olddecl)
1980 || (DECL_TI_TEMPLATE (olddecl)
1981 != DECL_TI_TEMPLATE (newdecl))))))
1982 /* It's OK to have a template specialization and a non-template
1983 with the same type, or to have specializations of two
1984 different templates with the same type. Note that if one is a
1985 specialization, and the other is an instantiation of the same
1986 template, that we do not exit at this point. That situation
1987 can occur if we instantiate a template class, and then
1988 specialize one of its methods. This situation is valid, but
1989 the declarations must be merged in the usual way. */
1990 return NULL_TREE;
1991 else if (TREE_CODE (newdecl) == FUNCTION_DECL
1992 && ((DECL_TEMPLATE_INSTANTIATION (olddecl)
1993 && !DECL_USE_TEMPLATE (newdecl))
1994 || (DECL_TEMPLATE_INSTANTIATION (newdecl)
1995 && !DECL_USE_TEMPLATE (olddecl))))
1996 /* One of the declarations is a template instantiation, and the
1997 other is not a template at all. That's OK. */
1998 return NULL_TREE;
1999 else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
2001 /* In [namespace.alias] we have:
2003 In a declarative region, a namespace-alias-definition can be
2004 used to redefine a namespace-alias declared in that declarative
2005 region to refer only to the namespace to which it already
2006 refers.
2008 Therefore, if we encounter a second alias directive for the same
2009 alias, we can just ignore the second directive. */
2010 if (DECL_NAMESPACE_ALIAS (newdecl)
2011 && (DECL_NAMESPACE_ALIAS (newdecl)
2012 == DECL_NAMESPACE_ALIAS (olddecl)))
2013 return olddecl;
2015 /* Leave it to update_binding to merge or report error. */
2016 return NULL_TREE;
2018 else
2020 const char *errmsg = redeclaration_error_message (newdecl, olddecl);
2021 if (errmsg)
2023 auto_diagnostic_group d;
2024 error_at (newdecl_loc, errmsg, newdecl);
2025 if (DECL_NAME (olddecl) != NULL_TREE)
2026 inform (olddecl_loc,
2027 (DECL_INITIAL (olddecl) && namespace_bindings_p ())
2028 ? G_("%q#D previously defined here")
2029 : G_("%q#D previously declared here"), olddecl);
2030 return error_mark_node;
2032 else if (TREE_CODE (olddecl) == FUNCTION_DECL
2033 && DECL_INITIAL (olddecl) != NULL_TREE
2034 && !prototype_p (TREE_TYPE (olddecl))
2035 && prototype_p (TREE_TYPE (newdecl)))
2037 /* Prototype decl follows defn w/o prototype. */
2038 auto_diagnostic_group d;
2039 if (warning_at (newdecl_loc, 0,
2040 "prototype specified for %q#D", newdecl))
2041 inform (olddecl_loc,
2042 "previous non-prototype definition here");
2044 else if (VAR_OR_FUNCTION_DECL_P (olddecl)
2045 && DECL_LANGUAGE (newdecl) != DECL_LANGUAGE (olddecl))
2047 /* [dcl.link]
2048 If two declarations of the same function or object
2049 specify different linkage-specifications ..., the program
2050 is ill-formed.... Except for functions with C++ linkage,
2051 a function declaration without a linkage specification
2052 shall not precede the first linkage specification for
2053 that function. A function can be declared without a
2054 linkage specification after an explicit linkage
2055 specification has been seen; the linkage explicitly
2056 specified in the earlier declaration is not affected by
2057 such a function declaration.
2059 DR 563 raises the question why the restrictions on
2060 functions should not also apply to objects. Older
2061 versions of G++ silently ignore the linkage-specification
2062 for this example:
2064 namespace N {
2065 extern int i;
2066 extern "C" int i;
2069 which is clearly wrong. Therefore, we now treat objects
2070 like functions. */
2071 if (current_lang_depth () == 0)
2073 /* There is no explicit linkage-specification, so we use
2074 the linkage from the previous declaration. */
2075 retrofit_lang_decl (newdecl);
2076 SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
2078 else
2080 auto_diagnostic_group d;
2081 error_at (newdecl_loc,
2082 "conflicting declaration of %q#D with %qL linkage",
2083 newdecl, DECL_LANGUAGE (newdecl));
2084 inform (olddecl_loc,
2085 "previous declaration with %qL linkage",
2086 DECL_LANGUAGE (olddecl));
2090 if (DECL_LANG_SPECIFIC (olddecl) && DECL_USE_TEMPLATE (olddecl))
2092 else if (TREE_CODE (olddecl) == FUNCTION_DECL)
2094 /* Note: free functions, as TEMPLATE_DECLs, are handled below. */
2095 if (DECL_FUNCTION_MEMBER_P (olddecl)
2096 && (/* grokfndecl passes member function templates too
2097 as FUNCTION_DECLs. */
2098 DECL_TEMPLATE_INFO (olddecl)
2099 /* C++11 8.3.6/6.
2100 Default arguments for a member function of a class
2101 template shall be specified on the initial declaration
2102 of the member function within the class template. */
2103 || CLASSTYPE_TEMPLATE_INFO (CP_DECL_CONTEXT (olddecl))))
2105 check_redeclaration_no_default_args (newdecl);
2107 if (DECL_TEMPLATE_INFO (olddecl)
2108 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (olddecl)))
2110 tree new_parms = DECL_TEMPLATE_INFO (newdecl)
2111 ? DECL_INNERMOST_TEMPLATE_PARMS (DECL_TI_TEMPLATE (newdecl))
2112 : INNERMOST_TEMPLATE_PARMS (current_template_parms);
2113 tree old_parms
2114 = DECL_INNERMOST_TEMPLATE_PARMS (DECL_TI_TEMPLATE (olddecl));
2115 merge_default_template_args (new_parms, old_parms,
2116 /*class_p=*/false);
2119 else
2121 tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl);
2122 tree t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
2123 int i = 1;
2125 for (; t1 && t1 != void_list_node;
2126 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2), i++)
2127 if (TREE_PURPOSE (t1) && TREE_PURPOSE (t2))
2129 if (simple_cst_equal (TREE_PURPOSE (t1),
2130 TREE_PURPOSE (t2)) == 1)
2132 auto_diagnostic_group d;
2133 if (permerror (newdecl_loc,
2134 "default argument given for parameter "
2135 "%d of %q#D", i, newdecl))
2136 inform (olddecl_loc,
2137 "previous specification in %q#D here",
2138 olddecl);
2140 else
2142 auto_diagnostic_group d;
2143 error_at (newdecl_loc,
2144 "default argument given for parameter %d "
2145 "of %q#D", i, newdecl);
2146 inform (olddecl_loc,
2147 "previous specification in %q#D here",
2148 olddecl);
2152 /* C++17 11.3.6/4: "If a friend declaration specifies a default
2153 argument expression, that declaration... shall be the only
2154 declaration of the function or function template in the
2155 translation unit." */
2156 check_no_redeclaration_friend_default_args (olddecl, newdecl);
2161 /* Do not merge an implicit typedef with an explicit one. In:
2163 class A;
2165 typedef class A A __attribute__ ((foo));
2167 the attribute should apply only to the typedef. */
2168 if (TREE_CODE (olddecl) == TYPE_DECL
2169 && (DECL_IMPLICIT_TYPEDEF_P (olddecl)
2170 || DECL_IMPLICIT_TYPEDEF_P (newdecl)))
2171 return NULL_TREE;
2173 if (DECL_TEMPLATE_PARM_P (olddecl) != DECL_TEMPLATE_PARM_P (newdecl))
2174 return NULL_TREE;
2176 if (!validate_constexpr_redeclaration (olddecl, newdecl))
2177 return error_mark_node;
2179 if (modules_p ()
2180 && TREE_CODE (CP_DECL_CONTEXT (olddecl)) == NAMESPACE_DECL
2181 && TREE_CODE (olddecl) != NAMESPACE_DECL
2182 && !hiding)
2184 if (!module_may_redeclare (olddecl))
2186 if (DECL_ARTIFICIAL (olddecl))
2187 error ("declaration %qD conflicts with builtin", newdecl);
2188 else
2190 error ("declaration %qD conflicts with import", newdecl);
2191 inform (olddecl_loc, "import declared %q#D here", olddecl);
2194 return error_mark_node;
2197 tree not_tmpl = STRIP_TEMPLATE (olddecl);
2198 if (DECL_LANG_SPECIFIC (not_tmpl) && DECL_MODULE_ATTACH_P (not_tmpl))
2200 if (DECL_MODULE_EXPORT_P (STRIP_TEMPLATE (newdecl))
2201 && !DECL_MODULE_EXPORT_P (not_tmpl))
2203 error ("conflicting exporting declaration %qD", newdecl);
2204 inform (olddecl_loc, "previous declaration %q#D here", olddecl);
2207 else if (DECL_MODULE_EXPORT_P (newdecl))
2208 DECL_MODULE_EXPORT_P (not_tmpl) = true;
2211 /* We have committed to returning OLDDECL at this point. */
2213 /* If new decl is `static' and an `extern' was seen previously,
2214 warn about it. */
2215 warn_extern_redeclared_static (newdecl, olddecl);
2217 /* True to merge attributes between the declarations, false to
2218 set OLDDECL's attributes to those of NEWDECL (for template
2219 explicit specializations that specify their own attributes
2220 independent of those specified for the primary template). */
2221 const bool merge_attr = (TREE_CODE (newdecl) != FUNCTION_DECL
2222 || !DECL_TEMPLATE_SPECIALIZATION (newdecl)
2223 || DECL_TEMPLATE_SPECIALIZATION (olddecl));
2225 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2227 if (merge_attr)
2229 if (diagnose_mismatched_attributes (olddecl, newdecl))
2230 inform (olddecl_loc, DECL_INITIAL (olddecl)
2231 ? G_("previous definition of %qD here")
2232 : G_("previous declaration of %qD here"), olddecl);
2234 /* [dcl.attr.noreturn]: The first declaration of a function shall
2235 specify the noreturn attribute if any declaration of that function
2236 specifies the noreturn attribute. */
2237 tree a;
2238 if (TREE_THIS_VOLATILE (newdecl)
2239 && !TREE_THIS_VOLATILE (olddecl)
2240 /* This applies to [[noreturn]] only, not its GNU variants. */
2241 && (a = lookup_attribute ("noreturn", DECL_ATTRIBUTES (newdecl)))
2242 && cxx11_attribute_p (a)
2243 && get_attribute_namespace (a) == NULL_TREE)
2245 error_at (newdecl_loc, "function %qD declared %<[[noreturn]]%> "
2246 "but its first declaration was not", newdecl);
2247 inform (olddecl_loc, "previous declaration of %qD", olddecl);
2251 /* Now that functions must hold information normally held
2252 by field decls, there is extra work to do so that
2253 declaration information does not get destroyed during
2254 definition. */
2255 if (DECL_VINDEX (olddecl))
2256 DECL_VINDEX (newdecl) = DECL_VINDEX (olddecl);
2257 if (DECL_CONTEXT (olddecl))
2258 DECL_CONTEXT (newdecl) = DECL_CONTEXT (olddecl);
2259 DECL_STATIC_CONSTRUCTOR (newdecl) |= DECL_STATIC_CONSTRUCTOR (olddecl);
2260 DECL_STATIC_DESTRUCTOR (newdecl) |= DECL_STATIC_DESTRUCTOR (olddecl);
2261 DECL_PURE_VIRTUAL_P (newdecl) |= DECL_PURE_VIRTUAL_P (olddecl);
2262 DECL_VIRTUAL_P (newdecl) |= DECL_VIRTUAL_P (olddecl);
2263 DECL_INVALID_OVERRIDER_P (newdecl) |= DECL_INVALID_OVERRIDER_P (olddecl);
2264 DECL_FINAL_P (newdecl) |= DECL_FINAL_P (olddecl);
2265 DECL_OVERRIDE_P (newdecl) |= DECL_OVERRIDE_P (olddecl);
2266 DECL_THIS_STATIC (newdecl) |= DECL_THIS_STATIC (olddecl);
2267 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (newdecl)
2268 |= DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (olddecl);
2269 if (DECL_OVERLOADED_OPERATOR_P (olddecl))
2270 DECL_OVERLOADED_OPERATOR_CODE_RAW (newdecl)
2271 = DECL_OVERLOADED_OPERATOR_CODE_RAW (olddecl);
2272 new_defines_function = DECL_INITIAL (newdecl) != NULL_TREE;
2274 duplicate_contracts (newdecl, olddecl);
2276 /* Optionally warn about more than one declaration for the same
2277 name, but don't warn about a function declaration followed by a
2278 definition. */
2279 if (warn_redundant_decls && ! DECL_ARTIFICIAL (olddecl)
2280 && !(new_defines_function && DECL_INITIAL (olddecl) == NULL_TREE)
2281 /* Don't warn about extern decl followed by definition. */
2282 && !(DECL_EXTERNAL (olddecl) && ! DECL_EXTERNAL (newdecl))
2283 /* Don't warn if at least one is/was hidden. */
2284 && !(hiding || was_hidden)
2285 /* Don't warn about declaration followed by specialization. */
2286 && (! DECL_TEMPLATE_SPECIALIZATION (newdecl)
2287 || DECL_TEMPLATE_SPECIALIZATION (olddecl)))
2289 auto_diagnostic_group d;
2290 if (warning_at (newdecl_loc,
2291 OPT_Wredundant_decls,
2292 "redundant redeclaration of %qD in same scope",
2293 newdecl))
2294 inform (olddecl_loc,
2295 "previous declaration of %qD", olddecl);
2298 /* [dcl.fct.def.delete] A deleted definition of a function shall be the
2299 first declaration of the function or, for an explicit specialization
2300 of a function template, the first declaration of that
2301 specialization. */
2302 if (!(DECL_TEMPLATE_INSTANTIATION (olddecl)
2303 && DECL_TEMPLATE_SPECIALIZATION (newdecl)))
2305 if (DECL_DELETED_FN (newdecl))
2307 auto_diagnostic_group d;
2308 if (pedwarn (newdecl_loc, 0, "deleted definition of %qD "
2309 "is not first declaration", newdecl))
2310 inform (olddecl_loc,
2311 "previous declaration of %qD", olddecl);
2313 DECL_DELETED_FN (newdecl) |= DECL_DELETED_FN (olddecl);
2317 /* Deal with C++: must preserve virtual function table size. */
2318 if (TREE_CODE (olddecl) == TYPE_DECL)
2320 tree newtype = TREE_TYPE (newdecl);
2321 tree oldtype = TREE_TYPE (olddecl);
2323 if (newtype != error_mark_node && oldtype != error_mark_node
2324 && TYPE_LANG_SPECIFIC (newtype) && TYPE_LANG_SPECIFIC (oldtype))
2325 CLASSTYPE_FRIEND_CLASSES (newtype)
2326 = CLASSTYPE_FRIEND_CLASSES (oldtype);
2328 DECL_ORIGINAL_TYPE (newdecl) = DECL_ORIGINAL_TYPE (olddecl);
2331 /* Copy all the DECL_... slots specified in the new decl except for
2332 any that we copy here from the old type. */
2333 if (merge_attr)
2334 DECL_ATTRIBUTES (newdecl)
2335 = (*targetm.merge_decl_attributes) (olddecl, newdecl);
2336 else
2337 DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
2339 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
2341 tree old_result = DECL_TEMPLATE_RESULT (olddecl);
2342 tree new_result = DECL_TEMPLATE_RESULT (newdecl);
2343 TREE_TYPE (olddecl) = TREE_TYPE (old_result);
2345 /* The new decl should not already have gathered any
2346 specializations. */
2347 gcc_assert (!DECL_TEMPLATE_SPECIALIZATIONS (newdecl));
2349 /* Make sure the contracts are equivalent. */
2350 duplicate_contracts (newdecl, olddecl);
2352 /* Remove contracts from old_result so they aren't appended to
2353 old_result by the merge function. */
2354 remove_contract_attributes (old_result);
2356 DECL_ATTRIBUTES (old_result)
2357 = (*targetm.merge_decl_attributes) (old_result, new_result);
2359 if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2361 if (DECL_SOURCE_LOCATION (newdecl)
2362 != DECL_SOURCE_LOCATION (olddecl))
2364 /* Per C++11 8.3.6/4, default arguments cannot be added in
2365 later declarations of a function template. */
2366 check_redeclaration_no_default_args (newdecl);
2367 /* C++17 11.3.6/4: "If a friend declaration specifies a default
2368 argument expression, that declaration... shall be the only
2369 declaration of the function or function template in the
2370 translation unit." */
2371 check_no_redeclaration_friend_default_args
2372 (old_result, new_result);
2374 tree new_parms = DECL_INNERMOST_TEMPLATE_PARMS (newdecl);
2375 tree old_parms = DECL_INNERMOST_TEMPLATE_PARMS (olddecl);
2376 merge_default_template_args (new_parms, old_parms,
2377 /*class_p=*/false);
2379 if (!DECL_UNIQUE_FRIEND_P (new_result))
2380 DECL_UNIQUE_FRIEND_P (old_result) = false;
2382 check_default_args (newdecl);
2384 if (GNU_INLINE_P (old_result) != GNU_INLINE_P (new_result)
2385 && DECL_INITIAL (new_result))
2387 if (DECL_INITIAL (old_result))
2388 DECL_UNINLINABLE (old_result) = 1;
2389 else
2390 DECL_UNINLINABLE (old_result) = DECL_UNINLINABLE (new_result);
2391 DECL_EXTERNAL (old_result) = DECL_EXTERNAL (new_result);
2392 DECL_NOT_REALLY_EXTERN (old_result)
2393 = DECL_NOT_REALLY_EXTERN (new_result);
2394 DECL_INTERFACE_KNOWN (old_result)
2395 = DECL_INTERFACE_KNOWN (new_result);
2396 DECL_DECLARED_INLINE_P (old_result)
2397 = DECL_DECLARED_INLINE_P (new_result);
2398 DECL_DISREGARD_INLINE_LIMITS (old_result)
2399 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2401 else
2403 DECL_DECLARED_INLINE_P (old_result)
2404 |= DECL_DECLARED_INLINE_P (new_result);
2405 DECL_DISREGARD_INLINE_LIMITS (old_result)
2406 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2407 check_redeclaration_exception_specification (newdecl, olddecl);
2409 merge_attribute_bits (new_result, old_result);
2413 /* If the new declaration is a definition, update the file and
2414 line information on the declaration, and also make
2415 the old declaration the same definition. */
2416 if (DECL_INITIAL (new_result) != NULL_TREE)
2418 DECL_SOURCE_LOCATION (olddecl)
2419 = DECL_SOURCE_LOCATION (old_result)
2420 = DECL_SOURCE_LOCATION (newdecl);
2421 DECL_INITIAL (old_result) = DECL_INITIAL (new_result);
2422 if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2424 DECL_ARGUMENTS (old_result) = DECL_ARGUMENTS (new_result);
2425 for (tree p = DECL_ARGUMENTS (old_result); p; p = DECL_CHAIN (p))
2426 DECL_CONTEXT (p) = old_result;
2428 if (tree fc = DECL_FRIEND_CONTEXT (new_result))
2429 SET_DECL_FRIEND_CONTEXT (old_result, fc);
2433 return olddecl;
2436 if (types_match)
2438 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2439 check_redeclaration_exception_specification (newdecl, olddecl);
2441 /* Automatically handles default parameters. */
2442 tree oldtype = TREE_TYPE (olddecl);
2443 tree newtype;
2445 /* For typedefs use the old type, as the new type's DECL_NAME points
2446 at newdecl, which will be ggc_freed. */
2447 if (TREE_CODE (newdecl) == TYPE_DECL)
2449 /* But NEWTYPE might have an attribute, honor that. */
2450 tree tem = TREE_TYPE (newdecl);
2451 newtype = oldtype;
2453 if (TYPE_USER_ALIGN (tem))
2455 if (TYPE_ALIGN (tem) > TYPE_ALIGN (newtype))
2456 SET_TYPE_ALIGN (newtype, TYPE_ALIGN (tem));
2457 TYPE_USER_ALIGN (newtype) = true;
2460 /* And remove the new type from the variants list. */
2461 if (TYPE_NAME (TREE_TYPE (newdecl)) == newdecl)
2463 tree remove = TREE_TYPE (newdecl);
2464 if (TYPE_MAIN_VARIANT (remove) == remove)
2466 gcc_assert (TYPE_NEXT_VARIANT (remove) == NULL_TREE);
2467 /* If remove is the main variant, no need to remove that
2468 from the list. One of the DECL_ORIGINAL_TYPE
2469 variants, e.g. created for aligned attribute, might still
2470 refer to the newdecl TYPE_DECL though, so remove that one
2471 in that case. */
2472 if (tree orig = DECL_ORIGINAL_TYPE (newdecl))
2473 if (orig != remove)
2474 for (tree t = TYPE_MAIN_VARIANT (orig); t;
2475 t = TYPE_MAIN_VARIANT (t))
2476 if (TYPE_NAME (TYPE_NEXT_VARIANT (t)) == newdecl)
2478 TYPE_NEXT_VARIANT (t)
2479 = TYPE_NEXT_VARIANT (TYPE_NEXT_VARIANT (t));
2480 break;
2483 else
2484 for (tree t = TYPE_MAIN_VARIANT (remove); ;
2485 t = TYPE_NEXT_VARIANT (t))
2486 if (TYPE_NEXT_VARIANT (t) == remove)
2488 TYPE_NEXT_VARIANT (t) = TYPE_NEXT_VARIANT (remove);
2489 break;
2493 else if (merge_attr)
2494 newtype = merge_types (TREE_TYPE (newdecl), TREE_TYPE (olddecl));
2495 else
2496 newtype = TREE_TYPE (newdecl);
2498 if (VAR_P (newdecl))
2500 DECL_THIS_EXTERN (newdecl) |= DECL_THIS_EXTERN (olddecl);
2501 /* For already initialized vars, TREE_READONLY could have been
2502 cleared in cp_finish_decl, because the var needs runtime
2503 initialization or destruction. Make sure not to set
2504 TREE_READONLY on it again. */
2505 if (DECL_INITIALIZED_P (olddecl)
2506 && !DECL_EXTERNAL (olddecl)
2507 && !TREE_READONLY (olddecl))
2508 TREE_READONLY (newdecl) = 0;
2509 DECL_INITIALIZED_P (newdecl) |= DECL_INITIALIZED_P (olddecl);
2510 DECL_NONTRIVIALLY_INITIALIZED_P (newdecl)
2511 |= DECL_NONTRIVIALLY_INITIALIZED_P (olddecl);
2512 if (DECL_DEPENDENT_INIT_P (olddecl))
2513 SET_DECL_DEPENDENT_INIT_P (newdecl, true);
2514 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (newdecl)
2515 |= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (olddecl);
2516 DECL_DECLARED_CONSTEXPR_P (newdecl)
2517 |= DECL_DECLARED_CONSTEXPR_P (olddecl);
2518 DECL_DECLARED_CONSTINIT_P (newdecl)
2519 |= DECL_DECLARED_CONSTINIT_P (olddecl);
2521 /* Merge the threadprivate attribute from OLDDECL into NEWDECL. */
2522 if (DECL_LANG_SPECIFIC (olddecl)
2523 && CP_DECL_THREADPRIVATE_P (olddecl))
2525 /* Allocate a LANG_SPECIFIC structure for NEWDECL, if needed. */
2526 retrofit_lang_decl (newdecl);
2527 CP_DECL_THREADPRIVATE_P (newdecl) = 1;
2531 /* An explicit specialization of a function template or of a member
2532 function of a class template can be declared transaction_safe
2533 independently of whether the corresponding template entity is declared
2534 transaction_safe. */
2535 if (flag_tm && TREE_CODE (newdecl) == FUNCTION_DECL
2536 && DECL_TEMPLATE_INSTANTIATION (olddecl)
2537 && DECL_TEMPLATE_SPECIALIZATION (newdecl)
2538 && tx_safe_fn_type_p (newtype)
2539 && !tx_safe_fn_type_p (TREE_TYPE (newdecl)))
2540 newtype = tx_unsafe_fn_variant (newtype);
2542 TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = newtype;
2544 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2545 check_default_args (newdecl);
2547 /* Lay the type out, unless already done. */
2548 if (! same_type_p (newtype, oldtype)
2549 && TREE_TYPE (newdecl) != error_mark_node
2550 && !(processing_template_decl && uses_template_parms (newdecl)))
2551 layout_type (TREE_TYPE (newdecl));
2553 if ((VAR_P (newdecl)
2554 || TREE_CODE (newdecl) == PARM_DECL
2555 || TREE_CODE (newdecl) == RESULT_DECL
2556 || TREE_CODE (newdecl) == FIELD_DECL
2557 || TREE_CODE (newdecl) == TYPE_DECL)
2558 && !(processing_template_decl && uses_template_parms (newdecl)))
2559 layout_decl (newdecl, 0);
2561 /* Merge deprecatedness. */
2562 if (TREE_DEPRECATED (newdecl))
2563 TREE_DEPRECATED (olddecl) = 1;
2565 /* Merge unavailability. */
2566 if (TREE_UNAVAILABLE (newdecl))
2567 TREE_UNAVAILABLE (olddecl) = 1;
2569 /* Preserve function specific target and optimization options */
2570 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2572 if (DECL_FUNCTION_SPECIFIC_TARGET (olddecl)
2573 && !DECL_FUNCTION_SPECIFIC_TARGET (newdecl))
2574 DECL_FUNCTION_SPECIFIC_TARGET (newdecl)
2575 = DECL_FUNCTION_SPECIFIC_TARGET (olddecl);
2577 if (DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl)
2578 && !DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl))
2579 DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl)
2580 = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl);
2582 if (!DECL_UNIQUE_FRIEND_P (olddecl))
2583 DECL_UNIQUE_FRIEND_P (newdecl) = false;
2585 else
2587 /* Merge the const type qualifier. */
2588 if (TREE_READONLY (newdecl))
2589 TREE_READONLY (olddecl) = 1;
2590 /* Merge the volatile type qualifier. */
2591 if (TREE_THIS_VOLATILE (newdecl))
2592 TREE_THIS_VOLATILE (olddecl) = 1;
2595 /* Merge the initialization information. */
2596 if (DECL_INITIAL (newdecl) == NULL_TREE
2597 && DECL_INITIAL (olddecl) != NULL_TREE)
2599 DECL_INITIAL (newdecl) = DECL_INITIAL (olddecl);
2600 DECL_SOURCE_LOCATION (newdecl) = DECL_SOURCE_LOCATION (olddecl);
2601 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2603 DECL_SAVED_TREE (newdecl) = DECL_SAVED_TREE (olddecl);
2604 DECL_STRUCT_FUNCTION (newdecl) = DECL_STRUCT_FUNCTION (olddecl);
2608 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2610 DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (newdecl)
2611 |= DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (olddecl);
2612 DECL_NO_LIMIT_STACK (newdecl) |= DECL_NO_LIMIT_STACK (olddecl);
2613 if (DECL_IS_OPERATOR_NEW_P (olddecl))
2614 DECL_SET_IS_OPERATOR_NEW (newdecl, true);
2615 DECL_LOOPING_CONST_OR_PURE_P (newdecl)
2616 |= DECL_LOOPING_CONST_OR_PURE_P (olddecl);
2617 DECL_IS_REPLACEABLE_OPERATOR (newdecl)
2618 |= DECL_IS_REPLACEABLE_OPERATOR (olddecl);
2620 if (merge_attr)
2621 merge_attribute_bits (newdecl, olddecl);
2622 else
2624 /* Merge the noreturn bit. */
2625 TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2626 TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2627 TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2628 DECL_IS_MALLOC (olddecl) = DECL_IS_MALLOC (newdecl);
2629 DECL_PURE_P (olddecl) = DECL_PURE_P (newdecl);
2631 /* Keep the old RTL. */
2632 COPY_DECL_RTL (olddecl, newdecl);
2634 else if (VAR_P (newdecl)
2635 && (DECL_SIZE (olddecl) || !DECL_SIZE (newdecl)))
2637 /* Keep the old RTL. We cannot keep the old RTL if the old
2638 declaration was for an incomplete object and the new
2639 declaration is not since many attributes of the RTL will
2640 change. */
2641 COPY_DECL_RTL (olddecl, newdecl);
2644 /* If cannot merge, then use the new type and qualifiers,
2645 and don't preserve the old rtl. */
2646 else
2648 /* Clean out any memory we had of the old declaration. */
2649 tree oldstatic = value_member (olddecl, static_aggregates);
2650 if (oldstatic)
2651 TREE_VALUE (oldstatic) = error_mark_node;
2653 TREE_TYPE (olddecl) = TREE_TYPE (newdecl);
2654 TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2655 TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2656 TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2657 TREE_SIDE_EFFECTS (olddecl) = TREE_SIDE_EFFECTS (newdecl);
2660 /* Merge the storage class information. */
2661 merge_weak (newdecl, olddecl);
2663 DECL_DEFER_OUTPUT (newdecl) |= DECL_DEFER_OUTPUT (olddecl);
2664 TREE_PUBLIC (newdecl) = TREE_PUBLIC (olddecl);
2665 TREE_STATIC (olddecl) = TREE_STATIC (newdecl) |= TREE_STATIC (olddecl);
2666 if (! DECL_EXTERNAL (olddecl))
2667 DECL_EXTERNAL (newdecl) = 0;
2668 if (! DECL_COMDAT (olddecl))
2669 DECL_COMDAT (newdecl) = 0;
2671 if (VAR_OR_FUNCTION_DECL_P (newdecl) && DECL_LOCAL_DECL_P (newdecl))
2673 if (!DECL_LOCAL_DECL_P (olddecl))
2674 /* This can happen if olddecl was brought in from the
2675 enclosing namespace via a using-decl. The new decl is
2676 then not a block-scope extern at all. */
2677 DECL_LOCAL_DECL_P (newdecl) = false;
2678 else
2680 retrofit_lang_decl (newdecl);
2681 tree alias = DECL_LOCAL_DECL_ALIAS (newdecl)
2682 = DECL_LOCAL_DECL_ALIAS (olddecl);
2683 DECL_ATTRIBUTES (alias)
2684 = (*targetm.merge_decl_attributes) (alias, newdecl);
2685 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2686 merge_attribute_bits (newdecl, alias);
2690 new_template_info = NULL_TREE;
2691 if (DECL_LANG_SPECIFIC (newdecl) && DECL_LANG_SPECIFIC (olddecl))
2693 bool new_redefines_gnu_inline = false;
2695 if (new_defines_function
2696 && ((DECL_INTERFACE_KNOWN (olddecl)
2697 && TREE_CODE (olddecl) == FUNCTION_DECL)
2698 || (TREE_CODE (olddecl) == TEMPLATE_DECL
2699 && (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl))
2700 == FUNCTION_DECL))))
2701 new_redefines_gnu_inline = GNU_INLINE_P (STRIP_TEMPLATE (olddecl));
2703 if (!new_redefines_gnu_inline)
2705 DECL_INTERFACE_KNOWN (newdecl) |= DECL_INTERFACE_KNOWN (olddecl);
2706 DECL_NOT_REALLY_EXTERN (newdecl) |= DECL_NOT_REALLY_EXTERN (olddecl);
2707 DECL_COMDAT (newdecl) |= DECL_COMDAT (olddecl);
2710 if (TREE_CODE (newdecl) != TYPE_DECL)
2712 DECL_TEMPLATE_INSTANTIATED (newdecl)
2713 |= DECL_TEMPLATE_INSTANTIATED (olddecl);
2714 DECL_ODR_USED (newdecl) |= DECL_ODR_USED (olddecl);
2716 /* If the OLDDECL is an instantiation and/or specialization,
2717 then the NEWDECL must be too. But, it may not yet be marked
2718 as such if the caller has created NEWDECL, but has not yet
2719 figured out that it is a redeclaration. */
2720 if (!DECL_USE_TEMPLATE (newdecl))
2721 DECL_USE_TEMPLATE (newdecl) = DECL_USE_TEMPLATE (olddecl);
2723 if (!DECL_TEMPLATE_SPECIALIZATION (newdecl))
2724 DECL_INITIALIZED_IN_CLASS_P (newdecl)
2725 |= DECL_INITIALIZED_IN_CLASS_P (olddecl);
2728 /* Don't really know how much of the language-specific
2729 values we should copy from old to new. */
2730 DECL_IN_AGGR_P (newdecl) = DECL_IN_AGGR_P (olddecl);
2732 if (LANG_DECL_HAS_MIN (newdecl))
2734 DECL_ACCESS (newdecl) = DECL_ACCESS (olddecl);
2735 if (DECL_TEMPLATE_INFO (newdecl))
2737 new_template_info = DECL_TEMPLATE_INFO (newdecl);
2738 if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2739 && DECL_TEMPLATE_SPECIALIZATION (newdecl))
2740 /* Remember the presence of explicit specialization args. */
2741 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (olddecl))
2742 = TINFO_USED_TEMPLATE_ID (new_template_info);
2745 /* We don't want to copy template info from a non-templated friend
2746 (PR105761), but these shouldn't have DECL_TEMPLATE_INFO now. */
2747 gcc_checking_assert (!DECL_TEMPLATE_INFO (olddecl)
2748 || !non_templated_friend_p (olddecl));
2749 DECL_TEMPLATE_INFO (newdecl) = DECL_TEMPLATE_INFO (olddecl);
2752 if (DECL_DECLARES_FUNCTION_P (newdecl))
2754 /* Only functions have these fields. */
2755 DECL_NONCONVERTING_P (newdecl) = DECL_NONCONVERTING_P (olddecl);
2756 DECL_BEFRIENDING_CLASSES (newdecl)
2757 = chainon (DECL_BEFRIENDING_CLASSES (newdecl),
2758 DECL_BEFRIENDING_CLASSES (olddecl));
2759 /* DECL_THUNKS is only valid for virtual functions,
2760 otherwise it is a DECL_FRIEND_CONTEXT. */
2761 if (DECL_VIRTUAL_P (newdecl))
2762 SET_DECL_THUNKS (newdecl, DECL_THUNKS (olddecl));
2763 else if (tree fc = DECL_FRIEND_CONTEXT (newdecl))
2764 SET_DECL_FRIEND_CONTEXT (olddecl, fc);
2766 else if (VAR_P (newdecl))
2768 /* Only variables have this field. */
2769 if (VAR_HAD_UNKNOWN_BOUND (olddecl))
2770 SET_VAR_HAD_UNKNOWN_BOUND (newdecl);
2774 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2776 tree parm;
2778 /* Merge parameter attributes. */
2779 tree oldarg, newarg;
2780 for (oldarg = DECL_ARGUMENTS(olddecl), newarg = DECL_ARGUMENTS(newdecl);
2781 oldarg && newarg;
2782 oldarg = DECL_CHAIN(oldarg), newarg = DECL_CHAIN(newarg))
2784 DECL_ATTRIBUTES (newarg)
2785 = (*targetm.merge_decl_attributes) (oldarg, newarg);
2786 DECL_ATTRIBUTES (oldarg) = DECL_ATTRIBUTES (newarg);
2789 if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2790 && !DECL_TEMPLATE_INSTANTIATION (newdecl))
2792 /* If newdecl is not a specialization, then it is not a
2793 template-related function at all. And that means that we
2794 should have exited above, returning 0. */
2795 gcc_assert (DECL_TEMPLATE_SPECIALIZATION (newdecl));
2797 if (DECL_ODR_USED (olddecl))
2798 /* From [temp.expl.spec]:
2800 If a template, a member template or the member of a class
2801 template is explicitly specialized then that
2802 specialization shall be declared before the first use of
2803 that specialization that would cause an implicit
2804 instantiation to take place, in every translation unit in
2805 which such a use occurs. */
2806 error ("explicit specialization of %qD after first use",
2807 olddecl);
2809 SET_DECL_TEMPLATE_SPECIALIZATION (olddecl);
2810 DECL_COMDAT (newdecl) = (TREE_PUBLIC (newdecl)
2811 && DECL_DECLARED_INLINE_P (newdecl));
2813 /* Don't propagate visibility from the template to the
2814 specialization here. We'll do that in determine_visibility if
2815 appropriate. */
2816 DECL_VISIBILITY_SPECIFIED (olddecl) = 0;
2818 /* [temp.expl.spec/14] We don't inline explicit specialization
2819 just because the primary template says so. */
2820 gcc_assert (!merge_attr);
2822 DECL_DECLARED_INLINE_P (olddecl)
2823 = DECL_DECLARED_INLINE_P (newdecl);
2825 DECL_DISREGARD_INLINE_LIMITS (olddecl)
2826 = DECL_DISREGARD_INLINE_LIMITS (newdecl);
2828 DECL_UNINLINABLE (olddecl) = DECL_UNINLINABLE (newdecl);
2830 else if (new_defines_function && DECL_INITIAL (olddecl))
2832 /* Never inline re-defined extern inline functions.
2833 FIXME: this could be better handled by keeping both
2834 function as separate declarations. */
2835 DECL_UNINLINABLE (newdecl) = 1;
2837 else
2839 if (DECL_PENDING_INLINE_P (olddecl))
2841 DECL_PENDING_INLINE_P (newdecl) = 1;
2842 DECL_PENDING_INLINE_INFO (newdecl)
2843 = DECL_PENDING_INLINE_INFO (olddecl);
2845 else if (DECL_PENDING_INLINE_P (newdecl))
2847 else if (DECL_SAVED_AUTO_RETURN_TYPE (newdecl) == NULL)
2848 DECL_SAVED_AUTO_RETURN_TYPE (newdecl)
2849 = DECL_SAVED_AUTO_RETURN_TYPE (olddecl);
2851 DECL_DECLARED_INLINE_P (newdecl) |= DECL_DECLARED_INLINE_P (olddecl);
2853 DECL_UNINLINABLE (newdecl) = DECL_UNINLINABLE (olddecl)
2854 = (DECL_UNINLINABLE (newdecl) || DECL_UNINLINABLE (olddecl));
2856 DECL_DISREGARD_INLINE_LIMITS (newdecl)
2857 = DECL_DISREGARD_INLINE_LIMITS (olddecl)
2858 = (DECL_DISREGARD_INLINE_LIMITS (newdecl)
2859 || DECL_DISREGARD_INLINE_LIMITS (olddecl));
2862 /* Preserve abstractness on cloned [cd]tors. */
2863 DECL_ABSTRACT_P (newdecl) = DECL_ABSTRACT_P (olddecl);
2865 /* Update newdecl's parms to point at olddecl. */
2866 for (parm = DECL_ARGUMENTS (newdecl); parm;
2867 parm = DECL_CHAIN (parm))
2868 DECL_CONTEXT (parm) = olddecl;
2870 if (! types_match)
2872 SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
2873 COPY_DECL_ASSEMBLER_NAME (newdecl, olddecl);
2874 COPY_DECL_RTL (newdecl, olddecl);
2876 if (! types_match || new_defines_function)
2878 /* These are the final DECL_ARGUMENTS that will be used within the
2879 body; update any references to old DECL_ARGUMENTS in the
2880 contracts, if present. */
2881 if (tree contracts = DECL_CONTRACTS (newdecl))
2882 remap_contracts (olddecl, newdecl, contracts, true);
2884 /* These need to be copied so that the names are available.
2885 Note that if the types do match, we'll preserve inline
2886 info and other bits, but if not, we won't. */
2887 DECL_ARGUMENTS (olddecl) = DECL_ARGUMENTS (newdecl);
2888 DECL_RESULT (olddecl) = DECL_RESULT (newdecl);
2890 /* In some cases, duplicate_contracts will remove contracts from
2891 OLDDECL, to avoid duplications. Sometimes, the contracts end up
2892 shared. If we removed them, re-add them. */
2893 if (!DECL_CONTRACTS (olddecl))
2894 copy_contract_attributes (olddecl, newdecl);
2896 /* If redeclaring a builtin function, it stays built in
2897 if newdecl is a gnu_inline definition, or if newdecl is just
2898 a declaration. */
2899 if (fndecl_built_in_p (olddecl)
2900 && (new_defines_function ? GNU_INLINE_P (newdecl) : types_match))
2902 copy_decl_built_in_function (newdecl, olddecl);
2903 /* If we're keeping the built-in definition, keep the rtl,
2904 regardless of declaration matches. */
2905 COPY_DECL_RTL (olddecl, newdecl);
2906 if (DECL_BUILT_IN_CLASS (newdecl) == BUILT_IN_NORMAL)
2908 enum built_in_function fncode = DECL_FUNCTION_CODE (newdecl);
2909 if (builtin_decl_explicit_p (fncode))
2911 /* A compatible prototype of these builtin functions
2912 is seen, assume the runtime implements it with
2913 the expected semantics. */
2914 switch (fncode)
2916 case BUILT_IN_STPCPY:
2917 set_builtin_decl_implicit_p (fncode, true);
2918 break;
2919 default:
2920 set_builtin_decl_declared_p (fncode, true);
2921 break;
2925 copy_attributes_to_builtin (newdecl);
2928 if (new_defines_function)
2929 /* If defining a function declared with other language
2930 linkage, use the previously declared language linkage. */
2931 SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
2932 else if (types_match)
2934 DECL_RESULT (newdecl) = DECL_RESULT (olddecl);
2935 /* Don't clear out the arguments if we're just redeclaring a
2936 function. */
2937 if (DECL_ARGUMENTS (olddecl))
2939 /* If we removed contracts from previous definition, re-attach
2940 them. Otherwise, rewrite the contracts so they match the
2941 parameters of the new declaration. */
2942 if (DECL_INITIAL (olddecl)
2943 && DECL_CONTRACTS (newdecl)
2944 && !DECL_CONTRACTS (olddecl))
2945 copy_contract_attributes (olddecl, newdecl);
2946 else
2948 /* Temporarily undo the re-contexting of parameters so we can
2949 actually remap parameters. The inliner won't replace
2950 parameters if we don't do this. */
2951 tree args = DECL_ARGUMENTS (newdecl);
2952 for (tree p = args; p; p = DECL_CHAIN (p))
2953 DECL_CONTEXT (p) = newdecl;
2955 /* Save new argument names for use in contracts parsing,
2956 unless we've already started parsing the body of olddecl
2957 (particular issues arise when newdecl is from a prior
2958 friend decl with no argument names, see
2959 modules/contracts-tpl-friend-1). */
2960 if (tree contracts = DECL_CONTRACTS (olddecl))
2961 remap_contracts (newdecl, olddecl, contracts, true);
2963 /* And reverse this operation again. */
2964 for (tree p = args; p; p = DECL_CHAIN (p))
2965 DECL_CONTEXT (p) = olddecl;
2968 DECL_ARGUMENTS (newdecl) = DECL_ARGUMENTS (olddecl);
2972 else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
2973 NAMESPACE_LEVEL (newdecl) = NAMESPACE_LEVEL (olddecl);
2975 /* Now preserve various other info from the definition. */
2976 TREE_ADDRESSABLE (newdecl) = TREE_ADDRESSABLE (olddecl);
2977 TREE_ASM_WRITTEN (newdecl) = TREE_ASM_WRITTEN (olddecl);
2978 DECL_COMMON (newdecl) = DECL_COMMON (olddecl);
2979 COPY_DECL_ASSEMBLER_NAME (olddecl, newdecl);
2981 /* Warn about conflicting visibility specifications. */
2982 if (DECL_VISIBILITY_SPECIFIED (olddecl)
2983 && DECL_VISIBILITY_SPECIFIED (newdecl)
2984 && DECL_VISIBILITY (newdecl) != DECL_VISIBILITY (olddecl))
2986 auto_diagnostic_group d;
2987 if (warning_at (newdecl_loc, OPT_Wattributes,
2988 "%qD: visibility attribute ignored because it "
2989 "conflicts with previous declaration", newdecl))
2990 inform (olddecl_loc,
2991 "previous declaration of %qD", olddecl);
2993 /* Choose the declaration which specified visibility. */
2994 if (DECL_VISIBILITY_SPECIFIED (olddecl))
2996 DECL_VISIBILITY (newdecl) = DECL_VISIBILITY (olddecl);
2997 DECL_VISIBILITY_SPECIFIED (newdecl) = 1;
2999 /* Init priority used to be merged from newdecl to olddecl by the memcpy,
3000 so keep this behavior. */
3001 if (VAR_P (newdecl) && DECL_HAS_INIT_PRIORITY_P (newdecl))
3003 SET_DECL_INIT_PRIORITY (olddecl, DECL_INIT_PRIORITY (newdecl));
3004 DECL_HAS_INIT_PRIORITY_P (olddecl) = 1;
3006 /* Likewise for DECL_ALIGN, DECL_USER_ALIGN and DECL_PACKED. */
3007 if (DECL_ALIGN (olddecl) > DECL_ALIGN (newdecl))
3009 SET_DECL_ALIGN (newdecl, DECL_ALIGN (olddecl));
3010 DECL_USER_ALIGN (newdecl) |= DECL_USER_ALIGN (olddecl);
3012 else if (DECL_ALIGN (olddecl) == DECL_ALIGN (newdecl)
3013 && DECL_USER_ALIGN (olddecl) != DECL_USER_ALIGN (newdecl))
3014 DECL_USER_ALIGN (newdecl) = 1;
3016 DECL_USER_ALIGN (olddecl) = DECL_USER_ALIGN (newdecl);
3017 if (DECL_WARN_IF_NOT_ALIGN (olddecl)
3018 > DECL_WARN_IF_NOT_ALIGN (newdecl))
3019 SET_DECL_WARN_IF_NOT_ALIGN (newdecl,
3020 DECL_WARN_IF_NOT_ALIGN (olddecl));
3021 if (TREE_CODE (newdecl) == FIELD_DECL)
3022 DECL_PACKED (olddecl) = DECL_PACKED (newdecl);
3024 /* The DECL_LANG_SPECIFIC information in OLDDECL will be replaced
3025 with that from NEWDECL below. */
3026 if (DECL_LANG_SPECIFIC (olddecl))
3028 gcc_checking_assert (DECL_LANG_SPECIFIC (olddecl)
3029 != DECL_LANG_SPECIFIC (newdecl));
3030 ggc_free (DECL_LANG_SPECIFIC (olddecl));
3033 /* Merge the USED information. */
3034 if (TREE_USED (olddecl))
3035 TREE_USED (newdecl) = 1;
3036 else if (TREE_USED (newdecl))
3037 TREE_USED (olddecl) = 1;
3039 if (VAR_P (newdecl))
3041 if (DECL_READ_P (olddecl))
3042 DECL_READ_P (newdecl) = 1;
3043 else if (DECL_READ_P (newdecl))
3044 DECL_READ_P (olddecl) = 1;
3047 if (DECL_PRESERVE_P (olddecl))
3048 DECL_PRESERVE_P (newdecl) = 1;
3049 else if (DECL_PRESERVE_P (newdecl))
3050 DECL_PRESERVE_P (olddecl) = 1;
3052 /* Merge the DECL_FUNCTION_VERSIONED information. newdecl will be copied
3053 to olddecl and deleted. */
3054 if (TREE_CODE (newdecl) == FUNCTION_DECL
3055 && DECL_FUNCTION_VERSIONED (olddecl))
3057 /* Set the flag for newdecl so that it gets copied to olddecl. */
3058 DECL_FUNCTION_VERSIONED (newdecl) = 1;
3059 /* newdecl will be purged after copying to olddecl and is no longer
3060 a version. */
3061 cgraph_node::delete_function_version_by_decl (newdecl);
3064 if (TREE_CODE (newdecl) == FUNCTION_DECL)
3066 int function_size;
3067 struct symtab_node *snode = symtab_node::get (olddecl);
3069 function_size = sizeof (struct tree_decl_common);
3071 memcpy ((char *) olddecl + sizeof (struct tree_common),
3072 (char *) newdecl + sizeof (struct tree_common),
3073 function_size - sizeof (struct tree_common));
3075 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3076 (char *) newdecl + sizeof (struct tree_decl_common),
3077 sizeof (struct tree_function_decl) - sizeof (struct tree_decl_common));
3079 /* Preserve symtab node mapping. */
3080 olddecl->decl_with_vis.symtab_node = snode;
3082 if (new_template_info)
3083 /* If newdecl is a template instantiation, it is possible that
3084 the following sequence of events has occurred:
3086 o A friend function was declared in a class template. The
3087 class template was instantiated.
3089 o The instantiation of the friend declaration was
3090 recorded on the instantiation list, and is newdecl.
3092 o Later, however, instantiate_class_template called pushdecl
3093 on the newdecl to perform name injection. But, pushdecl in
3094 turn called duplicate_decls when it discovered that another
3095 declaration of a global function with the same name already
3096 existed.
3098 o Here, in duplicate_decls, we decided to clobber newdecl.
3100 If we're going to do that, we'd better make sure that
3101 olddecl, and not newdecl, is on the list of
3102 instantiations so that if we try to do the instantiation
3103 again we won't get the clobbered declaration. */
3104 reregister_specialization (newdecl,
3105 new_template_info,
3106 olddecl);
3108 else
3110 size_t size = tree_code_size (TREE_CODE (newdecl));
3112 memcpy ((char *) olddecl + sizeof (struct tree_common),
3113 (char *) newdecl + sizeof (struct tree_common),
3114 sizeof (struct tree_decl_common) - sizeof (struct tree_common));
3116 switch (TREE_CODE (newdecl))
3118 case LABEL_DECL:
3119 case VAR_DECL:
3120 case RESULT_DECL:
3121 case PARM_DECL:
3122 case FIELD_DECL:
3123 case TYPE_DECL:
3124 case CONST_DECL:
3126 struct symtab_node *snode = NULL;
3128 if (VAR_P (newdecl)
3129 && (TREE_STATIC (olddecl) || TREE_PUBLIC (olddecl)
3130 || DECL_EXTERNAL (olddecl)))
3131 snode = symtab_node::get (olddecl);
3132 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3133 (char *) newdecl + sizeof (struct tree_decl_common),
3134 size - sizeof (struct tree_decl_common)
3135 + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
3136 if (VAR_P (newdecl))
3137 olddecl->decl_with_vis.symtab_node = snode;
3139 break;
3140 default:
3141 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3142 (char *) newdecl + sizeof (struct tree_decl_common),
3143 sizeof (struct tree_decl_non_common) - sizeof (struct tree_decl_common)
3144 + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
3145 break;
3149 if (VAR_OR_FUNCTION_DECL_P (newdecl))
3151 if (DECL_EXTERNAL (olddecl)
3152 || TREE_PUBLIC (olddecl)
3153 || TREE_STATIC (olddecl))
3155 /* Merge the section attribute.
3156 We want to issue an error if the sections conflict but that must be
3157 done later in decl_attributes since we are called before attributes
3158 are assigned. */
3159 if (DECL_SECTION_NAME (newdecl) != NULL)
3160 set_decl_section_name (olddecl, newdecl);
3162 if (DECL_ONE_ONLY (newdecl))
3164 struct symtab_node *oldsym, *newsym;
3165 if (TREE_CODE (olddecl) == FUNCTION_DECL)
3166 oldsym = cgraph_node::get_create (olddecl);
3167 else
3168 oldsym = varpool_node::get_create (olddecl);
3169 newsym = symtab_node::get (newdecl);
3170 oldsym->set_comdat_group (newsym->get_comdat_group ());
3174 if (VAR_P (newdecl)
3175 && CP_DECL_THREAD_LOCAL_P (newdecl))
3177 CP_DECL_THREAD_LOCAL_P (olddecl) = true;
3178 if (!processing_template_decl)
3179 set_decl_tls_model (olddecl, DECL_TLS_MODEL (newdecl));
3183 DECL_UID (olddecl) = olddecl_uid;
3185 /* NEWDECL contains the merged attribute lists.
3186 Update OLDDECL to be the same. */
3187 DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
3189 /* If OLDDECL had its DECL_RTL instantiated, re-invoke make_decl_rtl
3190 so that encode_section_info has a chance to look at the new decl
3191 flags and attributes. */
3192 if (DECL_RTL_SET_P (olddecl)
3193 && (TREE_CODE (olddecl) == FUNCTION_DECL
3194 || (VAR_P (olddecl)
3195 && TREE_STATIC (olddecl))))
3196 make_decl_rtl (olddecl);
3198 /* The NEWDECL will no longer be needed. Because every out-of-class
3199 declaration of a member results in a call to duplicate_decls,
3200 freeing these nodes represents in a significant savings.
3202 Before releasing the node, be sore to remove function from symbol
3203 table that might have been inserted there to record comdat group.
3204 Be sure to however do not free DECL_STRUCT_FUNCTION because this
3205 structure is shared in between newdecl and oldecl. */
3206 if (TREE_CODE (newdecl) == FUNCTION_DECL)
3207 DECL_STRUCT_FUNCTION (newdecl) = NULL;
3208 if (VAR_OR_FUNCTION_DECL_P (newdecl))
3210 struct symtab_node *snode = symtab_node::get (newdecl);
3211 if (snode)
3212 snode->remove ();
3215 if (TREE_CODE (olddecl) == FUNCTION_DECL)
3217 tree clone;
3218 FOR_EACH_CLONE (clone, olddecl)
3220 DECL_ATTRIBUTES (clone) = DECL_ATTRIBUTES (olddecl);
3221 DECL_PRESERVE_P (clone) |= DECL_PRESERVE_P (olddecl);
3225 /* Remove the associated constraints for newdecl, if any, before
3226 reclaiming memory. */
3227 if (flag_concepts)
3228 remove_constraints (newdecl);
3230 ggc_free (newdecl);
3232 return olddecl;
3235 /* Return zero if the declaration NEWDECL is valid
3236 when the declaration OLDDECL (assumed to be for the same name)
3237 has already been seen.
3238 Otherwise return an error message format string with a %s
3239 where the identifier should go. */
3241 static const char *
3242 redeclaration_error_message (tree newdecl, tree olddecl)
3244 if (TREE_CODE (newdecl) == TYPE_DECL)
3246 /* Because C++ can put things into name space for free,
3247 constructs like "typedef struct foo { ... } foo"
3248 would look like an erroneous redeclaration. */
3249 if (same_type_p (TREE_TYPE (newdecl), TREE_TYPE (olddecl)))
3250 return NULL;
3251 else
3252 return G_("redefinition of %q#D");
3254 else if (TREE_CODE (newdecl) == FUNCTION_DECL)
3256 /* If this is a pure function, its olddecl will actually be
3257 the original initialization to `0' (which we force to call
3258 abort()). Don't complain about redefinition in this case. */
3259 if (DECL_LANG_SPECIFIC (olddecl) && DECL_PURE_VIRTUAL_P (olddecl)
3260 && DECL_INITIAL (olddecl) == NULL_TREE)
3261 return NULL;
3263 /* If both functions come from different namespaces, this is not
3264 a redeclaration - this is a conflict with a used function. */
3265 if (DECL_NAMESPACE_SCOPE_P (olddecl)
3266 && DECL_CONTEXT (olddecl) != DECL_CONTEXT (newdecl)
3267 && ! decls_match (olddecl, newdecl))
3268 return G_("%qD conflicts with used function");
3270 /* We'll complain about linkage mismatches in
3271 warn_extern_redeclared_static. */
3273 /* Defining the same name twice is no good. */
3274 if (decl_defined_p (olddecl)
3275 && decl_defined_p (newdecl))
3277 if (DECL_NAME (olddecl) == NULL_TREE)
3278 return G_("%q#D not declared in class");
3279 else if (!GNU_INLINE_P (olddecl)
3280 || GNU_INLINE_P (newdecl))
3281 return G_("redefinition of %q#D");
3284 if (DECL_DECLARED_INLINE_P (olddecl) && DECL_DECLARED_INLINE_P (newdecl))
3286 bool olda = GNU_INLINE_P (olddecl);
3287 bool newa = GNU_INLINE_P (newdecl);
3289 if (olda != newa)
3291 if (newa)
3292 return G_("%q+D redeclared inline with "
3293 "%<gnu_inline%> attribute");
3294 else
3295 return G_("%q+D redeclared inline without "
3296 "%<gnu_inline%> attribute");
3300 if (deduction_guide_p (olddecl)
3301 && deduction_guide_p (newdecl))
3302 return G_("deduction guide %q+D redeclared");
3304 /* [class.compare.default]: A definition of a comparison operator as
3305 defaulted that appears in a class shall be the first declaration of
3306 that function. */
3307 special_function_kind sfk = special_function_p (olddecl);
3308 if (sfk == sfk_comparison && DECL_DEFAULTED_FN (newdecl))
3309 return G_("comparison operator %q+D defaulted after "
3310 "its first declaration");
3312 check_abi_tag_redeclaration
3313 (olddecl, lookup_attribute ("abi_tag", DECL_ATTRIBUTES (olddecl)),
3314 lookup_attribute ("abi_tag", DECL_ATTRIBUTES (newdecl)));
3316 return NULL;
3318 else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
3320 tree nt, ot;
3322 if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == CONCEPT_DECL)
3323 return G_("redefinition of %q#D");
3325 if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) != FUNCTION_DECL)
3326 return redeclaration_error_message (DECL_TEMPLATE_RESULT (newdecl),
3327 DECL_TEMPLATE_RESULT (olddecl));
3329 if (DECL_TEMPLATE_RESULT (newdecl) == DECL_TEMPLATE_RESULT (olddecl))
3330 return NULL;
3332 nt = DECL_TEMPLATE_RESULT (newdecl);
3333 if (DECL_TEMPLATE_INFO (nt))
3334 nt = DECL_TEMPLATE_RESULT (template_for_substitution (nt));
3335 ot = DECL_TEMPLATE_RESULT (olddecl);
3336 if (DECL_TEMPLATE_INFO (ot))
3337 ot = DECL_TEMPLATE_RESULT (template_for_substitution (ot));
3338 if (DECL_INITIAL (nt) && DECL_INITIAL (ot)
3339 && (!GNU_INLINE_P (ot) || GNU_INLINE_P (nt)))
3340 return G_("redefinition of %q#D");
3342 if (DECL_DECLARED_INLINE_P (ot) && DECL_DECLARED_INLINE_P (nt))
3344 bool olda = GNU_INLINE_P (ot);
3345 bool newa = GNU_INLINE_P (nt);
3347 if (olda != newa)
3349 if (newa)
3350 return G_("%q+D redeclared inline with "
3351 "%<gnu_inline%> attribute");
3352 else
3353 return G_("%q+D redeclared inline without "
3354 "%<gnu_inline%> attribute");
3358 if (deduction_guide_p (olddecl)
3359 && deduction_guide_p (newdecl))
3360 return G_("deduction guide %q+D redeclared");
3362 /* Core issue #226 (C++11):
3364 If a friend function template declaration specifies a
3365 default template-argument, that declaration shall be a
3366 definition and shall be the only declaration of the
3367 function template in the translation unit. */
3368 if ((cxx_dialect != cxx98)
3369 && TREE_CODE (ot) == FUNCTION_DECL && DECL_UNIQUE_FRIEND_P (ot)
3370 && !check_default_tmpl_args (nt, DECL_TEMPLATE_PARMS (newdecl),
3371 /*is_primary=*/true,
3372 /*is_partial=*/false,
3373 /*is_friend_decl=*/2))
3374 return G_("redeclaration of friend %q#D "
3375 "may not have default template arguments");
3377 return NULL;
3379 else if (VAR_P (newdecl)
3380 && (CP_DECL_THREAD_LOCAL_P (newdecl)
3381 != CP_DECL_THREAD_LOCAL_P (olddecl))
3382 && (! DECL_LANG_SPECIFIC (olddecl)
3383 || ! CP_DECL_THREADPRIVATE_P (olddecl)
3384 || CP_DECL_THREAD_LOCAL_P (newdecl)))
3386 /* Only variables can be thread-local, and all declarations must
3387 agree on this property. */
3388 if (CP_DECL_THREAD_LOCAL_P (newdecl))
3389 return G_("thread-local declaration of %q#D follows "
3390 "non-thread-local declaration");
3391 else
3392 return G_("non-thread-local declaration of %q#D follows "
3393 "thread-local declaration");
3395 else if (toplevel_bindings_p () || DECL_NAMESPACE_SCOPE_P (newdecl))
3397 /* The objects have been declared at namespace scope. If either
3398 is a member of an anonymous union, then this is an invalid
3399 redeclaration. For example:
3401 int i;
3402 union { int i; };
3404 is invalid. */
3405 if ((VAR_P (newdecl) && DECL_ANON_UNION_VAR_P (newdecl))
3406 || (VAR_P (olddecl) && DECL_ANON_UNION_VAR_P (olddecl)))
3407 return G_("redeclaration of %q#D");
3408 /* If at least one declaration is a reference, there is no
3409 conflict. For example:
3411 int i = 3;
3412 extern int i;
3414 is valid. */
3415 if (DECL_EXTERNAL (newdecl) || DECL_EXTERNAL (olddecl))
3416 return NULL;
3418 /* Static data member declared outside a class definition
3419 if the variable is defined within the class with constexpr
3420 specifier is declaration rather than definition (and
3421 deprecated). */
3422 if (cxx_dialect >= cxx17
3423 && VAR_P (olddecl)
3424 && DECL_CLASS_SCOPE_P (olddecl)
3425 && DECL_DECLARED_CONSTEXPR_P (olddecl)
3426 && !DECL_INITIAL (newdecl))
3428 DECL_EXTERNAL (newdecl) = 1;
3429 /* For now, only warn with explicit -Wdeprecated. */
3430 if (OPTION_SET_P (warn_deprecated))
3432 auto_diagnostic_group d;
3433 if (warning_at (DECL_SOURCE_LOCATION (newdecl), OPT_Wdeprecated,
3434 "redundant redeclaration of %<constexpr%> "
3435 "static data member %qD", newdecl))
3436 inform (DECL_SOURCE_LOCATION (olddecl),
3437 "previous declaration of %qD", olddecl);
3439 return NULL;
3442 /* Reject two definitions. */
3443 return G_("redefinition of %q#D");
3445 else
3447 /* Objects declared with block scope: */
3448 /* Reject two definitions, and reject a definition
3449 together with an external reference. */
3450 if (!(DECL_EXTERNAL (newdecl) && DECL_EXTERNAL (olddecl)))
3451 return G_("redeclaration of %q#D");
3452 return NULL;
3457 /* Hash and equality functions for the named_label table. */
3459 hashval_t
3460 named_label_hash::hash (const value_type entry)
3462 return IDENTIFIER_HASH_VALUE (entry->name);
3465 bool
3466 named_label_hash::equal (const value_type entry, compare_type name)
3468 return name == entry->name;
3471 /* Look for a label named ID in the current function. If one cannot
3472 be found, create one. Return the named_label_entry, or NULL on
3473 failure. */
3475 static named_label_entry *
3476 lookup_label_1 (tree id, bool making_local_p)
3478 auto_cond_timevar tv (TV_NAME_LOOKUP);
3480 /* You can't use labels at global scope. */
3481 if (current_function_decl == NULL_TREE)
3483 error ("label %qE referenced outside of any function", id);
3484 return NULL;
3487 if (!named_labels)
3488 named_labels = hash_table<named_label_hash>::create_ggc (13);
3490 hashval_t hash = IDENTIFIER_HASH_VALUE (id);
3491 named_label_entry **slot
3492 = named_labels->find_slot_with_hash (id, hash, INSERT);
3493 named_label_entry *old = *slot;
3495 if (old && old->label_decl)
3497 if (!making_local_p)
3498 return old;
3500 if (old->binding_level == current_binding_level)
3502 error ("local label %qE conflicts with existing label", id);
3503 inform (DECL_SOURCE_LOCATION (old->label_decl), "previous label");
3504 return NULL;
3508 /* We are making a new decl, create or reuse the named_label_entry */
3509 named_label_entry *ent = NULL;
3510 if (old && !old->label_decl)
3511 ent = old;
3512 else
3514 ent = ggc_cleared_alloc<named_label_entry> ();
3515 ent->name = id;
3516 ent->outer = old;
3517 *slot = ent;
3520 /* Now create the LABEL_DECL. */
3521 tree decl = build_decl (input_location, LABEL_DECL, id, void_type_node);
3523 DECL_CONTEXT (decl) = current_function_decl;
3524 SET_DECL_MODE (decl, VOIDmode);
3525 if (making_local_p)
3527 C_DECLARED_LABEL_FLAG (decl) = true;
3528 DECL_CHAIN (decl) = current_binding_level->names;
3529 current_binding_level->names = decl;
3532 ent->label_decl = decl;
3534 return ent;
3537 /* Wrapper for lookup_label_1. */
3539 tree
3540 lookup_label (tree id)
3542 named_label_entry *ent = lookup_label_1 (id, false);
3543 return ent ? ent->label_decl : NULL_TREE;
3546 tree
3547 declare_local_label (tree id)
3549 named_label_entry *ent = lookup_label_1 (id, true);
3550 return ent ? ent->label_decl : NULL_TREE;
3553 /* Returns true if it is ill-formed to jump past the declaration of DECL. */
3555 static bool
3556 decl_jump_unsafe (tree decl)
3558 /* [stmt.dcl]/3: A program that jumps from a point where a local variable
3559 with automatic storage duration is not in scope to a point where it is
3560 in scope is ill-formed unless the variable has scalar type, class type
3561 with a trivial default constructor and a trivial destructor, a
3562 cv-qualified version of one of these types, or an array of one of the
3563 preceding types and is declared without an initializer (8.5). */
3564 tree type = TREE_TYPE (decl);
3566 return (type != error_mark_node
3567 && VAR_P (decl)
3568 && !TREE_STATIC (decl)
3569 && (DECL_NONTRIVIALLY_INITIALIZED_P (decl)
3570 || variably_modified_type_p (type, NULL_TREE)));
3573 /* A subroutine of check_previous_goto_1 and check_goto to identify a branch
3574 to the user. */
3576 static bool
3577 identify_goto (tree decl, location_t loc, const location_t *locus,
3578 diagnostic_t diag_kind)
3580 bool complained
3581 = emit_diagnostic (diag_kind, loc, 0,
3582 decl ? N_("jump to label %qD")
3583 : N_("jump to case label"), decl);
3584 if (complained && locus)
3585 inform (*locus, " from here");
3586 return complained;
3589 /* Check that a single previously seen jump to a newly defined label
3590 is OK. DECL is the LABEL_DECL or 0; LEVEL is the binding_level for
3591 the jump context; NAMES are the names in scope in LEVEL at the jump
3592 context; LOCUS is the source position of the jump or 0. Returns
3593 true if all is well. */
3595 static bool
3596 check_previous_goto_1 (tree decl, cp_binding_level* level, tree names,
3597 bool exited_omp, const location_t *locus)
3599 cp_binding_level *b;
3600 bool complained = false;
3601 int identified = 0;
3602 bool saw_eh = false, saw_omp = false, saw_tm = false, saw_cxif = false;
3603 bool saw_ceif = false, saw_se = false;
3605 if (exited_omp)
3607 complained = identify_goto (decl, input_location, locus, DK_ERROR);
3608 if (complained)
3609 inform (input_location, " exits OpenMP structured block");
3610 saw_omp = true;
3611 identified = 2;
3614 for (b = current_binding_level; b ; b = b->level_chain)
3616 tree new_decls, old_decls = (b == level ? names : NULL_TREE);
3618 for (new_decls = b->names; new_decls != old_decls;
3619 new_decls = (DECL_P (new_decls) ? DECL_CHAIN (new_decls)
3620 : TREE_CHAIN (new_decls)))
3622 bool problem = decl_jump_unsafe (new_decls);
3623 if (! problem)
3624 continue;
3626 if (!identified)
3628 complained = identify_goto (decl, input_location, locus, DK_ERROR);
3629 identified = 1;
3631 if (complained)
3632 inform (DECL_SOURCE_LOCATION (new_decls),
3633 " crosses initialization of %q#D", new_decls);
3636 if (b == level)
3637 break;
3639 const char *inf = NULL;
3640 location_t loc = input_location;
3641 switch (b->kind)
3643 case sk_try:
3644 if (!saw_eh)
3645 inf = G_(" enters %<try%> block");
3646 saw_eh = true;
3647 break;
3649 case sk_catch:
3650 if (!saw_eh)
3651 inf = G_(" enters %<catch%> block");
3652 saw_eh = true;
3653 break;
3655 case sk_omp:
3656 if (!saw_omp)
3657 inf = G_(" enters OpenMP structured block");
3658 saw_omp = true;
3659 break;
3661 case sk_transaction:
3662 if (!saw_tm)
3663 inf = G_(" enters synchronized or atomic statement");
3664 saw_tm = true;
3665 break;
3667 case sk_stmt_expr:
3668 if (!saw_se)
3669 inf = G_(" enters statement expression");
3670 saw_se = true;
3671 break;
3673 case sk_block:
3674 if (!saw_cxif && level_for_constexpr_if (b->level_chain))
3676 inf = G_(" enters %<constexpr if%> statement");
3677 loc = EXPR_LOCATION (b->level_chain->this_entity);
3678 saw_cxif = true;
3680 else if (!saw_ceif && level_for_consteval_if (b->level_chain))
3682 inf = G_(" enters %<consteval if%> statement");
3683 loc = EXPR_LOCATION (b->level_chain->this_entity);
3684 saw_ceif = true;
3686 break;
3688 default:
3689 break;
3692 if (inf)
3694 if (identified < 2)
3695 complained = identify_goto (decl, input_location, locus, DK_ERROR);
3696 identified = 2;
3697 if (complained)
3698 inform (loc, inf);
3702 return !identified;
3705 static void
3706 check_previous_goto (tree decl, struct named_label_use_entry *use)
3708 check_previous_goto_1 (decl, use->binding_level,
3709 use->names_in_scope, use->in_omp_scope,
3710 &use->o_goto_locus);
3713 static bool
3714 check_switch_goto (cp_binding_level* level)
3716 return check_previous_goto_1 (NULL_TREE, level, level->names, false, NULL);
3719 /* Check that a new jump to a label DECL is OK. Called by
3720 finish_goto_stmt. */
3722 void
3723 check_goto (tree decl)
3725 /* We can't know where a computed goto is jumping.
3726 So we assume that it's OK. */
3727 if (TREE_CODE (decl) != LABEL_DECL)
3728 return;
3730 hashval_t hash = IDENTIFIER_HASH_VALUE (DECL_NAME (decl));
3731 named_label_entry **slot
3732 = named_labels->find_slot_with_hash (DECL_NAME (decl), hash, NO_INSERT);
3733 named_label_entry *ent = *slot;
3735 /* If the label hasn't been defined yet, defer checking. */
3736 if (! DECL_INITIAL (decl))
3738 /* Don't bother creating another use if the last goto had the
3739 same data, and will therefore create the same set of errors. */
3740 if (ent->uses
3741 && ent->uses->names_in_scope == current_binding_level->names)
3742 return;
3744 named_label_use_entry *new_use
3745 = ggc_alloc<named_label_use_entry> ();
3746 new_use->binding_level = current_binding_level;
3747 new_use->names_in_scope = current_binding_level->names;
3748 new_use->o_goto_locus = input_location;
3749 new_use->in_omp_scope = false;
3751 new_use->next = ent->uses;
3752 ent->uses = new_use;
3753 return;
3756 bool saw_catch = false, complained = false;
3757 int identified = 0;
3758 tree bad;
3759 unsigned ix;
3761 if (ent->in_try_scope || ent->in_catch_scope || ent->in_transaction_scope
3762 || ent->in_constexpr_if || ent->in_consteval_if
3763 || ent->in_omp_scope || ent->in_stmt_expr
3764 || !vec_safe_is_empty (ent->bad_decls))
3766 diagnostic_t diag_kind = DK_PERMERROR;
3767 if (ent->in_try_scope || ent->in_catch_scope || ent->in_constexpr_if
3768 || ent->in_consteval_if || ent->in_transaction_scope
3769 || ent->in_omp_scope || ent->in_stmt_expr)
3770 diag_kind = DK_ERROR;
3771 complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3772 &input_location, diag_kind);
3773 identified = 1 + (diag_kind == DK_ERROR);
3776 FOR_EACH_VEC_SAFE_ELT (ent->bad_decls, ix, bad)
3778 bool problem = decl_jump_unsafe (bad);
3780 if (problem && DECL_ARTIFICIAL (bad))
3782 /* Can't skip init of __exception_info. */
3783 if (identified == 1)
3785 complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3786 &input_location, DK_ERROR);
3787 identified = 2;
3789 if (complained)
3790 inform (DECL_SOURCE_LOCATION (bad), " enters %<catch%> block");
3791 saw_catch = true;
3793 else if (complained)
3794 inform (DECL_SOURCE_LOCATION (bad),
3795 " skips initialization of %q#D", bad);
3798 if (complained)
3800 if (ent->in_try_scope)
3801 inform (input_location, " enters %<try%> block");
3802 else if (ent->in_catch_scope && !saw_catch)
3803 inform (input_location, " enters %<catch%> block");
3804 else if (ent->in_transaction_scope)
3805 inform (input_location, " enters synchronized or atomic statement");
3806 else if (ent->in_constexpr_if)
3807 inform (input_location, " enters %<constexpr if%> statement");
3808 else if (ent->in_consteval_if)
3809 inform (input_location, " enters %<consteval if%> statement");
3810 else if (ent->in_stmt_expr)
3811 inform (input_location, " enters statement expression");
3814 if (ent->in_omp_scope)
3816 if (complained)
3817 inform (input_location, " enters OpenMP structured block");
3819 else if (flag_openmp)
3820 for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3822 if (b == ent->binding_level)
3823 break;
3824 if (b->kind == sk_omp)
3826 if (identified < 2)
3828 complained = identify_goto (decl,
3829 DECL_SOURCE_LOCATION (decl),
3830 &input_location, DK_ERROR);
3831 identified = 2;
3833 if (complained)
3834 inform (input_location, " exits OpenMP structured block");
3835 break;
3840 /* Check that a return is ok wrt OpenMP structured blocks.
3841 Called by finish_return_stmt. Returns true if all is well. */
3843 bool
3844 check_omp_return (void)
3846 for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3847 if (b->kind == sk_omp)
3849 error ("invalid exit from OpenMP structured block");
3850 return false;
3852 else if (b->kind == sk_function_parms)
3853 break;
3854 return true;
3857 /* Define a label, specifying the location in the source file.
3858 Return the LABEL_DECL node for the label. */
3860 tree
3861 define_label (location_t location, tree name)
3863 auto_cond_timevar tv (TV_NAME_LOOKUP);
3865 /* After labels, make any new cleanups in the function go into their
3866 own new (temporary) binding contour. */
3867 for (cp_binding_level *p = current_binding_level;
3868 p->kind != sk_function_parms;
3869 p = p->level_chain)
3870 p->more_cleanups_ok = 0;
3872 named_label_entry *ent = lookup_label_1 (name, false);
3873 tree decl = ent->label_decl;
3875 if (DECL_INITIAL (decl) != NULL_TREE)
3877 error ("duplicate label %qD", decl);
3878 return error_mark_node;
3880 else
3882 /* Mark label as having been defined. */
3883 DECL_INITIAL (decl) = error_mark_node;
3884 /* Say where in the source. */
3885 DECL_SOURCE_LOCATION (decl) = location;
3887 ent->binding_level = current_binding_level;
3888 ent->names_in_scope = current_binding_level->names;
3890 for (named_label_use_entry *use = ent->uses; use; use = use->next)
3891 check_previous_goto (decl, use);
3892 ent->uses = NULL;
3895 return decl;
3898 struct cp_switch
3900 cp_binding_level *level;
3901 struct cp_switch *next;
3902 /* The SWITCH_STMT being built. */
3903 tree switch_stmt;
3904 /* A splay-tree mapping the low element of a case range to the high
3905 element, or NULL_TREE if there is no high element. Used to
3906 determine whether or not a new case label duplicates an old case
3907 label. We need a tree, rather than simply a hash table, because
3908 of the GNU case range extension. */
3909 splay_tree cases;
3910 /* Remember whether a default: case label has been seen. */
3911 bool has_default_p;
3912 /* Remember whether a BREAK_STMT has been seen in this SWITCH_STMT. */
3913 bool break_stmt_seen_p;
3914 /* Set if inside of {FOR,DO,WHILE}_BODY nested inside of a switch,
3915 where BREAK_STMT doesn't belong to the SWITCH_STMT. */
3916 bool in_loop_body_p;
3919 /* A stack of the currently active switch statements. The innermost
3920 switch statement is on the top of the stack. There is no need to
3921 mark the stack for garbage collection because it is only active
3922 during the processing of the body of a function, and we never
3923 collect at that point. */
3925 static struct cp_switch *switch_stack;
3927 /* Called right after a switch-statement condition is parsed.
3928 SWITCH_STMT is the switch statement being parsed. */
3930 void
3931 push_switch (tree switch_stmt)
3933 struct cp_switch *p = XNEW (struct cp_switch);
3934 p->level = current_binding_level;
3935 p->next = switch_stack;
3936 p->switch_stmt = switch_stmt;
3937 p->cases = splay_tree_new (case_compare, NULL, NULL);
3938 p->has_default_p = false;
3939 p->break_stmt_seen_p = false;
3940 p->in_loop_body_p = false;
3941 switch_stack = p;
3944 void
3945 pop_switch (void)
3947 struct cp_switch *cs = switch_stack;
3949 /* Emit warnings as needed. */
3950 location_t switch_location = cp_expr_loc_or_input_loc (cs->switch_stmt);
3951 tree cond = SWITCH_STMT_COND (cs->switch_stmt);
3952 const bool bool_cond_p
3953 = (SWITCH_STMT_TYPE (cs->switch_stmt)
3954 && TREE_CODE (SWITCH_STMT_TYPE (cs->switch_stmt)) == BOOLEAN_TYPE);
3955 if (!processing_template_decl)
3956 c_do_switch_warnings (cs->cases, switch_location,
3957 SWITCH_STMT_TYPE (cs->switch_stmt), cond,
3958 bool_cond_p);
3960 /* For the benefit of block_may_fallthru remember if the switch body
3961 case labels cover all possible values and if there are break; stmts. */
3962 if (cs->has_default_p
3963 || (!processing_template_decl
3964 && c_switch_covers_all_cases_p (cs->cases,
3965 SWITCH_STMT_TYPE (cs->switch_stmt))))
3966 SWITCH_STMT_ALL_CASES_P (cs->switch_stmt) = 1;
3967 if (!cs->break_stmt_seen_p)
3968 SWITCH_STMT_NO_BREAK_P (cs->switch_stmt) = 1;
3969 /* Now that we're done with the switch warnings, set the switch type
3970 to the type of the condition if the index type was of scoped enum type.
3971 (Such types don't participate in the integer promotions.) We do this
3972 because of bit-fields whose declared type is a scoped enum type:
3973 gimplification will use the lowered index type, but convert the
3974 case values to SWITCH_STMT_TYPE, which would have been the declared type
3975 and verify_gimple_switch doesn't accept that. */
3976 if (is_bitfield_expr_with_lowered_type (cond))
3977 SWITCH_STMT_TYPE (cs->switch_stmt) = TREE_TYPE (cond);
3978 gcc_assert (!cs->in_loop_body_p);
3979 splay_tree_delete (cs->cases);
3980 switch_stack = switch_stack->next;
3981 free (cs);
3984 /* Note that a BREAK_STMT is about to be added. If it is inside of
3985 a SWITCH_STMT and not inside of a loop body inside of it, note
3986 in switch_stack we've seen a BREAK_STMT. */
3988 void
3989 note_break_stmt (void)
3991 if (switch_stack && !switch_stack->in_loop_body_p)
3992 switch_stack->break_stmt_seen_p = true;
3995 /* Note the start of processing of an iteration statement's body.
3996 The note_break_stmt function will do nothing while processing it.
3997 Return a flag that should be passed to note_iteration_stmt_body_end. */
3999 bool
4000 note_iteration_stmt_body_start (void)
4002 if (!switch_stack)
4003 return false;
4004 bool ret = switch_stack->in_loop_body_p;
4005 switch_stack->in_loop_body_p = true;
4006 return ret;
4009 /* Note the end of processing of an iteration statement's body. */
4011 void
4012 note_iteration_stmt_body_end (bool prev)
4014 if (switch_stack)
4015 switch_stack->in_loop_body_p = prev;
4018 /* Convert a case constant VALUE in a switch to the type TYPE of the switch
4019 condition. Note that if TYPE and VALUE are already integral we don't
4020 really do the conversion because the language-independent
4021 warning/optimization code will work better that way. */
4023 static tree
4024 case_conversion (tree type, tree value)
4026 if (value == NULL_TREE)
4027 return value;
4029 value = mark_rvalue_use (value);
4031 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
4032 type = type_promotes_to (type);
4034 tree ovalue = value;
4035 /* The constant-expression VALUE shall be a converted constant expression
4036 of the adjusted type of the switch condition, which doesn't allow
4037 narrowing conversions. */
4038 value = build_converted_constant_expr (type, value, tf_warning_or_error);
4040 if (cxx_dialect >= cxx11
4041 && (SCOPED_ENUM_P (type)
4042 || !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ovalue))))
4043 /* Use the converted value. */;
4044 else
4045 /* The already integral case. */
4046 value = ovalue;
4048 return cxx_constant_value (value);
4051 /* Note that we've seen a definition of a case label, and complain if this
4052 is a bad place for one. */
4054 tree
4055 finish_case_label (location_t loc, tree low_value, tree high_value)
4057 tree cond, r;
4058 cp_binding_level *p;
4059 tree type;
4061 if (low_value == NULL_TREE && high_value == NULL_TREE)
4062 switch_stack->has_default_p = true;
4064 if (processing_template_decl)
4066 tree label;
4068 /* For templates, just add the case label; we'll do semantic
4069 analysis at instantiation-time. */
4070 label = build_decl (loc, LABEL_DECL, NULL_TREE, void_type_node);
4071 return add_stmt (build_case_label (low_value, high_value, label));
4074 /* Find the condition on which this switch statement depends. */
4075 cond = SWITCH_STMT_COND (switch_stack->switch_stmt);
4076 if (cond && TREE_CODE (cond) == TREE_LIST)
4077 cond = TREE_VALUE (cond);
4079 if (!check_switch_goto (switch_stack->level))
4080 return error_mark_node;
4082 type = SWITCH_STMT_TYPE (switch_stack->switch_stmt);
4083 if (type == error_mark_node)
4084 return error_mark_node;
4086 low_value = case_conversion (type, low_value);
4087 high_value = case_conversion (type, high_value);
4089 r = c_add_case_label (loc, switch_stack->cases, cond, low_value, high_value);
4091 /* After labels, make any new cleanups in the function go into their
4092 own new (temporary) binding contour. */
4093 for (p = current_binding_level;
4094 p->kind != sk_function_parms;
4095 p = p->level_chain)
4096 p->more_cleanups_ok = 0;
4098 return r;
4101 struct typename_info {
4102 tree scope;
4103 tree name;
4104 tree template_id;
4105 bool enum_p;
4106 bool class_p;
4109 struct typename_hasher : ggc_ptr_hash<tree_node>
4111 typedef typename_info *compare_type;
4113 /* Hash a TYPENAME_TYPE. */
4115 static hashval_t
4116 hash (tree context, tree fullname)
4118 hashval_t hash = 0;
4119 hash = iterative_hash_object (context, hash);
4120 hash = iterative_hash_object (fullname, hash);
4121 return hash;
4124 static hashval_t
4125 hash (const typename_info *ti)
4127 return typename_hasher::hash (ti->scope, ti->template_id);
4130 static hashval_t
4131 hash (tree t)
4133 return typename_hasher::hash (TYPE_CONTEXT (t), TYPENAME_TYPE_FULLNAME (t));
4136 /* Compare two TYPENAME_TYPEs. */
4138 static bool
4139 equal (tree t1, const typename_info *t2)
4141 return (TYPE_IDENTIFIER (t1) == t2->name
4142 && TYPE_CONTEXT (t1) == t2->scope
4143 && TYPENAME_TYPE_FULLNAME (t1) == t2->template_id
4144 && TYPENAME_IS_ENUM_P (t1) == t2->enum_p
4145 && TYPENAME_IS_CLASS_P (t1) == t2->class_p);
4149 /* Build a TYPENAME_TYPE. If the type is `typename T::t', CONTEXT is
4150 the type of `T', NAME is the IDENTIFIER_NODE for `t'.
4152 Returns the new TYPENAME_TYPE. */
4154 static GTY (()) hash_table<typename_hasher> *typename_htab;
4156 tree
4157 build_typename_type (tree context, tree name, tree fullname,
4158 enum tag_types tag_type)
4160 typename_info ti;
4162 if (typename_htab == NULL)
4163 typename_htab = hash_table<typename_hasher>::create_ggc (61);
4165 ti.scope = FROB_CONTEXT (context);
4166 ti.name = name;
4167 ti.template_id = fullname;
4168 ti.enum_p = tag_type == enum_type;
4169 ti.class_p = (tag_type == class_type
4170 || tag_type == record_type
4171 || tag_type == union_type);
4172 hashval_t hash = typename_hasher::hash (&ti);
4174 /* See if we already have this type. */
4175 tree *e = typename_htab->find_slot_with_hash (&ti, hash, INSERT);
4176 tree t = *e;
4177 if (*e)
4178 t = *e;
4179 else
4181 /* Build the TYPENAME_TYPE. */
4182 t = cxx_make_type (TYPENAME_TYPE);
4183 TYPE_CONTEXT (t) = ti.scope;
4184 TYPENAME_TYPE_FULLNAME (t) = ti.template_id;
4185 TYPENAME_IS_ENUM_P (t) = ti.enum_p;
4186 TYPENAME_IS_CLASS_P (t) = ti.class_p;
4188 /* Build the corresponding TYPE_DECL. */
4189 tree d = build_decl (input_location, TYPE_DECL, name, t);
4190 TYPE_NAME (t) = d;
4191 TYPE_STUB_DECL (t) = d;
4192 DECL_CONTEXT (d) = ti.scope;
4193 DECL_ARTIFICIAL (d) = 1;
4195 /* Store it in the hash table. */
4196 *e = t;
4198 /* TYPENAME_TYPEs must always be compared structurally, because
4199 they may or may not resolve down to another type depending on
4200 the currently open classes. */
4201 SET_TYPE_STRUCTURAL_EQUALITY (t);
4204 return t;
4207 /* Resolve `typename CONTEXT::NAME'. TAG_TYPE indicates the tag
4208 provided to name the type. Returns an appropriate type, unless an
4209 error occurs, in which case error_mark_node is returned. If we
4210 locate a non-artificial TYPE_DECL and TF_KEEP_TYPE_DECL is set, we
4211 return that, rather than the _TYPE it corresponds to, in other
4212 cases we look through the type decl. If TF_ERROR is set, complain
4213 about errors, otherwise be quiet. */
4215 tree
4216 make_typename_type (tree context, tree name, enum tag_types tag_type,
4217 tsubst_flags_t complain)
4219 tree fullname;
4220 tree t;
4221 bool want_template;
4223 if (name == error_mark_node
4224 || context == NULL_TREE
4225 || context == error_mark_node)
4226 return error_mark_node;
4228 if (TYPE_P (name))
4230 if (!(TYPE_LANG_SPECIFIC (name)
4231 && (CLASSTYPE_IS_TEMPLATE (name)
4232 || CLASSTYPE_USE_TEMPLATE (name))))
4233 name = TYPE_IDENTIFIER (name);
4234 else
4235 /* Create a TEMPLATE_ID_EXPR for the type. */
4236 name = build_nt (TEMPLATE_ID_EXPR,
4237 CLASSTYPE_TI_TEMPLATE (name),
4238 CLASSTYPE_TI_ARGS (name));
4240 else if (TREE_CODE (name) == TYPE_DECL)
4241 name = DECL_NAME (name);
4243 fullname = name;
4245 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
4247 name = TREE_OPERAND (name, 0);
4248 if (DECL_TYPE_TEMPLATE_P (name))
4249 name = TREE_OPERAND (fullname, 0) = DECL_NAME (name);
4250 if (TREE_CODE (name) != IDENTIFIER_NODE)
4252 if (complain & tf_error)
4253 error ("%qD is not a type", name);
4254 return error_mark_node;
4257 if (TREE_CODE (name) == TEMPLATE_DECL)
4259 if (complain & tf_error)
4260 error ("%qD used without template arguments", name);
4261 return error_mark_node;
4263 else if (is_overloaded_fn (name))
4265 if (complain & tf_error)
4266 error ("%qD is a function, not a type", name);
4267 return error_mark_node;
4269 gcc_assert (identifier_p (name));
4270 gcc_assert (TYPE_P (context));
4272 if (TREE_CODE (context) == TYPE_PACK_EXPANSION)
4273 /* This can happen for C++17 variadic using (c++/88986). */;
4274 else if (!MAYBE_CLASS_TYPE_P (context))
4276 if (complain & tf_error)
4277 error ("%q#T is not a class", context);
4278 return error_mark_node;
4281 /* When the CONTEXT is a dependent type, NAME could refer to a
4282 dependent base class of CONTEXT. But look inside it anyway
4283 if CONTEXT is a currently open scope, in case it refers to a
4284 member of the current instantiation or a non-dependent base;
4285 lookup will stop when we hit a dependent base. */
4286 if (!dependent_scope_p (context))
4288 /* We generally don't ignore non-types during TYPENAME_TYPE lookup
4289 (as per [temp.res.general]/3), unless
4290 - the tag corresponds to a class-key or 'enum' so
4291 [basic.lookup.elab] applies, or
4292 - the tag corresponds to scope_type or tf_qualifying_scope is
4293 set so [basic.lookup.qual]/1 applies.
4294 TODO: If we'd set/track the scope_type tag thoroughly on all
4295 TYPENAME_TYPEs that are followed by :: then we wouldn't need the
4296 tf_qualifying_scope flag. */
4297 bool want_type = (tag_type != none_type && tag_type != typename_type)
4298 || (complain & tf_qualifying_scope);
4299 t = lookup_member (context, name, /*protect=*/2, want_type, complain);
4301 else
4302 t = NULL_TREE;
4304 if ((!t || TREE_CODE (t) == TREE_LIST) && dependent_type_p (context))
4305 return build_typename_type (context, name, fullname, tag_type);
4307 want_template = TREE_CODE (fullname) == TEMPLATE_ID_EXPR;
4309 if (!t)
4311 if (complain & tf_error)
4313 if (!COMPLETE_TYPE_P (context))
4314 cxx_incomplete_type_error (NULL_TREE, context);
4315 else
4316 error (want_template ? G_("no class template named %q#T in %q#T")
4317 : G_("no type named %q#T in %q#T"), name, context);
4319 return error_mark_node;
4322 /* Pull out the template from an injected-class-name (or multiple). */
4323 if (want_template)
4324 t = maybe_get_template_decl_from_type_decl (t);
4326 if (TREE_CODE (t) == TREE_LIST)
4328 if (complain & tf_error)
4330 error ("lookup of %qT in %qT is ambiguous", name, context);
4331 print_candidates (t);
4333 return error_mark_node;
4336 if (want_template && !DECL_TYPE_TEMPLATE_P (t))
4338 if (complain & tf_error)
4339 error ("%<typename %T::%D%> names %q#T, which is not a class template",
4340 context, name, t);
4341 return error_mark_node;
4343 if (!want_template && TREE_CODE (t) != TYPE_DECL)
4345 if ((complain & tf_tst_ok) && cxx_dialect >= cxx17
4346 && DECL_TYPE_TEMPLATE_P (t))
4347 /* The caller permits this typename-specifier to name a template
4348 (because it appears in a CTAD-enabled context). */;
4349 else
4351 if (complain & tf_error)
4352 error ("%<typename %T::%D%> names %q#D, which is not a type",
4353 context, name, t);
4354 return error_mark_node;
4358 if (!check_accessibility_of_qualified_id (t, /*object_type=*/NULL_TREE,
4359 context, complain))
4360 return error_mark_node;
4362 if (!want_template && DECL_TYPE_TEMPLATE_P (t))
4363 return make_template_placeholder (t);
4365 if (want_template)
4367 t = lookup_template_class (t, TREE_OPERAND (fullname, 1),
4368 NULL_TREE, context,
4369 /*entering_scope=*/0,
4370 complain | tf_user);
4371 if (t == error_mark_node)
4372 return error_mark_node;
4373 t = TYPE_NAME (t);
4376 if (DECL_ARTIFICIAL (t) || !(complain & tf_keep_type_decl))
4377 t = TREE_TYPE (t);
4379 maybe_record_typedef_use (t);
4381 return t;
4384 /* Resolve `CONTEXT::template NAME'. Returns a TEMPLATE_DECL if the name
4385 can be resolved or an UNBOUND_CLASS_TEMPLATE, unless an error occurs,
4386 in which case error_mark_node is returned.
4388 If PARM_LIST is non-NULL, also make sure that the template parameter
4389 list of TEMPLATE_DECL matches.
4391 If COMPLAIN zero, don't complain about any errors that occur. */
4393 tree
4394 make_unbound_class_template (tree context, tree name, tree parm_list,
4395 tsubst_flags_t complain)
4397 if (TYPE_P (name))
4398 name = TYPE_IDENTIFIER (name);
4399 else if (DECL_P (name))
4400 name = DECL_NAME (name);
4401 gcc_assert (identifier_p (name));
4403 if (!dependent_type_p (context)
4404 || currently_open_class (context))
4406 tree tmpl = NULL_TREE;
4408 if (MAYBE_CLASS_TYPE_P (context))
4409 tmpl = lookup_field (context, name, 0, false);
4411 if (tmpl && TREE_CODE (tmpl) == TYPE_DECL)
4412 tmpl = maybe_get_template_decl_from_type_decl (tmpl);
4414 if (!tmpl || !DECL_TYPE_TEMPLATE_P (tmpl))
4416 if (complain & tf_error)
4417 error ("no class template named %q#T in %q#T", name, context);
4418 return error_mark_node;
4421 if (parm_list
4422 && !comp_template_parms (DECL_TEMPLATE_PARMS (tmpl), parm_list))
4424 if (complain & tf_error)
4426 error ("template parameters do not match template %qD", tmpl);
4427 inform (DECL_SOURCE_LOCATION (tmpl),
4428 "%qD declared here", tmpl);
4430 return error_mark_node;
4433 if (!perform_or_defer_access_check (TYPE_BINFO (context), tmpl, tmpl,
4434 complain))
4435 return error_mark_node;
4437 return tmpl;
4440 return make_unbound_class_template_raw (context, name, parm_list);
4443 /* Build an UNBOUND_CLASS_TEMPLATE. */
4445 tree
4446 make_unbound_class_template_raw (tree context, tree name, tree parm_list)
4448 /* Build the UNBOUND_CLASS_TEMPLATE. */
4449 tree t = cxx_make_type (UNBOUND_CLASS_TEMPLATE);
4450 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
4451 TREE_TYPE (t) = NULL_TREE;
4452 SET_TYPE_STRUCTURAL_EQUALITY (t);
4454 /* Build the corresponding TEMPLATE_DECL. */
4455 tree d = build_decl (input_location, TEMPLATE_DECL, name, t);
4456 TYPE_NAME (t) = d;
4457 TYPE_STUB_DECL (t) = d;
4458 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
4459 DECL_ARTIFICIAL (d) = 1;
4460 DECL_TEMPLATE_PARMS (d) = parm_list;
4462 return t;
4467 /* Push the declarations of builtin types into the global namespace.
4468 RID_INDEX is the index of the builtin type in the array
4469 RID_POINTERS. NAME is the name used when looking up the builtin
4470 type. TYPE is the _TYPE node for the builtin type.
4472 The calls to set_global_binding below should be
4473 eliminated. Built-in types should not be looked up name; their
4474 names are keywords that the parser can recognize. However, there
4475 is code in c-common.cc that uses identifier_global_value to look up
4476 built-in types by name. */
4478 void
4479 record_builtin_type (enum rid rid_index,
4480 const char* name,
4481 tree type)
4483 tree decl = NULL_TREE;
4485 if (name)
4487 tree tname = get_identifier (name);
4488 tree tdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, tname, type);
4489 DECL_ARTIFICIAL (tdecl) = 1;
4490 set_global_binding (tdecl);
4491 decl = tdecl;
4494 if ((int) rid_index < (int) RID_MAX)
4495 if (tree rname = ridpointers[(int) rid_index])
4496 if (!decl || DECL_NAME (decl) != rname)
4498 tree rdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, rname, type);
4499 DECL_ARTIFICIAL (rdecl) = 1;
4500 set_global_binding (rdecl);
4501 if (!decl)
4502 decl = rdecl;
4505 if (decl)
4507 if (!TYPE_NAME (type))
4508 TYPE_NAME (type) = decl;
4509 debug_hooks->type_decl (decl, 0);
4513 /* Push a type into the namespace so that the back ends ignore it. */
4515 static void
4516 record_unknown_type (tree type, const char* name)
4518 tree decl = pushdecl (build_decl (UNKNOWN_LOCATION,
4519 TYPE_DECL, get_identifier (name), type));
4520 /* Make sure the "unknown type" typedecl gets ignored for debug info. */
4521 DECL_IGNORED_P (decl) = 1;
4522 TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
4523 TYPE_SIZE (type) = TYPE_SIZE (void_type_node);
4524 SET_TYPE_ALIGN (type, 1);
4525 TYPE_USER_ALIGN (type) = 0;
4526 SET_TYPE_MODE (type, TYPE_MODE (void_type_node));
4529 /* Create all the predefined identifiers. */
4531 static void
4532 initialize_predefined_identifiers (void)
4534 struct predefined_identifier
4536 const char *name; /* Name. */
4537 tree *node; /* Node to store it in. */
4538 cp_identifier_kind kind; /* Kind of identifier. */
4541 /* A table of identifiers to create at startup. */
4542 static const predefined_identifier predefined_identifiers[] = {
4543 {"C++", &lang_name_cplusplus, cik_normal},
4544 {"C", &lang_name_c, cik_normal},
4545 /* Some of these names have a trailing space so that it is
4546 impossible for them to conflict with names written by users. */
4547 {"__ct ", &ctor_identifier, cik_ctor},
4548 {"__ct_base ", &base_ctor_identifier, cik_ctor},
4549 {"__ct_comp ", &complete_ctor_identifier, cik_ctor},
4550 {"__dt ", &dtor_identifier, cik_dtor},
4551 {"__dt_base ", &base_dtor_identifier, cik_dtor},
4552 {"__dt_comp ", &complete_dtor_identifier, cik_dtor},
4553 {"__dt_del ", &deleting_dtor_identifier, cik_dtor},
4554 {"__conv_op ", &conv_op_identifier, cik_conv_op},
4555 {"__in_chrg", &in_charge_identifier, cik_normal},
4556 {"__as_base ", &as_base_identifier, cik_normal},
4557 {"this", &this_identifier, cik_normal},
4558 {"__delta", &delta_identifier, cik_normal},
4559 {"__pfn", &pfn_identifier, cik_normal},
4560 {"_vptr", &vptr_identifier, cik_normal},
4561 {"__vtt_parm", &vtt_parm_identifier, cik_normal},
4562 {"::", &global_identifier, cik_normal},
4563 /* The demangler expects anonymous namespaces to be called
4564 something starting with '_GLOBAL__N_'. It no longer needs
4565 to be unique to the TU. */
4566 {"_GLOBAL__N_1", &anon_identifier, cik_normal},
4567 {"auto", &auto_identifier, cik_normal},
4568 {"decltype(auto)", &decltype_auto_identifier, cik_normal},
4569 {"initializer_list", &init_list_identifier, cik_normal},
4570 {"__for_range ", &for_range__identifier, cik_normal},
4571 {"__for_begin ", &for_begin__identifier, cik_normal},
4572 {"__for_end ", &for_end__identifier, cik_normal},
4573 {"__for_range", &for_range_identifier, cik_normal},
4574 {"__for_begin", &for_begin_identifier, cik_normal},
4575 {"__for_end", &for_end_identifier, cik_normal},
4576 {"abi_tag", &abi_tag_identifier, cik_normal},
4577 {"aligned", &aligned_identifier, cik_normal},
4578 {"begin", &begin_identifier, cik_normal},
4579 {"end", &end_identifier, cik_normal},
4580 {"get", &get__identifier, cik_normal},
4581 {"gnu", &gnu_identifier, cik_normal},
4582 {"tuple_element", &tuple_element_identifier, cik_normal},
4583 {"tuple_size", &tuple_size_identifier, cik_normal},
4584 {"type", &type_identifier, cik_normal},
4585 {"value", &value_identifier, cik_normal},
4586 {"_FUN", &fun_identifier, cik_normal},
4587 {"__closure", &closure_identifier, cik_normal},
4588 {"heap uninit", &heap_uninit_identifier, cik_normal},
4589 {"heap ", &heap_identifier, cik_normal},
4590 {"heap deleted", &heap_deleted_identifier, cik_normal},
4591 {"heap [] uninit", &heap_vec_uninit_identifier, cik_normal},
4592 {"heap []", &heap_vec_identifier, cik_normal},
4593 {"omp", &omp_identifier, cik_normal},
4594 {NULL, NULL, cik_normal}
4597 for (const predefined_identifier *pid = predefined_identifiers;
4598 pid->name; ++pid)
4600 *pid->node = get_identifier (pid->name);
4601 /* Some of these identifiers already have a special kind. */
4602 if (pid->kind != cik_normal)
4603 set_identifier_kind (*pid->node, pid->kind);
4607 /* Create the predefined scalar types of C,
4608 and some nodes representing standard constants (0, 1, (void *)0).
4609 Initialize the global binding level.
4610 Make definitions for built-in primitive functions. */
4612 void
4613 cxx_init_decl_processing (void)
4615 tree void_ftype;
4616 tree void_ftype_ptr;
4618 /* Create all the identifiers we need. */
4619 initialize_predefined_identifiers ();
4621 /* Create the global variables. */
4622 push_to_top_level ();
4624 current_function_decl = NULL_TREE;
4625 current_binding_level = NULL;
4626 /* Enter the global namespace. */
4627 gcc_assert (global_namespace == NULL_TREE);
4628 global_namespace = build_lang_decl (NAMESPACE_DECL, global_identifier,
4629 void_type_node);
4630 TREE_PUBLIC (global_namespace) = true;
4631 DECL_MODULE_EXPORT_P (global_namespace) = true;
4632 DECL_CONTEXT (global_namespace)
4633 = build_translation_unit_decl (get_identifier (main_input_filename));
4634 /* Remember whether we want the empty class passing ABI change warning
4635 in this TU. */
4636 TRANSLATION_UNIT_WARN_EMPTY_P (DECL_CONTEXT (global_namespace))
4637 = warn_abi && abi_version_crosses (12);
4638 debug_hooks->register_main_translation_unit
4639 (DECL_CONTEXT (global_namespace));
4640 begin_scope (sk_namespace, global_namespace);
4641 current_namespace = global_namespace;
4643 if (flag_visibility_ms_compat)
4644 default_visibility = VISIBILITY_HIDDEN;
4646 /* Initially, C. */
4647 current_lang_name = lang_name_c;
4649 /* Create the `std' namespace. */
4650 push_namespace (get_identifier ("std"));
4651 std_node = current_namespace;
4652 pop_namespace ();
4654 flag_noexcept_type = (cxx_dialect >= cxx17);
4656 c_common_nodes_and_builtins ();
4658 tree bool_ftype = build_function_type_list (boolean_type_node, NULL_TREE);
4659 tree decl
4660 = add_builtin_function ("__builtin_is_constant_evaluated",
4661 bool_ftype, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
4662 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4663 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4665 /* The concrete return type of __builtin_source_location is
4666 const std::source_location::__impl*, but we can't form the type
4667 at this point. So we initially declare it with an auto return
4668 type which we then "deduce" from require_deduced_type upon first use. */
4669 tree auto_ftype = build_function_type_list (make_auto (), NULL_TREE);
4670 decl = add_builtin_function ("__builtin_source_location",
4671 auto_ftype, CP_BUILT_IN_SOURCE_LOCATION,
4672 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4673 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4675 tree bool_vaftype = build_varargs_function_type_list (boolean_type_node,
4676 NULL_TREE);
4677 decl
4678 = add_builtin_function ("__builtin_is_corresponding_member",
4679 bool_vaftype,
4680 CP_BUILT_IN_IS_CORRESPONDING_MEMBER,
4681 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4682 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4684 decl
4685 = add_builtin_function ("__builtin_is_pointer_interconvertible_with_class",
4686 bool_vaftype,
4687 CP_BUILT_IN_IS_POINTER_INTERCONVERTIBLE_WITH_CLASS,
4688 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4689 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4691 integer_two_node = build_int_cst (NULL_TREE, 2);
4693 /* Guess at the initial static decls size. */
4694 vec_alloc (static_decls, 500);
4696 /* ... and keyed classes. */
4697 vec_alloc (keyed_classes, 100);
4699 record_builtin_type (RID_BOOL, "bool", boolean_type_node);
4700 truthvalue_type_node = boolean_type_node;
4701 truthvalue_false_node = boolean_false_node;
4702 truthvalue_true_node = boolean_true_node;
4704 empty_except_spec = build_tree_list (NULL_TREE, NULL_TREE);
4705 noexcept_true_spec = build_tree_list (boolean_true_node, NULL_TREE);
4706 noexcept_false_spec = build_tree_list (boolean_false_node, NULL_TREE);
4707 noexcept_deferred_spec = build_tree_list (make_node (DEFERRED_NOEXCEPT),
4708 NULL_TREE);
4710 #if 0
4711 record_builtin_type (RID_MAX, NULL, string_type_node);
4712 #endif
4714 delta_type_node = ptrdiff_type_node;
4715 vtable_index_type = ptrdiff_type_node;
4717 vtt_parm_type = build_pointer_type (const_ptr_type_node);
4718 void_ftype = build_function_type_list (void_type_node, NULL_TREE);
4719 void_ftype_ptr = build_function_type_list (void_type_node,
4720 ptr_type_node, NULL_TREE);
4721 void_ftype_ptr
4722 = build_exception_variant (void_ftype_ptr, empty_except_spec);
4724 /* Create the conversion operator marker. This operator's DECL_NAME
4725 is in the identifier table, so we can use identifier equality to
4726 find it. */
4727 conv_op_marker = build_lang_decl (FUNCTION_DECL, conv_op_identifier,
4728 void_ftype);
4730 /* C++ extensions */
4732 unknown_type_node = make_node (LANG_TYPE);
4733 record_unknown_type (unknown_type_node, "unknown type");
4735 /* Indirecting an UNKNOWN_TYPE node yields an UNKNOWN_TYPE node. */
4736 TREE_TYPE (unknown_type_node) = unknown_type_node;
4738 /* Looking up TYPE_POINTER_TO and TYPE_REFERENCE_TO yield the same
4739 result. */
4740 TYPE_POINTER_TO (unknown_type_node) = unknown_type_node;
4741 TYPE_REFERENCE_TO (unknown_type_node) = unknown_type_node;
4743 init_list_type_node = make_node (LANG_TYPE);
4744 record_unknown_type (init_list_type_node, "init list");
4746 /* Used when parsing to distinguish parameter-lists () and (void). */
4747 explicit_void_list_node = build_tree_list (NULL_TREE, void_type_node);
4750 /* Make sure we get a unique function type, so we can give
4751 its pointer type a name. (This wins for gdb.) */
4752 tree vfunc_type = make_node (FUNCTION_TYPE);
4753 TREE_TYPE (vfunc_type) = integer_type_node;
4754 TYPE_ARG_TYPES (vfunc_type) = NULL_TREE;
4755 layout_type (vfunc_type);
4757 vtable_entry_type = build_pointer_type (vfunc_type);
4759 record_builtin_type (RID_MAX, "__vtbl_ptr_type", vtable_entry_type);
4761 vtbl_type_node
4762 = build_cplus_array_type (vtable_entry_type, NULL_TREE);
4763 layout_type (vtbl_type_node);
4764 vtbl_type_node = cp_build_qualified_type (vtbl_type_node, TYPE_QUAL_CONST);
4765 record_builtin_type (RID_MAX, NULL, vtbl_type_node);
4766 vtbl_ptr_type_node = build_pointer_type (vtable_entry_type);
4767 layout_type (vtbl_ptr_type_node);
4768 record_builtin_type (RID_MAX, NULL, vtbl_ptr_type_node);
4770 push_namespace (get_identifier ("__cxxabiv1"));
4771 abi_node = current_namespace;
4772 pop_namespace ();
4774 any_targ_node = make_node (LANG_TYPE);
4775 record_unknown_type (any_targ_node, "any type");
4777 /* Now, C++. */
4778 current_lang_name = lang_name_cplusplus;
4780 if (aligned_new_threshold > 1
4781 && !pow2p_hwi (aligned_new_threshold))
4783 error ("%<-faligned-new=%d%> is not a power of two",
4784 aligned_new_threshold);
4785 aligned_new_threshold = 1;
4787 if (aligned_new_threshold == -1)
4788 aligned_new_threshold = (cxx_dialect >= cxx17) ? 1 : 0;
4789 if (aligned_new_threshold == 1)
4790 aligned_new_threshold = malloc_alignment () / BITS_PER_UNIT;
4793 tree newattrs, extvisattr;
4794 tree newtype, deltype;
4795 tree ptr_ftype_sizetype;
4796 tree new_eh_spec;
4798 ptr_ftype_sizetype
4799 = build_function_type_list (ptr_type_node, size_type_node, NULL_TREE);
4800 if (cxx_dialect == cxx98)
4802 tree bad_alloc_id;
4803 tree bad_alloc_type_node;
4804 tree bad_alloc_decl;
4806 push_nested_namespace (std_node);
4807 bad_alloc_id = get_identifier ("bad_alloc");
4808 bad_alloc_type_node = make_class_type (RECORD_TYPE);
4809 TYPE_CONTEXT (bad_alloc_type_node) = current_namespace;
4810 bad_alloc_decl
4811 = create_implicit_typedef (bad_alloc_id, bad_alloc_type_node);
4812 DECL_CONTEXT (bad_alloc_decl) = current_namespace;
4813 pop_nested_namespace (std_node);
4815 new_eh_spec
4816 = add_exception_specifier (NULL_TREE, bad_alloc_type_node, -1);
4818 else
4819 new_eh_spec = noexcept_false_spec;
4821 /* Ensure attribs.cc is initialized. */
4822 init_attributes ();
4824 extvisattr = build_tree_list (get_identifier ("externally_visible"),
4825 NULL_TREE);
4826 newattrs = tree_cons (get_identifier ("alloc_size"),
4827 build_tree_list (NULL_TREE, integer_one_node),
4828 extvisattr);
4829 newtype = cp_build_type_attribute_variant (ptr_ftype_sizetype, newattrs);
4830 newtype = build_exception_variant (newtype, new_eh_spec);
4831 deltype = cp_build_type_attribute_variant (void_ftype_ptr, extvisattr);
4832 deltype = build_exception_variant (deltype, empty_except_spec);
4833 tree opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
4834 DECL_IS_MALLOC (opnew) = 1;
4835 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4836 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4837 opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
4838 DECL_IS_MALLOC (opnew) = 1;
4839 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4840 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4841 tree opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4842 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4843 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4844 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4845 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4846 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4847 if (flag_sized_deallocation)
4849 /* Also push the sized deallocation variants:
4850 void operator delete(void*, std::size_t) throw();
4851 void operator delete[](void*, std::size_t) throw(); */
4852 tree void_ftype_ptr_size
4853 = build_function_type_list (void_type_node, ptr_type_node,
4854 size_type_node, NULL_TREE);
4855 deltype = cp_build_type_attribute_variant (void_ftype_ptr_size,
4856 extvisattr);
4857 deltype = build_exception_variant (deltype, empty_except_spec);
4858 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4859 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4860 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4861 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4862 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4863 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4866 if (aligned_new_threshold)
4868 push_nested_namespace (std_node);
4869 tree align_id = get_identifier ("align_val_t");
4870 align_type_node = start_enum (align_id, NULL_TREE, size_type_node,
4871 NULL_TREE, /*scoped*/true, NULL);
4872 pop_nested_namespace (std_node);
4874 /* operator new (size_t, align_val_t); */
4875 newtype = build_function_type_list (ptr_type_node, size_type_node,
4876 align_type_node, NULL_TREE);
4877 newtype = cp_build_type_attribute_variant (newtype, newattrs);
4878 newtype = build_exception_variant (newtype, new_eh_spec);
4879 opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
4880 DECL_IS_MALLOC (opnew) = 1;
4881 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4882 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4883 opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
4884 DECL_IS_MALLOC (opnew) = 1;
4885 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4886 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4888 /* operator delete (void *, align_val_t); */
4889 deltype = build_function_type_list (void_type_node, ptr_type_node,
4890 align_type_node, NULL_TREE);
4891 deltype = cp_build_type_attribute_variant (deltype, extvisattr);
4892 deltype = build_exception_variant (deltype, empty_except_spec);
4893 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4894 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4895 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4896 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4897 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4898 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4900 if (flag_sized_deallocation)
4902 /* operator delete (void *, size_t, align_val_t); */
4903 deltype = build_function_type_list (void_type_node, ptr_type_node,
4904 size_type_node, align_type_node,
4905 NULL_TREE);
4906 deltype = cp_build_type_attribute_variant (deltype, extvisattr);
4907 deltype = build_exception_variant (deltype, empty_except_spec);
4908 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4909 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4910 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4911 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4912 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4913 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4917 /* C++-specific nullptr initialization. */
4918 if (abi_version_at_least (9))
4919 SET_TYPE_ALIGN (nullptr_type_node, GET_MODE_ALIGNMENT (ptr_mode));
4920 record_builtin_type (RID_MAX, "decltype(nullptr)", nullptr_type_node);
4923 if (! supports_one_only ())
4924 flag_weak = 0;
4926 abort_fndecl
4927 = build_library_fn_ptr ("__cxa_pure_virtual", void_ftype,
4928 ECF_NORETURN | ECF_NOTHROW | ECF_COLD);
4929 if (flag_weak)
4930 /* If no definition is available, resolve references to NULL. */
4931 declare_weak (abort_fndecl);
4933 /* Perform other language dependent initializations. */
4934 init_class_processing ();
4935 init_rtti_processing ();
4936 init_template_processing ();
4938 if (flag_exceptions)
4939 init_exception_processing ();
4941 if (modules_p ())
4942 init_modules (parse_in);
4944 make_fname_decl = cp_make_fname_decl;
4945 start_fname_decls ();
4947 /* Show we use EH for cleanups. */
4948 if (flag_exceptions)
4949 using_eh_for_cleanups ();
4951 /* Check that the hardware interference sizes are at least
4952 alignof(max_align_t), as required by the standard. */
4953 const int max_align = max_align_t_align () / BITS_PER_UNIT;
4954 if (OPTION_SET_P (param_destruct_interfere_size))
4956 if (param_destruct_interfere_size < max_align)
4957 error ("%<--param destructive-interference-size=%d%> is less than "
4958 "%d", param_destruct_interfere_size, max_align);
4959 else if (param_destruct_interfere_size < param_l1_cache_line_size)
4960 warning (OPT_Winterference_size,
4961 "%<--param destructive-interference-size=%d%> "
4962 "is less than %<--param l1-cache-line-size=%d%>",
4963 param_destruct_interfere_size, param_l1_cache_line_size);
4965 else if (param_destruct_interfere_size)
4966 /* Assume the internal value is OK. */;
4967 else if (param_l1_cache_line_size >= max_align)
4968 param_destruct_interfere_size = param_l1_cache_line_size;
4969 /* else leave it unset. */
4971 if (OPTION_SET_P (param_construct_interfere_size))
4973 if (param_construct_interfere_size < max_align)
4974 error ("%<--param constructive-interference-size=%d%> is less than "
4975 "%d", param_construct_interfere_size, max_align);
4976 else if (param_construct_interfere_size > param_l1_cache_line_size
4977 && param_l1_cache_line_size >= max_align)
4978 warning (OPT_Winterference_size,
4979 "%<--param constructive-interference-size=%d%> "
4980 "is greater than %<--param l1-cache-line-size=%d%>",
4981 param_construct_interfere_size, param_l1_cache_line_size);
4983 else if (param_construct_interfere_size)
4984 /* Assume the internal value is OK. */;
4985 else if (param_l1_cache_line_size >= max_align)
4986 param_construct_interfere_size = param_l1_cache_line_size;
4989 /* Enter an abi node in global-module context. returns a cookie to
4990 give to pop_abi_namespace. */
4992 unsigned
4993 push_abi_namespace (tree node)
4995 push_nested_namespace (node);
4996 push_visibility ("default", 2);
4997 unsigned flags = module_kind;
4998 module_kind = 0;
4999 return flags;
5002 /* Pop an abi namespace, FLAGS is the cookie push_abi_namespace gave
5003 you. */
5005 void
5006 pop_abi_namespace (unsigned flags, tree node)
5008 module_kind = flags;
5009 pop_visibility (2);
5010 pop_nested_namespace (node);
5013 /* Create the VAR_DECL for __FUNCTION__ etc. ID is the name to give
5014 the decl, LOC is the location to give the decl, NAME is the
5015 initialization string and TYPE_DEP indicates whether NAME depended
5016 on the type of the function. We make use of that to detect
5017 __PRETTY_FUNCTION__ inside a template fn. This is being done lazily
5018 at the point of first use, so we mustn't push the decl now. */
5020 static tree
5021 cp_make_fname_decl (location_t loc, tree id, int type_dep)
5023 tree domain = NULL_TREE;
5024 tree init = NULL_TREE;
5026 if (!(type_dep && current_function_decl && in_template_context))
5028 const char *name = NULL;
5029 bool release_name = false;
5031 if (current_function_decl == NULL_TREE)
5032 name = "top level";
5033 else if (type_dep == 0)
5035 /* __FUNCTION__ */
5036 name = fname_as_string (type_dep);
5037 release_name = true;
5039 else
5041 /* __PRETTY_FUNCTION__ */
5042 gcc_checking_assert (type_dep == 1);
5043 name = cxx_printable_name (current_function_decl, 2);
5046 size_t length = strlen (name);
5047 domain = build_index_type (size_int (length));
5048 init = build_string (length + 1, name);
5049 if (release_name)
5050 free (const_cast<char *> (name));
5053 tree type = cp_build_qualified_type (char_type_node, TYPE_QUAL_CONST);
5054 type = build_cplus_array_type (type, domain);
5056 if (init)
5057 TREE_TYPE (init) = type;
5058 else
5059 init = error_mark_node;
5061 tree decl = build_decl (loc, VAR_DECL, id, type);
5063 TREE_READONLY (decl) = 1;
5064 DECL_ARTIFICIAL (decl) = 1;
5065 DECL_DECLARED_CONSTEXPR_P (decl) = 1;
5066 TREE_STATIC (decl) = 1;
5068 TREE_USED (decl) = 1;
5070 SET_DECL_VALUE_EXPR (decl, init);
5071 DECL_HAS_VALUE_EXPR_P (decl) = 1;
5072 /* For decl_constant_var_p. */
5073 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
5075 if (current_function_decl)
5077 DECL_CONTEXT (decl) = current_function_decl;
5078 decl = pushdecl_outermost_localscope (decl);
5079 if (decl != error_mark_node)
5080 add_decl_expr (decl);
5082 else
5084 DECL_THIS_STATIC (decl) = true;
5085 decl = pushdecl_top_level_and_finish (decl, NULL_TREE);
5088 return decl;
5091 /* Install DECL as a builtin function at current global scope. Return
5092 the new decl (if we found an existing version). Also installs it
5093 into ::std, if it's not '_*'. */
5095 tree
5096 cxx_builtin_function (tree decl)
5098 retrofit_lang_decl (decl);
5100 DECL_ARTIFICIAL (decl) = 1;
5101 SET_DECL_LANGUAGE (decl, lang_c);
5102 /* Runtime library routines are, by definition, available in an
5103 external shared object. */
5104 DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
5105 DECL_VISIBILITY_SPECIFIED (decl) = 1;
5107 tree id = DECL_NAME (decl);
5108 const char *name = IDENTIFIER_POINTER (id);
5109 bool hiding = false;
5110 if (name[0] != '_' || name[1] != '_')
5111 /* In the user's namespace, it must be declared before use. */
5112 hiding = true;
5113 else if (IDENTIFIER_LENGTH (id) > strlen ("___chk")
5114 && !startswith (name + 2, "builtin_")
5115 && 0 == memcmp (name + IDENTIFIER_LENGTH (id) - strlen ("_chk"),
5116 "_chk", strlen ("_chk") + 1))
5117 /* Treat __*_chk fortification functions as anticipated as well,
5118 unless they are __builtin_*_chk. */
5119 hiding = true;
5121 /* All builtins that don't begin with an '_' should additionally
5122 go in the 'std' namespace. */
5123 if (name[0] != '_')
5125 tree std_decl = copy_decl (decl);
5127 push_nested_namespace (std_node);
5128 DECL_CONTEXT (std_decl) = FROB_CONTEXT (std_node);
5129 pushdecl (std_decl, hiding);
5130 pop_nested_namespace (std_node);
5133 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5134 decl = pushdecl (decl, hiding);
5136 return decl;
5139 /* Like cxx_builtin_function, but guarantee the function is added to the global
5140 scope. This is to allow function specific options to add new machine
5141 dependent builtins when the target ISA changes via attribute((target(...)))
5142 which saves space on program startup if the program does not use non-generic
5143 ISAs. */
5145 tree
5146 cxx_builtin_function_ext_scope (tree decl)
5148 push_nested_namespace (global_namespace);
5149 decl = cxx_builtin_function (decl);
5150 pop_nested_namespace (global_namespace);
5152 return decl;
5155 /* Implement LANG_HOOKS_SIMULATE_BUILTIN_FUNCTION_DECL. */
5157 tree
5158 cxx_simulate_builtin_function_decl (tree decl)
5160 retrofit_lang_decl (decl);
5162 DECL_ARTIFICIAL (decl) = 1;
5163 SET_DECL_LANGUAGE (decl, lang_cplusplus);
5164 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5165 return pushdecl (decl);
5168 /* Generate a FUNCTION_DECL with the typical flags for a runtime library
5169 function. Not called directly. */
5171 static tree
5172 build_library_fn (tree name, enum tree_code operator_code, tree type,
5173 int ecf_flags)
5175 tree fn = build_lang_decl (FUNCTION_DECL, name, type);
5176 DECL_EXTERNAL (fn) = 1;
5177 TREE_PUBLIC (fn) = 1;
5178 DECL_ARTIFICIAL (fn) = 1;
5179 DECL_OVERLOADED_OPERATOR_CODE_RAW (fn)
5180 = OVL_OP_INFO (false, operator_code)->ovl_op_code;
5181 SET_DECL_LANGUAGE (fn, lang_c);
5182 /* Runtime library routines are, by definition, available in an
5183 external shared object. */
5184 DECL_VISIBILITY (fn) = VISIBILITY_DEFAULT;
5185 DECL_VISIBILITY_SPECIFIED (fn) = 1;
5186 set_call_expr_flags (fn, ecf_flags);
5187 return fn;
5190 /* Returns the _DECL for a library function with C++ linkage. */
5192 static tree
5193 build_cp_library_fn (tree name, enum tree_code operator_code, tree type,
5194 int ecf_flags)
5196 tree fn = build_library_fn (name, operator_code, type, ecf_flags);
5197 DECL_CONTEXT (fn) = FROB_CONTEXT (current_namespace);
5198 SET_DECL_LANGUAGE (fn, lang_cplusplus);
5199 return fn;
5202 /* Like build_library_fn, but takes a C string instead of an
5203 IDENTIFIER_NODE. */
5205 tree
5206 build_library_fn_ptr (const char* name, tree type, int ecf_flags)
5208 return build_library_fn (get_identifier (name), ERROR_MARK, type, ecf_flags);
5211 /* Like build_cp_library_fn, but takes a C string instead of an
5212 IDENTIFIER_NODE. */
5214 tree
5215 build_cp_library_fn_ptr (const char* name, tree type, int ecf_flags)
5217 return build_cp_library_fn (get_identifier (name), ERROR_MARK, type,
5218 ecf_flags);
5221 /* Like build_library_fn, but also pushes the function so that we will
5222 be able to find it via get_global_binding. Also, the function
5223 may throw exceptions listed in RAISES. */
5225 tree
5226 push_library_fn (tree name, tree type, tree raises, int ecf_flags)
5228 if (raises)
5229 type = build_exception_variant (type, raises);
5231 tree fn = build_library_fn (name, ERROR_MARK, type, ecf_flags);
5232 return pushdecl_top_level (fn);
5235 /* Like build_cp_library_fn, but also pushes the function so that it
5236 will be found by normal lookup. */
5238 static tree
5239 push_cp_library_fn (enum tree_code operator_code, tree type,
5240 int ecf_flags)
5242 tree fn = build_cp_library_fn (ovl_op_identifier (false, operator_code),
5243 operator_code, type, ecf_flags);
5244 pushdecl (fn);
5245 if (flag_tm)
5246 apply_tm_attr (fn, get_identifier ("transaction_safe"));
5247 return fn;
5250 /* Like push_library_fn, but also note that this function throws
5251 and does not return. Used for __throw_foo and the like. */
5253 tree
5254 push_throw_library_fn (tree name, tree type)
5256 tree fn = push_library_fn (name, type, NULL_TREE, ECF_NORETURN | ECF_COLD);
5257 return fn;
5260 /* When we call finish_struct for an anonymous union, we create
5261 default copy constructors and such. But, an anonymous union
5262 shouldn't have such things; this function undoes the damage to the
5263 anonymous union type T.
5265 (The reason that we create the synthesized methods is that we don't
5266 distinguish `union { int i; }' from `typedef union { int i; } U'.
5267 The first is an anonymous union; the second is just an ordinary
5268 union type.) */
5270 void
5271 fixup_anonymous_aggr (tree t)
5273 /* Wipe out memory of synthesized methods. */
5274 TYPE_HAS_USER_CONSTRUCTOR (t) = 0;
5275 TYPE_HAS_DEFAULT_CONSTRUCTOR (t) = 0;
5276 TYPE_HAS_COPY_CTOR (t) = 0;
5277 TYPE_HAS_CONST_COPY_CTOR (t) = 0;
5278 TYPE_HAS_COPY_ASSIGN (t) = 0;
5279 TYPE_HAS_CONST_COPY_ASSIGN (t) = 0;
5281 /* Splice the implicitly generated functions out of TYPE_FIELDS and diagnose
5282 invalid members. */
5283 for (tree probe, *prev_p = &TYPE_FIELDS (t); (probe = *prev_p);)
5285 if (TREE_CODE (probe) == FUNCTION_DECL && DECL_ARTIFICIAL (probe))
5286 *prev_p = DECL_CHAIN (probe);
5287 else
5288 prev_p = &DECL_CHAIN (probe);
5290 if (DECL_ARTIFICIAL (probe)
5291 && (!DECL_IMPLICIT_TYPEDEF_P (probe)
5292 || TYPE_ANON_P (TREE_TYPE (probe))))
5293 continue;
5295 if (TREE_CODE (probe) != FIELD_DECL
5296 || (TREE_PRIVATE (probe) || TREE_PROTECTED (probe)))
5298 /* We already complained about static data members in
5299 finish_static_data_member_decl. */
5300 if (!VAR_P (probe))
5302 auto_diagnostic_group d;
5303 if (permerror (DECL_SOURCE_LOCATION (probe),
5304 TREE_CODE (t) == UNION_TYPE
5305 ? "%q#D invalid; an anonymous union may "
5306 "only have public non-static data members"
5307 : "%q#D invalid; an anonymous struct may "
5308 "only have public non-static data members", probe))
5310 static bool hint;
5311 if (flag_permissive && !hint)
5313 hint = true;
5314 inform (DECL_SOURCE_LOCATION (probe),
5315 "this flexibility is deprecated and will be "
5316 "removed");
5323 /* Splice all functions out of CLASSTYPE_MEMBER_VEC. */
5324 vec<tree,va_gc>* vec = CLASSTYPE_MEMBER_VEC (t);
5325 unsigned store = 0;
5326 for (tree elt : vec)
5327 if (!is_overloaded_fn (elt))
5328 (*vec)[store++] = elt;
5329 vec_safe_truncate (vec, store);
5331 /* Wipe RTTI info. */
5332 CLASSTYPE_TYPEINFO_VAR (t) = NULL_TREE;
5334 /* Anonymous aggregates cannot have fields with ctors, dtors or complex
5335 assignment operators (because they cannot have these methods themselves).
5336 For anonymous unions this is already checked because they are not allowed
5337 in any union, otherwise we have to check it. */
5338 if (TREE_CODE (t) != UNION_TYPE)
5340 tree field, type;
5342 if (BINFO_N_BASE_BINFOS (TYPE_BINFO (t)))
5344 error_at (location_of (t), "anonymous struct with base classes");
5345 /* Avoid ICE after error on anon-struct9.C. */
5346 TYPE_NEEDS_CONSTRUCTING (t) = false;
5349 for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
5350 if (TREE_CODE (field) == FIELD_DECL)
5352 type = TREE_TYPE (field);
5353 if (CLASS_TYPE_P (type))
5355 if (TYPE_NEEDS_CONSTRUCTING (type))
5356 error ("member %q+#D with constructor not allowed "
5357 "in anonymous aggregate", field);
5358 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
5359 error ("member %q+#D with destructor not allowed "
5360 "in anonymous aggregate", field);
5361 if (TYPE_HAS_COMPLEX_COPY_ASSIGN (type))
5362 error ("member %q+#D with copy assignment operator "
5363 "not allowed in anonymous aggregate", field);
5369 /* Warn for an attribute located at LOCATION that appertains to the
5370 class type CLASS_TYPE that has not been properly placed after its
5371 class-key, in it class-specifier. */
5373 void
5374 warn_misplaced_attr_for_class_type (location_t location,
5375 tree class_type)
5377 gcc_assert (OVERLOAD_TYPE_P (class_type));
5379 auto_diagnostic_group d;
5380 if (warning_at (location, OPT_Wattributes,
5381 "attribute ignored in declaration "
5382 "of %q#T", class_type))
5383 inform (location,
5384 "attribute for %q#T must follow the %qs keyword",
5385 class_type, class_key_or_enum_as_string (class_type));
5388 /* Returns the cv-qualifiers that apply to the type specified
5389 by the DECLSPECS. */
5391 static int
5392 get_type_quals (const cp_decl_specifier_seq *declspecs)
5394 int type_quals = TYPE_UNQUALIFIED;
5396 if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5397 type_quals |= TYPE_QUAL_CONST;
5398 if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5399 type_quals |= TYPE_QUAL_VOLATILE;
5400 if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5401 type_quals |= TYPE_QUAL_RESTRICT;
5403 return type_quals;
5406 /* Make sure that a declaration with no declarator is well-formed, i.e.
5407 just declares a tagged type or anonymous union.
5409 Returns the type declared; or NULL_TREE if none. */
5411 tree
5412 check_tag_decl (cp_decl_specifier_seq *declspecs,
5413 bool explicit_type_instantiation_p)
5415 int saw_friend = decl_spec_seq_has_spec_p (declspecs, ds_friend);
5416 int saw_typedef = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
5417 /* If a class, struct, or enum type is declared by the DECLSPECS
5418 (i.e, if a class-specifier, enum-specifier, or non-typename
5419 elaborated-type-specifier appears in the DECLSPECS),
5420 DECLARED_TYPE is set to the corresponding type. */
5421 tree declared_type = NULL_TREE;
5422 bool error_p = false;
5424 if (declspecs->multiple_types_p)
5425 error_at (smallest_type_location (declspecs),
5426 "multiple types in one declaration");
5427 else if (declspecs->redefined_builtin_type)
5429 location_t loc = declspecs->locations[ds_redefined_builtin_type_spec];
5430 if (!in_system_header_at (loc))
5431 permerror (loc, "redeclaration of C++ built-in type %qT",
5432 declspecs->redefined_builtin_type);
5433 return NULL_TREE;
5436 if (declspecs->type
5437 && TYPE_P (declspecs->type)
5438 && ((TREE_CODE (declspecs->type) != TYPENAME_TYPE
5439 && MAYBE_CLASS_TYPE_P (declspecs->type))
5440 || TREE_CODE (declspecs->type) == ENUMERAL_TYPE))
5441 declared_type = declspecs->type;
5442 else if (declspecs->type == error_mark_node)
5443 error_p = true;
5445 if (type_uses_auto (declared_type))
5447 error_at (declspecs->locations[ds_type_spec],
5448 "%<auto%> can only be specified for variables "
5449 "or function declarations");
5450 return error_mark_node;
5453 if (declared_type && !OVERLOAD_TYPE_P (declared_type))
5454 declared_type = NULL_TREE;
5456 if (!declared_type && !saw_friend && !error_p)
5457 permerror (input_location, "declaration does not declare anything");
5458 /* Check for an anonymous union. */
5459 else if (declared_type && RECORD_OR_UNION_CODE_P (TREE_CODE (declared_type))
5460 && TYPE_UNNAMED_P (declared_type))
5462 /* 7/3 In a simple-declaration, the optional init-declarator-list
5463 can be omitted only when declaring a class (clause 9) or
5464 enumeration (7.2), that is, when the decl-specifier-seq contains
5465 either a class-specifier, an elaborated-type-specifier with
5466 a class-key (9.1), or an enum-specifier. In these cases and
5467 whenever a class-specifier or enum-specifier is present in the
5468 decl-specifier-seq, the identifiers in these specifiers are among
5469 the names being declared by the declaration (as class-name,
5470 enum-names, or enumerators, depending on the syntax). In such
5471 cases, and except for the declaration of an unnamed bit-field (9.6),
5472 the decl-specifier-seq shall introduce one or more names into the
5473 program, or shall redeclare a name introduced by a previous
5474 declaration. [Example:
5475 enum { }; // ill-formed
5476 typedef class { }; // ill-formed
5477 --end example] */
5478 if (saw_typedef)
5480 error_at (declspecs->locations[ds_typedef],
5481 "missing type-name in typedef-declaration");
5482 return NULL_TREE;
5484 /* Anonymous unions are objects, so they can have specifiers. */;
5485 SET_ANON_AGGR_TYPE_P (declared_type);
5487 if (TREE_CODE (declared_type) != UNION_TYPE)
5488 pedwarn (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (declared_type)),
5489 OPT_Wpedantic, "ISO C++ prohibits anonymous structs");
5492 else
5494 if (decl_spec_seq_has_spec_p (declspecs, ds_inline))
5495 error_at (declspecs->locations[ds_inline],
5496 "%<inline%> can only be specified for functions");
5497 else if (decl_spec_seq_has_spec_p (declspecs, ds_virtual))
5498 error_at (declspecs->locations[ds_virtual],
5499 "%<virtual%> can only be specified for functions");
5500 else if (saw_friend
5501 && (!current_class_type
5502 || current_scope () != current_class_type))
5503 error_at (declspecs->locations[ds_friend],
5504 "%<friend%> can only be specified inside a class");
5505 else if (decl_spec_seq_has_spec_p (declspecs, ds_explicit))
5506 error_at (declspecs->locations[ds_explicit],
5507 "%<explicit%> can only be specified for constructors");
5508 else if (declspecs->storage_class)
5509 error_at (declspecs->locations[ds_storage_class],
5510 "a storage class can only be specified for objects "
5511 "and functions");
5512 else if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5513 error_at (declspecs->locations[ds_const],
5514 "%<const%> can only be specified for objects and "
5515 "functions");
5516 else if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5517 error_at (declspecs->locations[ds_volatile],
5518 "%<volatile%> can only be specified for objects and "
5519 "functions");
5520 else if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5521 error_at (declspecs->locations[ds_restrict],
5522 "%<__restrict%> can only be specified for objects and "
5523 "functions");
5524 else if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
5525 error_at (declspecs->locations[ds_thread],
5526 "%<__thread%> can only be specified for objects "
5527 "and functions");
5528 else if (saw_typedef)
5529 warning_at (declspecs->locations[ds_typedef], 0,
5530 "%<typedef%> was ignored in this declaration");
5531 else if (decl_spec_seq_has_spec_p (declspecs, ds_constexpr))
5532 error_at (declspecs->locations[ds_constexpr],
5533 "%qs cannot be used for type declarations", "constexpr");
5534 else if (decl_spec_seq_has_spec_p (declspecs, ds_constinit))
5535 error_at (declspecs->locations[ds_constinit],
5536 "%qs cannot be used for type declarations", "constinit");
5537 else if (decl_spec_seq_has_spec_p (declspecs, ds_consteval))
5538 error_at (declspecs->locations[ds_consteval],
5539 "%qs cannot be used for type declarations", "consteval");
5542 if (declspecs->attributes && warn_attributes && declared_type)
5544 location_t loc;
5545 if (!CLASS_TYPE_P (declared_type)
5546 || !CLASSTYPE_TEMPLATE_INSTANTIATION (declared_type))
5547 /* For a non-template class, use the name location. */
5548 loc = location_of (declared_type);
5549 else
5550 /* For a template class (an explicit instantiation), use the
5551 current location. */
5552 loc = input_location;
5554 if (explicit_type_instantiation_p)
5555 /* [dcl.attr.grammar]/4:
5557 No attribute-specifier-seq shall appertain to an explicit
5558 instantiation. */
5560 if (warning_at (loc, OPT_Wattributes,
5561 "attribute ignored in explicit instantiation %q#T",
5562 declared_type))
5563 inform (loc,
5564 "no attribute can be applied to "
5565 "an explicit instantiation");
5567 else
5568 warn_misplaced_attr_for_class_type (loc, declared_type);
5571 /* Diagnose invalid application of contracts, if any. */
5572 if (find_contract (declspecs->attributes))
5573 diagnose_misapplied_contracts (declspecs->attributes);
5574 else
5575 diagnose_misapplied_contracts (declspecs->std_attributes);
5577 return declared_type;
5580 /* Called when a declaration is seen that contains no names to declare.
5581 If its type is a reference to a structure, union or enum inherited
5582 from a containing scope, shadow that tag name for the current scope
5583 with a forward reference.
5584 If its type defines a new named structure or union
5585 or defines an enum, it is valid but we need not do anything here.
5586 Otherwise, it is an error.
5588 C++: may have to grok the declspecs to learn about static,
5589 complain for anonymous unions.
5591 Returns the TYPE declared -- or NULL_TREE if none. */
5593 tree
5594 shadow_tag (cp_decl_specifier_seq *declspecs)
5596 tree t = check_tag_decl (declspecs,
5597 /*explicit_type_instantiation_p=*/false);
5599 if (!t)
5600 return NULL_TREE;
5602 t = maybe_process_partial_specialization (t);
5603 if (t == error_mark_node)
5604 return NULL_TREE;
5606 /* This is where the variables in an anonymous union are
5607 declared. An anonymous union declaration looks like:
5608 union { ... } ;
5609 because there is no declarator after the union, the parser
5610 sends that declaration here. */
5611 if (ANON_AGGR_TYPE_P (t))
5613 fixup_anonymous_aggr (t);
5615 if (TYPE_FIELDS (t))
5617 tree decl = grokdeclarator (/*declarator=*/NULL,
5618 declspecs, NORMAL, 0, NULL);
5619 finish_anon_union (decl);
5623 return t;
5626 /* Decode a "typename", such as "int **", returning a ..._TYPE node. */
5628 tree
5629 groktypename (cp_decl_specifier_seq *type_specifiers,
5630 const cp_declarator *declarator,
5631 bool is_template_arg)
5633 tree attrs;
5634 tree type;
5635 enum decl_context context
5636 = is_template_arg ? TEMPLATE_TYPE_ARG : TYPENAME;
5637 attrs = type_specifiers->attributes;
5638 type_specifiers->attributes = NULL_TREE;
5639 type = grokdeclarator (declarator, type_specifiers, context, 0, &attrs);
5640 if (attrs && type != error_mark_node)
5642 if (CLASS_TYPE_P (type))
5643 warning (OPT_Wattributes, "ignoring attributes applied to class type %qT "
5644 "outside of definition", type);
5645 else if (MAYBE_CLASS_TYPE_P (type))
5646 /* A template type parameter or other dependent type. */
5647 warning (OPT_Wattributes, "ignoring attributes applied to dependent "
5648 "type %qT without an associated declaration", type);
5649 else
5650 cplus_decl_attributes (&type, attrs, 0);
5652 return type;
5655 /* Process a DECLARATOR for a function-scope or namespace-scope
5656 variable or function declaration.
5657 (Function definitions go through start_function; class member
5658 declarations appearing in the body of the class go through
5659 grokfield.) The DECL corresponding to the DECLARATOR is returned.
5660 If an error occurs, the error_mark_node is returned instead.
5662 DECLSPECS are the decl-specifiers for the declaration. INITIALIZED is
5663 SD_INITIALIZED if an explicit initializer is present, or SD_DEFAULTED
5664 for an explicitly defaulted function, or SD_DELETED for an explicitly
5665 deleted function, but 0 (SD_UNINITIALIZED) if this is a variable
5666 implicitly initialized via a default constructor. It can also be
5667 SD_DECOMPOSITION which behaves much like SD_INITIALIZED, but we also
5668 mark the new decl as DECL_DECOMPOSITION_P.
5670 ATTRIBUTES and PREFIX_ATTRIBUTES are GNU attributes associated with this
5671 declaration.
5673 The scope represented by the context of the returned DECL is pushed
5674 (if it is not the global namespace) and is assigned to
5675 *PUSHED_SCOPE_P. The caller is then responsible for calling
5676 pop_scope on *PUSHED_SCOPE_P if it is set. */
5678 tree
5679 start_decl (const cp_declarator *declarator,
5680 cp_decl_specifier_seq *declspecs,
5681 int initialized,
5682 tree attributes,
5683 tree prefix_attributes,
5684 tree *pushed_scope_p)
5686 tree decl;
5687 tree context;
5688 bool was_public;
5689 int flags;
5690 bool alias;
5691 tree initial;
5693 *pushed_scope_p = NULL_TREE;
5695 if (prefix_attributes != error_mark_node)
5696 attributes = attr_chainon (attributes, prefix_attributes);
5698 decl = grokdeclarator (declarator, declspecs, NORMAL, initialized,
5699 &attributes);
5701 if (decl == NULL_TREE || VOID_TYPE_P (decl)
5702 || decl == error_mark_node
5703 || prefix_attributes == error_mark_node)
5704 return error_mark_node;
5706 context = CP_DECL_CONTEXT (decl);
5707 if (context != global_namespace)
5708 *pushed_scope_p = push_scope (context);
5710 if (initialized && TREE_CODE (decl) == TYPE_DECL)
5712 error_at (DECL_SOURCE_LOCATION (decl),
5713 "typedef %qD is initialized (use %qs instead)",
5714 decl, "decltype");
5715 return error_mark_node;
5718 /* Save the DECL_INITIAL value in case it gets clobbered to assist
5719 with attribute validation. */
5720 initial = DECL_INITIAL (decl);
5722 if (initialized)
5724 if (! toplevel_bindings_p ()
5725 && DECL_EXTERNAL (decl))
5726 warning (0, "declaration of %q#D has %<extern%> and is initialized",
5727 decl);
5728 DECL_EXTERNAL (decl) = 0;
5729 if (toplevel_bindings_p ())
5730 TREE_STATIC (decl) = 1;
5731 /* Tell 'cplus_decl_attributes' this is an initialized decl,
5732 even though we might not yet have the initializer expression. */
5733 if (!DECL_INITIAL (decl))
5734 DECL_INITIAL (decl) = error_mark_node;
5736 alias = lookup_attribute ("alias", DECL_ATTRIBUTES (decl)) != 0;
5738 if (alias && TREE_CODE (decl) == FUNCTION_DECL)
5739 record_key_method_defined (decl);
5741 /* If this is a typedef that names the class for linkage purposes
5742 (7.1.3p8), apply any attributes directly to the type. */
5743 if (TREE_CODE (decl) == TYPE_DECL
5744 && OVERLOAD_TYPE_P (TREE_TYPE (decl))
5745 && decl == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (decl))))
5746 flags = ATTR_FLAG_TYPE_IN_PLACE;
5747 else
5748 flags = 0;
5750 /* Set attributes here so if duplicate decl, will have proper attributes. */
5751 cplus_decl_attributes (&decl, attributes, flags);
5753 /* Restore the original DECL_INITIAL that we may have clobbered earlier to
5754 assist with attribute validation. */
5755 DECL_INITIAL (decl) = initial;
5757 /* Dllimported symbols cannot be defined. Static data members (which
5758 can be initialized in-class and dllimported) go through grokfield,
5759 not here, so we don't need to exclude those decls when checking for
5760 a definition. */
5761 if (initialized && DECL_DLLIMPORT_P (decl))
5763 error_at (DECL_SOURCE_LOCATION (decl),
5764 "definition of %q#D is marked %<dllimport%>", decl);
5765 DECL_DLLIMPORT_P (decl) = 0;
5768 /* If #pragma weak was used, mark the decl weak now. */
5769 if (!processing_template_decl && !DECL_DECOMPOSITION_P (decl))
5770 maybe_apply_pragma_weak (decl);
5772 if (TREE_CODE (decl) == FUNCTION_DECL
5773 && DECL_DECLARED_INLINE_P (decl)
5774 && DECL_UNINLINABLE (decl)
5775 && lookup_attribute ("noinline", DECL_ATTRIBUTES (decl)))
5776 warning_at (DECL_SOURCE_LOCATION (decl), 0,
5777 "inline function %qD given attribute %qs", decl, "noinline");
5779 if (TYPE_P (context) && COMPLETE_TYPE_P (complete_type (context)))
5781 bool this_tmpl = (current_template_depth
5782 > template_class_depth (context));
5783 if (VAR_P (decl))
5785 tree field = lookup_field (context, DECL_NAME (decl), 0, false);
5786 if (field == NULL_TREE
5787 || !(VAR_P (field) || variable_template_p (field)))
5788 error ("%q+#D is not a static data member of %q#T", decl, context);
5789 else if (variable_template_p (field)
5790 && (DECL_LANG_SPECIFIC (decl)
5791 && DECL_TEMPLATE_SPECIALIZATION (decl)))
5792 /* OK, specialization was already checked. */;
5793 else if (variable_template_p (field) && !this_tmpl)
5795 error_at (DECL_SOURCE_LOCATION (decl),
5796 "non-member-template declaration of %qD", decl);
5797 inform (DECL_SOURCE_LOCATION (field), "does not match "
5798 "member template declaration here");
5799 return error_mark_node;
5801 else
5803 if (variable_template_p (field))
5804 field = DECL_TEMPLATE_RESULT (field);
5806 if (DECL_CONTEXT (field) != context)
5808 if (!same_type_p (DECL_CONTEXT (field), context))
5809 permerror (input_location, "ISO C++ does not permit %<%T::%D%> "
5810 "to be defined as %<%T::%D%>",
5811 DECL_CONTEXT (field), DECL_NAME (decl),
5812 context, DECL_NAME (decl));
5813 DECL_CONTEXT (decl) = DECL_CONTEXT (field);
5815 /* Static data member are tricky; an in-class initialization
5816 still doesn't provide a definition, so the in-class
5817 declaration will have DECL_EXTERNAL set, but will have an
5818 initialization. Thus, duplicate_decls won't warn
5819 about this situation, and so we check here. */
5820 if (initialized && DECL_INITIALIZED_IN_CLASS_P (field))
5821 error ("duplicate initialization of %qD", decl);
5822 field = duplicate_decls (decl, field);
5823 if (field == error_mark_node)
5824 return error_mark_node;
5825 else if (field)
5826 decl = field;
5829 else
5831 tree field = check_classfn (context, decl,
5832 this_tmpl
5833 ? current_template_parms
5834 : NULL_TREE);
5835 if (field && field != error_mark_node
5836 && duplicate_decls (decl, field))
5837 decl = field;
5840 /* cp_finish_decl sets DECL_EXTERNAL if DECL_IN_AGGR_P is set. */
5841 DECL_IN_AGGR_P (decl) = 0;
5842 /* Do not mark DECL as an explicit specialization if it was not
5843 already marked as an instantiation; a declaration should
5844 never be marked as a specialization unless we know what
5845 template is being specialized. */
5846 if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
5848 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
5849 if (TREE_CODE (decl) == FUNCTION_DECL)
5850 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
5851 && DECL_DECLARED_INLINE_P (decl));
5852 else
5853 DECL_COMDAT (decl) = false;
5855 /* [temp.expl.spec] An explicit specialization of a static data
5856 member of a template is a definition if the declaration
5857 includes an initializer; otherwise, it is a declaration.
5859 We check for processing_specialization so this only applies
5860 to the new specialization syntax. */
5861 if (!initialized && processing_specialization)
5862 DECL_EXTERNAL (decl) = 1;
5865 if (DECL_EXTERNAL (decl) && ! DECL_TEMPLATE_SPECIALIZATION (decl)
5866 /* Aliases are definitions. */
5867 && !alias)
5869 if (DECL_VIRTUAL_P (decl) || !flag_contracts)
5870 permerror (declarator->id_loc,
5871 "declaration of %q#D outside of class is not definition",
5872 decl);
5873 else if (flag_contract_strict_declarations)
5874 warning_at (declarator->id_loc, OPT_fcontract_strict_declarations_,
5875 "declaration of %q#D outside of class is not definition",
5876 decl);
5880 /* Create a DECL_LANG_SPECIFIC so that DECL_DECOMPOSITION_P works. */
5881 if (initialized == SD_DECOMPOSITION)
5882 fit_decomposition_lang_decl (decl, NULL_TREE);
5884 was_public = TREE_PUBLIC (decl);
5886 if ((DECL_EXTERNAL (decl) || TREE_CODE (decl) == FUNCTION_DECL)
5887 && current_function_decl)
5889 /* A function-scope decl of some namespace-scope decl. */
5890 DECL_LOCAL_DECL_P (decl) = true;
5891 if (named_module_purview_p ())
5892 error_at (declarator->id_loc,
5893 "block-scope extern declaration %q#D not permitted"
5894 " in module purview", decl);
5897 /* Enter this declaration into the symbol table. Don't push the plain
5898 VAR_DECL for a variable template. */
5899 if (!template_parm_scope_p ()
5900 || !VAR_P (decl))
5901 decl = maybe_push_decl (decl);
5903 if (processing_template_decl)
5904 decl = push_template_decl (decl);
5906 if (decl == error_mark_node)
5907 return error_mark_node;
5909 if (VAR_P (decl)
5910 && DECL_NAMESPACE_SCOPE_P (decl) && !TREE_PUBLIC (decl) && !was_public
5911 && !DECL_THIS_STATIC (decl) && !DECL_ARTIFICIAL (decl)
5912 /* But not templated variables. */
5913 && !(DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)))
5915 /* This is a const variable with implicit 'static'. Set
5916 DECL_THIS_STATIC so we can tell it from variables that are
5917 !TREE_PUBLIC because of the anonymous namespace. */
5918 gcc_assert (CP_TYPE_CONST_P (TREE_TYPE (decl)) || errorcount);
5919 DECL_THIS_STATIC (decl) = 1;
5922 if (current_function_decl && VAR_P (decl)
5923 && DECL_DECLARED_CONSTEXPR_P (current_function_decl)
5924 && cxx_dialect < cxx23)
5926 bool ok = false;
5927 if (CP_DECL_THREAD_LOCAL_P (decl) && !DECL_REALLY_EXTERN (decl))
5928 error_at (DECL_SOURCE_LOCATION (decl),
5929 "%qD defined %<thread_local%> in %qs function only "
5930 "available with %<-std=c++2b%> or %<-std=gnu++2b%>", decl,
5931 DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
5932 ? "consteval" : "constexpr");
5933 else if (TREE_STATIC (decl))
5934 error_at (DECL_SOURCE_LOCATION (decl),
5935 "%qD defined %<static%> in %qs function only available "
5936 "with %<-std=c++2b%> or %<-std=gnu++2b%>", decl,
5937 DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
5938 ? "consteval" : "constexpr");
5939 else
5940 ok = true;
5941 if (!ok)
5942 cp_function_chain->invalid_constexpr = true;
5945 if (!processing_template_decl && VAR_P (decl))
5946 start_decl_1 (decl, initialized);
5948 return decl;
5951 /* Process the declaration of a variable DECL. INITIALIZED is true
5952 iff DECL is explicitly initialized. (INITIALIZED is false if the
5953 variable is initialized via an implicitly-called constructor.)
5954 This function must be called for ordinary variables (including, for
5955 example, implicit instantiations of templates), but must not be
5956 called for template declarations. */
5958 void
5959 start_decl_1 (tree decl, bool initialized)
5961 gcc_checking_assert (!processing_template_decl);
5963 if (error_operand_p (decl))
5964 return;
5966 gcc_checking_assert (VAR_P (decl));
5968 tree type = TREE_TYPE (decl);
5969 bool complete_p = COMPLETE_TYPE_P (type);
5970 bool aggregate_definition_p
5971 = MAYBE_CLASS_TYPE_P (type) && !DECL_EXTERNAL (decl);
5973 /* If an explicit initializer is present, or if this is a definition
5974 of an aggregate, then we need a complete type at this point.
5975 (Scalars are always complete types, so there is nothing to
5976 check.) This code just sets COMPLETE_P; errors (if necessary)
5977 are issued below. */
5978 if ((initialized || aggregate_definition_p)
5979 && !complete_p
5980 && COMPLETE_TYPE_P (complete_type (type)))
5982 complete_p = true;
5983 /* We will not yet have set TREE_READONLY on DECL if the type
5984 was "const", but incomplete, before this point. But, now, we
5985 have a complete type, so we can try again. */
5986 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
5989 if (initialized)
5990 /* Is it valid for this decl to have an initializer at all? */
5992 /* Don't allow initializations for incomplete types except for
5993 arrays which might be completed by the initialization. */
5994 if (complete_p)
5995 ; /* A complete type is ok. */
5996 else if (type_uses_auto (type))
5997 ; /* An auto type is ok. */
5998 else if (TREE_CODE (type) != ARRAY_TYPE)
6000 auto_diagnostic_group d;
6001 error ("variable %q#D has initializer but incomplete type", decl);
6002 maybe_suggest_missing_header (input_location,
6003 TYPE_IDENTIFIER (type),
6004 CP_TYPE_CONTEXT (type));
6005 type = TREE_TYPE (decl) = error_mark_node;
6007 else if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (type))))
6009 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
6010 error ("elements of array %q#D have incomplete type", decl);
6011 /* else we already gave an error in start_decl. */
6014 else if (aggregate_definition_p && !complete_p)
6016 if (type_uses_auto (type))
6017 gcc_assert (CLASS_PLACEHOLDER_TEMPLATE (type));
6018 else
6020 auto_diagnostic_group d;
6021 error ("aggregate %q#D has incomplete type and cannot be defined",
6022 decl);
6023 maybe_suggest_missing_header (input_location,
6024 TYPE_IDENTIFIER (type),
6025 CP_TYPE_CONTEXT (type));
6026 /* Change the type so that assemble_variable will give
6027 DECL an rtl we can live with: (mem (const_int 0)). */
6028 type = TREE_TYPE (decl) = error_mark_node;
6032 /* Create a new scope to hold this declaration if necessary.
6033 Whether or not a new scope is necessary cannot be determined
6034 until after the type has been completed; if the type is a
6035 specialization of a class template it is not until after
6036 instantiation has occurred that TYPE_HAS_NONTRIVIAL_DESTRUCTOR
6037 will be set correctly. */
6038 maybe_push_cleanup_level (type);
6041 /* Given a parenthesized list of values INIT, create a CONSTRUCTOR to handle
6042 C++20 P0960. TYPE is the type of the object we're initializing. */
6044 tree
6045 do_aggregate_paren_init (tree init, tree type)
6047 tree val = TREE_VALUE (init);
6049 if (TREE_CHAIN (init) == NULL_TREE)
6051 /* If the list has a single element and it's a string literal,
6052 then it's the initializer for the array as a whole. */
6053 if (TREE_CODE (type) == ARRAY_TYPE
6054 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
6055 && TREE_CODE (tree_strip_any_location_wrapper (val))
6056 == STRING_CST)
6057 return val;
6058 /* Handle non-standard extensions like compound literals. This also
6059 prevents triggering aggregate parenthesized-initialization in
6060 compiler-generated code for =default. */
6061 else if (same_type_ignoring_top_level_qualifiers_p (type,
6062 TREE_TYPE (val)))
6063 return val;
6066 init = build_constructor_from_list (init_list_type_node, init);
6067 CONSTRUCTOR_IS_DIRECT_INIT (init) = true;
6068 CONSTRUCTOR_IS_PAREN_INIT (init) = true;
6069 return init;
6072 /* Handle initialization of references. DECL, TYPE, and INIT have the
6073 same meaning as in cp_finish_decl. *CLEANUP must be NULL on entry,
6074 but will be set to a new CLEANUP_STMT if a temporary is created
6075 that must be destroyed subsequently.
6077 Returns an initializer expression to use to initialize DECL, or
6078 NULL if the initialization can be performed statically.
6080 Quotes on semantics can be found in ARM 8.4.3. */
6082 static tree
6083 grok_reference_init (tree decl, tree type, tree init, int flags)
6085 if (init == NULL_TREE)
6087 if ((DECL_LANG_SPECIFIC (decl) == 0
6088 || DECL_IN_AGGR_P (decl) == 0)
6089 && ! DECL_THIS_EXTERN (decl))
6090 error_at (DECL_SOURCE_LOCATION (decl),
6091 "%qD declared as reference but not initialized", decl);
6092 return NULL_TREE;
6095 tree ttype = TREE_TYPE (type);
6096 if (TREE_CODE (init) == TREE_LIST)
6098 /* This handles (C++20 only) code like
6100 const A& r(1, 2, 3);
6102 where we treat the parenthesized list as a CONSTRUCTOR. */
6103 if (TREE_TYPE (init) == NULL_TREE
6104 && CP_AGGREGATE_TYPE_P (ttype)
6105 && !DECL_DECOMPOSITION_P (decl)
6106 && (cxx_dialect >= cxx20))
6108 /* We don't know yet if we should treat const A& r(1) as
6109 const A& r{1}. */
6110 if (list_length (init) == 1)
6112 flags |= LOOKUP_AGGREGATE_PAREN_INIT;
6113 init = build_x_compound_expr_from_list (init, ELK_INIT,
6114 tf_warning_or_error);
6116 /* If the list had more than one element, the code is ill-formed
6117 pre-C++20, so we can build a constructor right away. */
6118 else
6119 init = do_aggregate_paren_init (init, ttype);
6121 else
6122 init = build_x_compound_expr_from_list (init, ELK_INIT,
6123 tf_warning_or_error);
6126 if (TREE_CODE (ttype) != ARRAY_TYPE
6127 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
6128 /* Note: default conversion is only called in very special cases. */
6129 init = decay_conversion (init, tf_warning_or_error);
6131 /* check_initializer handles this for non-reference variables, but for
6132 references we need to do it here or the initializer will get the
6133 incomplete array type and confuse later calls to
6134 cp_complete_array_type. */
6135 if (TREE_CODE (ttype) == ARRAY_TYPE
6136 && TYPE_DOMAIN (ttype) == NULL_TREE
6137 && (BRACE_ENCLOSED_INITIALIZER_P (init)
6138 || TREE_CODE (init) == STRING_CST))
6140 cp_complete_array_type (&ttype, init, false);
6141 if (ttype != TREE_TYPE (type))
6142 type = cp_build_reference_type (ttype, TYPE_REF_IS_RVALUE (type));
6145 /* Convert INIT to the reference type TYPE. This may involve the
6146 creation of a temporary, whose lifetime must be the same as that
6147 of the reference. If so, a DECL_EXPR for the temporary will be
6148 added just after the DECL_EXPR for DECL. That's why we don't set
6149 DECL_INITIAL for local references (instead assigning to them
6150 explicitly); we need to allow the temporary to be initialized
6151 first. */
6152 return initialize_reference (type, init, flags,
6153 tf_warning_or_error);
6156 /* Designated initializers in arrays are not supported in GNU C++.
6157 The parser cannot detect this error since it does not know whether
6158 a given brace-enclosed initializer is for a class type or for an
6159 array. This function checks that CE does not use a designated
6160 initializer. If it does, an error is issued. Returns true if CE
6161 is valid, i.e., does not have a designated initializer. */
6163 bool
6164 check_array_designated_initializer (constructor_elt *ce,
6165 unsigned HOST_WIDE_INT index)
6167 /* Designated initializers for array elements are not supported. */
6168 if (ce->index)
6170 /* The parser only allows identifiers as designated
6171 initializers. */
6172 if (ce->index == error_mark_node)
6174 error ("name used in a GNU-style designated "
6175 "initializer for an array");
6176 return false;
6178 else if (identifier_p (ce->index))
6180 error ("name %qD used in a GNU-style designated "
6181 "initializer for an array", ce->index);
6182 return false;
6185 tree ce_index = build_expr_type_conversion (WANT_INT | WANT_ENUM,
6186 ce->index, true);
6187 if (ce_index
6188 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ce_index))
6189 && (TREE_CODE (ce_index = fold_non_dependent_expr (ce_index))
6190 == INTEGER_CST))
6192 /* A C99 designator is OK if it matches the current index. */
6193 if (wi::to_wide (ce_index) == index)
6195 ce->index = ce_index;
6196 return true;
6198 else
6199 sorry ("non-trivial designated initializers not supported");
6201 else
6202 error_at (cp_expr_loc_or_input_loc (ce->index),
6203 "C99 designator %qE is not an integral constant-expression",
6204 ce->index);
6206 return false;
6209 return true;
6212 /* When parsing `int a[] = {1, 2};' we don't know the size of the
6213 array until we finish parsing the initializer. If that's the
6214 situation we're in, update DECL accordingly. */
6216 static void
6217 maybe_deduce_size_from_array_init (tree decl, tree init)
6219 tree type = TREE_TYPE (decl);
6221 if (TREE_CODE (type) == ARRAY_TYPE
6222 && TYPE_DOMAIN (type) == NULL_TREE
6223 && TREE_CODE (decl) != TYPE_DECL)
6225 /* do_default is really a C-ism to deal with tentative definitions.
6226 But let's leave it here to ease the eventual merge. */
6227 int do_default = !DECL_EXTERNAL (decl);
6228 tree initializer = init ? init : DECL_INITIAL (decl);
6229 int failure = 0;
6231 /* Check that there are no designated initializers in INIT, as
6232 those are not supported in GNU C++, and as the middle-end
6233 will crash if presented with a non-numeric designated
6234 initializer. */
6235 if (initializer && BRACE_ENCLOSED_INITIALIZER_P (initializer))
6237 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initializer);
6238 constructor_elt *ce;
6239 HOST_WIDE_INT i;
6240 FOR_EACH_VEC_SAFE_ELT (v, i, ce)
6242 if (instantiation_dependent_expression_p (ce->index))
6243 return;
6244 if (!check_array_designated_initializer (ce, i))
6245 failure = 1;
6246 /* If an un-designated initializer is type-dependent, we can't
6247 check brace elision yet. */
6248 if (ce->index == NULL_TREE
6249 && type_dependent_expression_p (ce->value))
6250 return;
6254 if (failure)
6255 TREE_TYPE (decl) = error_mark_node;
6256 else
6258 failure = cp_complete_array_type (&TREE_TYPE (decl), initializer,
6259 do_default);
6260 if (failure == 1)
6262 error_at (cp_expr_loc_or_loc (initializer,
6263 DECL_SOURCE_LOCATION (decl)),
6264 "initializer fails to determine size of %qD", decl);
6266 else if (failure == 2)
6268 if (do_default)
6270 error_at (DECL_SOURCE_LOCATION (decl),
6271 "array size missing in %qD", decl);
6273 /* If a `static' var's size isn't known, make it extern as
6274 well as static, so it does not get allocated. If it's not
6275 `static', then don't mark it extern; finish_incomplete_decl
6276 will give it a default size and it will get allocated. */
6277 else if (!pedantic && TREE_STATIC (decl) && !TREE_PUBLIC (decl))
6278 DECL_EXTERNAL (decl) = 1;
6280 else if (failure == 3)
6282 error_at (DECL_SOURCE_LOCATION (decl),
6283 "zero-size array %qD", decl);
6287 cp_apply_type_quals_to_decl (cp_type_quals (TREE_TYPE (decl)), decl);
6289 relayout_decl (decl);
6293 /* Set DECL_SIZE, DECL_ALIGN, etc. for DECL (a VAR_DECL), and issue
6294 any appropriate error messages regarding the layout. */
6296 static void
6297 layout_var_decl (tree decl)
6299 tree type;
6301 type = TREE_TYPE (decl);
6302 if (type == error_mark_node)
6303 return;
6305 /* If we haven't already laid out this declaration, do so now.
6306 Note that we must not call complete type for an external object
6307 because it's type might involve templates that we are not
6308 supposed to instantiate yet. (And it's perfectly valid to say
6309 `extern X x' for some incomplete type `X'.) */
6310 if (!DECL_EXTERNAL (decl))
6311 complete_type (type);
6312 if (!DECL_SIZE (decl)
6313 && TREE_TYPE (decl) != error_mark_node
6314 && complete_or_array_type_p (type))
6315 layout_decl (decl, 0);
6317 if (!DECL_EXTERNAL (decl) && DECL_SIZE (decl) == NULL_TREE)
6319 /* An automatic variable with an incomplete type: that is an error.
6320 Don't talk about array types here, since we took care of that
6321 message in grokdeclarator. */
6322 error_at (DECL_SOURCE_LOCATION (decl),
6323 "storage size of %qD isn%'t known", decl);
6324 TREE_TYPE (decl) = error_mark_node;
6326 #if 0
6327 /* Keep this code around in case we later want to control debug info
6328 based on whether a type is "used". (jason 1999-11-11) */
6330 else if (!DECL_EXTERNAL (decl) && MAYBE_CLASS_TYPE_P (ttype))
6331 /* Let debugger know it should output info for this type. */
6332 note_debug_info_needed (ttype);
6334 if (TREE_STATIC (decl) && DECL_CLASS_SCOPE_P (decl))
6335 note_debug_info_needed (DECL_CONTEXT (decl));
6336 #endif
6338 if ((DECL_EXTERNAL (decl) || TREE_STATIC (decl))
6339 && DECL_SIZE (decl) != NULL_TREE
6340 && ! TREE_CONSTANT (DECL_SIZE (decl)))
6342 if (TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST
6343 && !DECL_LOCAL_DECL_P (decl))
6344 constant_expression_warning (DECL_SIZE (decl));
6345 else
6347 error_at (DECL_SOURCE_LOCATION (decl),
6348 "storage size of %qD isn%'t constant", decl);
6349 TREE_TYPE (decl) = error_mark_node;
6350 type = error_mark_node;
6354 /* If the final element initializes a flexible array field, add the size of
6355 that initializer to DECL's size. */
6356 if (type != error_mark_node
6357 && DECL_INITIAL (decl)
6358 && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
6359 && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl)))
6360 && DECL_SIZE (decl) != NULL_TREE
6361 && TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST
6362 && COMPLETE_TYPE_P (type)
6363 && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST
6364 && tree_int_cst_equal (DECL_SIZE (decl), TYPE_SIZE (type)))
6366 constructor_elt &elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ();
6367 if (elt.index)
6369 tree itype = TREE_TYPE (elt.index);
6370 tree vtype = TREE_TYPE (elt.value);
6371 if (TREE_CODE (itype) == ARRAY_TYPE
6372 && TYPE_DOMAIN (itype) == NULL
6373 && TREE_CODE (vtype) == ARRAY_TYPE
6374 && COMPLETE_TYPE_P (vtype))
6376 DECL_SIZE (decl)
6377 = size_binop (PLUS_EXPR, DECL_SIZE (decl), TYPE_SIZE (vtype));
6378 DECL_SIZE_UNIT (decl)
6379 = size_binop (PLUS_EXPR, DECL_SIZE_UNIT (decl),
6380 TYPE_SIZE_UNIT (vtype));
6386 /* If a local static variable is declared in an inline function, or if
6387 we have a weak definition, we must endeavor to create only one
6388 instance of the variable at link-time. */
6390 void
6391 maybe_commonize_var (tree decl)
6393 /* Don't mess with __FUNCTION__ and similar. */
6394 if (DECL_ARTIFICIAL (decl))
6395 return;
6397 /* Static data in a function with comdat linkage also has comdat
6398 linkage. */
6399 if ((TREE_STATIC (decl)
6400 && DECL_FUNCTION_SCOPE_P (decl)
6401 && vague_linkage_p (DECL_CONTEXT (decl)))
6402 || (TREE_PUBLIC (decl) && DECL_INLINE_VAR_P (decl)))
6404 if (flag_weak)
6406 /* With weak symbols, we simply make the variable COMDAT;
6407 that will cause copies in multiple translations units to
6408 be merged. */
6409 comdat_linkage (decl);
6411 else
6413 if (DECL_INITIAL (decl) == NULL_TREE
6414 || DECL_INITIAL (decl) == error_mark_node)
6416 /* Without weak symbols, we can use COMMON to merge
6417 uninitialized variables. */
6418 TREE_PUBLIC (decl) = 1;
6419 DECL_COMMON (decl) = 1;
6421 else
6423 /* While for initialized variables, we must use internal
6424 linkage -- which means that multiple copies will not
6425 be merged. */
6426 TREE_PUBLIC (decl) = 0;
6427 DECL_COMMON (decl) = 0;
6428 DECL_INTERFACE_KNOWN (decl) = 1;
6429 const char *msg;
6430 if (DECL_INLINE_VAR_P (decl))
6431 msg = G_("sorry: semantics of inline variable "
6432 "%q#D are wrong (you%'ll wind up with "
6433 "multiple copies)");
6434 else
6435 msg = G_("sorry: semantics of inline function "
6436 "static data %q#D are wrong (you%'ll wind "
6437 "up with multiple copies)");
6438 if (warning_at (DECL_SOURCE_LOCATION (decl), 0,
6439 msg, decl))
6440 inform (DECL_SOURCE_LOCATION (decl),
6441 "you can work around this by removing the initializer");
6447 /* Issue an error message if DECL is an uninitialized const variable.
6448 CONSTEXPR_CONTEXT_P is true when the function is called in a constexpr
6449 context from potential_constant_expression. Returns true if all is well,
6450 false otherwise. */
6452 bool
6453 check_for_uninitialized_const_var (tree decl, bool constexpr_context_p,
6454 tsubst_flags_t complain)
6456 tree type = strip_array_types (TREE_TYPE (decl));
6458 /* ``Unless explicitly declared extern, a const object does not have
6459 external linkage and must be initialized. ($8.4; $12.1)'' ARM
6460 7.1.6 */
6461 if (VAR_P (decl)
6462 && !TYPE_REF_P (type)
6463 && (CP_TYPE_CONST_P (type)
6464 /* C++20 permits trivial default initialization in constexpr
6465 context (P1331R2). */
6466 || (cxx_dialect < cxx20
6467 && (constexpr_context_p
6468 || var_in_constexpr_fn (decl))))
6469 && !DECL_NONTRIVIALLY_INITIALIZED_P (decl))
6471 tree field = default_init_uninitialized_part (type);
6472 if (!field)
6473 return true;
6475 bool show_notes = true;
6477 if (!constexpr_context_p || cxx_dialect >= cxx20)
6479 if (CP_TYPE_CONST_P (type))
6481 if (complain & tf_error)
6482 show_notes = permerror (DECL_SOURCE_LOCATION (decl),
6483 "uninitialized %<const %D%>", decl);
6485 else
6487 if (!is_instantiation_of_constexpr (current_function_decl)
6488 && (complain & tf_error))
6489 error_at (DECL_SOURCE_LOCATION (decl),
6490 "uninitialized variable %qD in %<constexpr%> "
6491 "function", decl);
6492 else
6493 show_notes = false;
6494 cp_function_chain->invalid_constexpr = true;
6497 else if (complain & tf_error)
6498 error_at (DECL_SOURCE_LOCATION (decl),
6499 "uninitialized variable %qD in %<constexpr%> context",
6500 decl);
6502 if (show_notes && CLASS_TYPE_P (type) && (complain & tf_error))
6504 tree defaulted_ctor;
6506 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)),
6507 "%q#T has no user-provided default constructor", type);
6508 defaulted_ctor = in_class_defaulted_default_constructor (type);
6509 if (defaulted_ctor)
6510 inform (DECL_SOURCE_LOCATION (defaulted_ctor),
6511 "constructor is not user-provided because it is "
6512 "explicitly defaulted in the class body");
6513 inform (DECL_SOURCE_LOCATION (field),
6514 "and the implicitly-defined constructor does not "
6515 "initialize %q#D", field);
6518 return false;
6521 return true;
6524 /* Structure holding the current initializer being processed by reshape_init.
6525 CUR is a pointer to the current element being processed, END is a pointer
6526 after the last element present in the initializer. */
6527 struct reshape_iter
6529 constructor_elt *cur;
6530 constructor_elt *end;
6533 static tree reshape_init_r (tree, reshape_iter *, tree, tsubst_flags_t);
6535 /* FIELD is an element of TYPE_FIELDS or NULL. In the former case, the value
6536 returned is the next FIELD_DECL (possibly FIELD itself) that can be
6537 initialized as if for an aggregate class. If there are no more such fields,
6538 the return value will be NULL. */
6540 tree
6541 next_aggregate_field (tree field)
6543 while (field
6544 && (TREE_CODE (field) != FIELD_DECL
6545 || DECL_UNNAMED_BIT_FIELD (field)
6546 || (DECL_ARTIFICIAL (field)
6547 /* In C++17, aggregates can have bases. */
6548 && !(cxx_dialect >= cxx17 && DECL_FIELD_IS_BASE (field)))))
6549 field = DECL_CHAIN (field);
6551 return field;
6554 /* FIELD is an element of TYPE_FIELDS or NULL. In the former case, the value
6555 returned is the next FIELD_DECL (possibly FIELD itself) that corresponds
6556 to a subobject. If there are no more such fields, the return value will be
6557 NULL. */
6559 tree
6560 next_subobject_field (tree field)
6562 while (field
6563 && (TREE_CODE (field) != FIELD_DECL
6564 || DECL_UNNAMED_BIT_FIELD (field)
6565 || (DECL_ARTIFICIAL (field)
6566 && !DECL_FIELD_IS_BASE (field)
6567 && !DECL_VIRTUAL_P (field))))
6568 field = DECL_CHAIN (field);
6570 return field;
6573 /* Return true for [dcl.init.list] direct-list-initialization from
6574 single element of enumeration with a fixed underlying type. */
6576 bool
6577 is_direct_enum_init (tree type, tree init)
6579 if (cxx_dialect >= cxx17
6580 && TREE_CODE (type) == ENUMERAL_TYPE
6581 && ENUM_FIXED_UNDERLYING_TYPE_P (type)
6582 && TREE_CODE (init) == CONSTRUCTOR
6583 && CONSTRUCTOR_IS_DIRECT_INIT (init)
6584 && CONSTRUCTOR_NELTS (init) == 1
6585 /* DR 2374: The single element needs to be implicitly
6586 convertible to the underlying type of the enum. */
6587 && can_convert_arg (ENUM_UNDERLYING_TYPE (type),
6588 TREE_TYPE (CONSTRUCTOR_ELT (init, 0)->value),
6589 CONSTRUCTOR_ELT (init, 0)->value,
6590 LOOKUP_IMPLICIT, tf_none))
6591 return true;
6592 return false;
6595 /* Subroutine of reshape_init_array and reshape_init_vector, which does
6596 the actual work. ELT_TYPE is the element type of the array. MAX_INDEX is an
6597 INTEGER_CST representing the size of the array minus one (the maximum index),
6598 or NULL_TREE if the array was declared without specifying the size. D is
6599 the iterator within the constructor. */
6601 static tree
6602 reshape_init_array_1 (tree elt_type, tree max_index, reshape_iter *d,
6603 tree first_initializer_p, tsubst_flags_t complain)
6605 tree new_init;
6606 bool sized_array_p = (max_index && TREE_CONSTANT (max_index));
6607 unsigned HOST_WIDE_INT max_index_cst = 0;
6608 unsigned HOST_WIDE_INT index;
6610 /* The initializer for an array is always a CONSTRUCTOR. If this is the
6611 outermost CONSTRUCTOR and the element type is non-aggregate, we don't need
6612 to build a new one. But don't reuse if not complaining; if this is
6613 tentative, we might also reshape to another type (95319). */
6614 bool reuse = (first_initializer_p
6615 && (complain & tf_error)
6616 && !CP_AGGREGATE_TYPE_P (elt_type)
6617 && !TREE_SIDE_EFFECTS (first_initializer_p));
6618 if (reuse)
6619 new_init = first_initializer_p;
6620 else
6621 new_init = build_constructor (init_list_type_node, NULL);
6623 if (sized_array_p)
6625 /* Minus 1 is used for zero sized arrays. */
6626 if (integer_all_onesp (max_index))
6627 return new_init;
6629 if (tree_fits_uhwi_p (max_index))
6630 max_index_cst = tree_to_uhwi (max_index);
6631 /* sizetype is sign extended, not zero extended. */
6632 else
6633 max_index_cst = tree_to_uhwi (fold_convert (size_type_node, max_index));
6636 /* Loop until there are no more initializers. */
6637 for (index = 0;
6638 d->cur != d->end && (!sized_array_p || index <= max_index_cst);
6639 ++index)
6641 tree elt_init;
6642 constructor_elt *old_cur = d->cur;
6644 if (d->cur->index)
6645 CONSTRUCTOR_IS_DESIGNATED_INIT (new_init) = true;
6646 check_array_designated_initializer (d->cur, index);
6647 elt_init = reshape_init_r (elt_type, d,
6648 /*first_initializer_p=*/NULL_TREE,
6649 complain);
6650 if (elt_init == error_mark_node)
6651 return error_mark_node;
6652 tree idx = size_int (index);
6653 if (reuse)
6655 old_cur->index = idx;
6656 old_cur->value = elt_init;
6658 else
6659 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
6660 idx, elt_init);
6661 if (!TREE_CONSTANT (elt_init))
6662 TREE_CONSTANT (new_init) = false;
6664 /* This can happen with an invalid initializer (c++/54501). */
6665 if (d->cur == old_cur && !sized_array_p)
6666 break;
6669 return new_init;
6672 /* Subroutine of reshape_init_r, processes the initializers for arrays.
6673 Parameters are the same of reshape_init_r. */
6675 static tree
6676 reshape_init_array (tree type, reshape_iter *d, tree first_initializer_p,
6677 tsubst_flags_t complain)
6679 tree max_index = NULL_TREE;
6681 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
6683 if (TYPE_DOMAIN (type))
6684 max_index = array_type_nelts (type);
6686 return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6687 first_initializer_p, complain);
6690 /* Subroutine of reshape_init_r, processes the initializers for vectors.
6691 Parameters are the same of reshape_init_r. */
6693 static tree
6694 reshape_init_vector (tree type, reshape_iter *d, tsubst_flags_t complain)
6696 tree max_index = NULL_TREE;
6698 gcc_assert (VECTOR_TYPE_P (type));
6700 if (COMPOUND_LITERAL_P (d->cur->value))
6702 tree value = d->cur->value;
6703 if (!same_type_p (TREE_TYPE (value), type))
6705 if (complain & tf_error)
6706 error ("invalid type %qT as initializer for a vector of type %qT",
6707 TREE_TYPE (d->cur->value), type);
6708 value = error_mark_node;
6710 ++d->cur;
6711 return value;
6714 /* For a vector, we initialize it as an array of the appropriate size. */
6715 if (VECTOR_TYPE_P (type))
6716 max_index = size_int (TYPE_VECTOR_SUBPARTS (type) - 1);
6718 return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6719 NULL_TREE, complain);
6722 /* Subroutine of reshape_init*: We're initializing an element with TYPE from
6723 INIT, in isolation from any designator or other initializers. */
6725 static tree
6726 reshape_single_init (tree type, tree init, tsubst_flags_t complain)
6728 /* We could also implement this by wrapping init in a new CONSTRUCTOR and
6729 calling reshape_init, but this way can just live on the stack. */
6730 constructor_elt elt = { /*index=*/NULL_TREE, init };
6731 reshape_iter iter = { &elt, &elt + 1 };
6732 return reshape_init_r (type, &iter,
6733 /*first_initializer_p=*/NULL_TREE,
6734 complain);
6737 /* Subroutine of reshape_init_r, processes the initializers for classes
6738 or union. Parameters are the same of reshape_init_r. */
6740 static tree
6741 reshape_init_class (tree type, reshape_iter *d, bool first_initializer_p,
6742 tsubst_flags_t complain)
6744 tree field;
6745 tree new_init;
6747 gcc_assert (CLASS_TYPE_P (type));
6749 /* The initializer for a class is always a CONSTRUCTOR. */
6750 new_init = build_constructor (init_list_type_node, NULL);
6752 int binfo_idx = -1;
6753 tree binfo = TYPE_BINFO (type);
6754 tree base_binfo = NULL_TREE;
6755 if (cxx_dialect >= cxx17 && uses_template_parms (type))
6757 /* We get here from maybe_aggr_guide for C++20 class template argument
6758 deduction. In this case we need to look through the binfo because a
6759 template doesn't have base fields. */
6760 binfo_idx = 0;
6761 BINFO_BASE_ITERATE (binfo, binfo_idx, base_binfo);
6763 if (base_binfo)
6764 field = base_binfo;
6765 else
6766 field = next_aggregate_field (TYPE_FIELDS (type));
6768 if (!field)
6770 /* [dcl.init.aggr]
6772 An initializer for an aggregate member that is an
6773 empty class shall have the form of an empty
6774 initializer-list {}. */
6775 if (!first_initializer_p)
6777 if (complain & tf_error)
6778 error ("initializer for %qT must be brace-enclosed", type);
6779 return error_mark_node;
6781 return new_init;
6784 /* For C++20 CTAD, handle pack expansions in the base list. */
6785 tree last_was_pack_expansion = NULL_TREE;
6787 /* Loop through the initializable fields, gathering initializers. */
6788 while (d->cur != d->end)
6790 tree field_init;
6791 constructor_elt *old_cur = d->cur;
6792 bool direct_desig = false;
6794 /* Handle C++20 designated initializers. */
6795 if (d->cur->index)
6797 if (d->cur->index == error_mark_node)
6798 return error_mark_node;
6800 if (TREE_CODE (d->cur->index) == FIELD_DECL)
6802 /* We already reshaped this; we should have returned early from
6803 reshape_init. */
6804 gcc_checking_assert (false);
6805 if (field != d->cur->index)
6807 if (tree id = DECL_NAME (d->cur->index))
6808 gcc_checking_assert (d->cur->index
6809 == get_class_binding (type, id));
6810 field = d->cur->index;
6813 else if (TREE_CODE (d->cur->index) == IDENTIFIER_NODE)
6815 CONSTRUCTOR_IS_DESIGNATED_INIT (new_init) = true;
6816 field = get_class_binding (type, d->cur->index);
6817 direct_desig = true;
6819 else
6821 if (complain & tf_error)
6822 error ("%<[%E] =%> used in a GNU-style designated initializer"
6823 " for class %qT", d->cur->index, type);
6824 return error_mark_node;
6827 if (!field && ANON_AGGR_TYPE_P (type))
6828 /* Apparently the designator isn't for a member of this anonymous
6829 struct, so head back to the enclosing class. */
6830 break;
6832 if (!field || TREE_CODE (field) != FIELD_DECL)
6834 if (complain & tf_error)
6835 error ("%qT has no non-static data member named %qD", type,
6836 d->cur->index);
6837 return error_mark_node;
6840 /* If the element is an anonymous union object and the initializer
6841 list is a designated-initializer-list, the anonymous union object
6842 is initialized by the designated-initializer-list { D }, where D
6843 is the designated-initializer-clause naming a member of the
6844 anonymous union object. */
6845 tree ictx = DECL_CONTEXT (field);
6846 if (!same_type_ignoring_top_level_qualifiers_p (ictx, type))
6848 /* Find the anon aggr that is a direct member of TYPE. */
6849 while (ANON_AGGR_TYPE_P (ictx))
6851 tree cctx = TYPE_CONTEXT (ictx);
6852 if (same_type_ignoring_top_level_qualifiers_p (cctx, type))
6853 goto found;
6854 ictx = cctx;
6857 /* Not found, e.g. FIELD is a member of a base class. */
6858 if (complain & tf_error)
6859 error ("%qD is not a direct member of %qT", field, type);
6860 return error_mark_node;
6862 found:
6863 /* Now find the TYPE member with that anon aggr type. */
6864 tree aafield = TYPE_FIELDS (type);
6865 for (; aafield; aafield = TREE_CHAIN (aafield))
6866 if (TREE_TYPE (aafield) == ictx)
6867 break;
6868 gcc_assert (aafield);
6869 field = aafield;
6870 direct_desig = false;
6874 /* If we processed all the member of the class, we are done. */
6875 if (!field)
6876 break;
6878 last_was_pack_expansion = (PACK_EXPANSION_P (TREE_TYPE (field))
6879 ? field : NULL_TREE);
6880 if (last_was_pack_expansion)
6881 /* Each non-trailing aggregate element that is a pack expansion is
6882 assumed to correspond to no elements of the initializer list. */
6883 goto continue_;
6885 if (direct_desig)
6887 /* The designated field F is initialized from this one element.
6889 Note that we don't want to do this if we found the designator
6890 inside an anon aggr above; we use the normal code to implement:
6892 "If the element is an anonymous union member and the initializer
6893 list is a brace-enclosed designated- initializer-list, the element
6894 is initialized by the designated-initializer-list { D }, where D
6895 is the designated- initializer-clause naming a member of the
6896 anonymous union member." */
6897 field_init = reshape_single_init (TREE_TYPE (field),
6898 d->cur->value, complain);
6899 d->cur++;
6901 else
6902 field_init = reshape_init_r (TREE_TYPE (field), d,
6903 /*first_initializer_p=*/NULL_TREE,
6904 complain);
6906 if (field_init == error_mark_node)
6907 return error_mark_node;
6909 if (d->cur == old_cur && d->cur->index)
6911 /* This can happen with an invalid initializer for a flexible
6912 array member (c++/54441). */
6913 if (complain & tf_error)
6914 error ("invalid initializer for %q#D", field);
6915 return error_mark_node;
6918 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init), field, field_init);
6920 /* [dcl.init.aggr]
6922 When a union is initialized with a brace-enclosed
6923 initializer, the braces shall only contain an
6924 initializer for the first member of the union. */
6925 if (TREE_CODE (type) == UNION_TYPE)
6926 break;
6928 continue_:
6929 if (base_binfo)
6931 if (BINFO_BASE_ITERATE (binfo, ++binfo_idx, base_binfo))
6932 field = base_binfo;
6933 else
6934 field = next_aggregate_field (TYPE_FIELDS (type));
6936 else
6937 field = next_aggregate_field (DECL_CHAIN (field));
6940 /* A trailing aggregate element that is a pack expansion is assumed to
6941 correspond to all remaining elements of the initializer list (if any). */
6942 if (last_was_pack_expansion)
6944 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
6945 last_was_pack_expansion, d->cur->value);
6946 while (d->cur != d->end)
6947 d->cur++;
6950 return new_init;
6953 /* Subroutine of reshape_init_r. We're in a context where C99 initializer
6954 designators are not valid; either complain or return true to indicate
6955 that reshape_init_r should return error_mark_node. */
6957 static bool
6958 has_designator_problem (reshape_iter *d, tsubst_flags_t complain)
6960 if (d->cur->index)
6962 if (complain & tf_error)
6963 error_at (cp_expr_loc_or_input_loc (d->cur->index),
6964 "C99 designator %qE outside aggregate initializer",
6965 d->cur->index);
6966 else
6967 return true;
6969 return false;
6972 /* Subroutine of reshape_init, which processes a single initializer (part of
6973 a CONSTRUCTOR). TYPE is the type of the variable being initialized, D is the
6974 iterator within the CONSTRUCTOR which points to the initializer to process.
6975 If this is the first initializer of the outermost CONSTRUCTOR node,
6976 FIRST_INITIALIZER_P is that CONSTRUCTOR; otherwise, it is NULL_TREE. */
6978 static tree
6979 reshape_init_r (tree type, reshape_iter *d, tree first_initializer_p,
6980 tsubst_flags_t complain)
6982 tree init = d->cur->value;
6984 if (error_operand_p (init))
6985 return error_mark_node;
6987 if (first_initializer_p && !CP_AGGREGATE_TYPE_P (type)
6988 && has_designator_problem (d, complain))
6989 return error_mark_node;
6991 tree stripped_init = tree_strip_any_location_wrapper (init);
6993 if (TREE_CODE (type) == COMPLEX_TYPE)
6995 /* A complex type can be initialized from one or two initializers,
6996 but braces are not elided. */
6997 d->cur++;
6998 if (BRACE_ENCLOSED_INITIALIZER_P (stripped_init))
7000 if (CONSTRUCTOR_NELTS (stripped_init) > 2)
7002 if (complain & tf_error)
7003 error ("too many initializers for %qT", type);
7004 else
7005 return error_mark_node;
7008 else if (first_initializer_p && d->cur != d->end)
7010 vec<constructor_elt, va_gc> *v = 0;
7011 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
7012 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, d->cur->value);
7013 if (has_designator_problem (d, complain))
7014 return error_mark_node;
7015 d->cur++;
7016 init = build_constructor (init_list_type_node, v);
7018 return init;
7021 /* A non-aggregate type is always initialized with a single
7022 initializer. */
7023 if (!CP_AGGREGATE_TYPE_P (type)
7024 /* As is an array with dependent bound, which we can see
7025 during C++20 aggregate CTAD. */
7026 || (cxx_dialect >= cxx20
7027 && TREE_CODE (type) == ARRAY_TYPE
7028 && uses_template_parms (TYPE_DOMAIN (type))))
7030 /* It is invalid to initialize a non-aggregate type with a
7031 brace-enclosed initializer before C++0x.
7032 We need to check for BRACE_ENCLOSED_INITIALIZER_P here because
7033 of g++.old-deja/g++.mike/p7626.C: a pointer-to-member constant is
7034 a CONSTRUCTOR (with a record type). */
7035 if (TREE_CODE (stripped_init) == CONSTRUCTOR
7036 /* Don't complain about a capture-init. */
7037 && !CONSTRUCTOR_IS_DIRECT_INIT (stripped_init)
7038 && BRACE_ENCLOSED_INITIALIZER_P (stripped_init)) /* p7626.C */
7040 if (SCALAR_TYPE_P (type))
7042 if (cxx_dialect < cxx11)
7044 if (complain & tf_error)
7045 error ("braces around scalar initializer for type %qT",
7046 type);
7047 init = error_mark_node;
7049 else if (first_initializer_p
7050 || (CONSTRUCTOR_NELTS (stripped_init) > 0
7051 && (BRACE_ENCLOSED_INITIALIZER_P
7052 (CONSTRUCTOR_ELT (stripped_init,0)->value))))
7054 if (complain & tf_error)
7055 error ("too many braces around scalar initializer "
7056 "for type %qT", type);
7057 init = error_mark_node;
7060 else
7061 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
7064 d->cur++;
7065 return init;
7068 /* "If T is a class type and the initializer list has a single element of
7069 type cv U, where U is T or a class derived from T, the object is
7070 initialized from that element." Even if T is an aggregate. */
7071 if (cxx_dialect >= cxx11 && (CLASS_TYPE_P (type) || VECTOR_TYPE_P (type))
7072 && first_initializer_p
7073 /* But not if it's a designated init. */
7074 && !d->cur->index
7075 && d->end - d->cur == 1
7076 && reference_related_p (type, TREE_TYPE (init)))
7078 d->cur++;
7079 return init;
7082 /* [dcl.init.aggr]
7084 All implicit type conversions (clause _conv_) are considered when
7085 initializing the aggregate member with an initializer from an
7086 initializer-list. If the initializer can initialize a member,
7087 the member is initialized. Otherwise, if the member is itself a
7088 non-empty subaggregate, brace elision is assumed and the
7089 initializer is considered for the initialization of the first
7090 member of the subaggregate. */
7091 if ((TREE_CODE (init) != CONSTRUCTOR || COMPOUND_LITERAL_P (init))
7092 /* But don't try this for the first initializer, since that would be
7093 looking through the outermost braces; A a2 = { a1 }; is not a
7094 valid aggregate initialization. */
7095 && !first_initializer_p
7096 && (same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (init))
7097 || can_convert_arg (type, TREE_TYPE (init), init, LOOKUP_NORMAL,
7098 complain)))
7100 d->cur++;
7101 return init;
7104 /* [dcl.init.string]
7106 A char array (whether plain char, signed char, or unsigned char)
7107 can be initialized by a string-literal (optionally enclosed in
7108 braces); a wchar_t array can be initialized by a wide
7109 string-literal (optionally enclosed in braces). */
7110 if (TREE_CODE (type) == ARRAY_TYPE
7111 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type))))
7113 tree str_init = init;
7114 tree stripped_str_init = stripped_init;
7115 reshape_iter stripd = {};
7117 /* Strip one level of braces if and only if they enclose a single
7118 element (as allowed by [dcl.init.string]). */
7119 if (!first_initializer_p
7120 && TREE_CODE (stripped_str_init) == CONSTRUCTOR
7121 && CONSTRUCTOR_NELTS (stripped_str_init) == 1)
7123 stripd.cur = CONSTRUCTOR_ELT (stripped_str_init, 0);
7124 str_init = stripd.cur->value;
7125 stripped_str_init = tree_strip_any_location_wrapper (str_init);
7128 /* If it's a string literal, then it's the initializer for the array
7129 as a whole. Otherwise, continue with normal initialization for
7130 array types (one value per array element). */
7131 if (TREE_CODE (stripped_str_init) == STRING_CST)
7133 if ((first_initializer_p && has_designator_problem (d, complain))
7134 || (stripd.cur && has_designator_problem (&stripd, complain)))
7135 return error_mark_node;
7136 d->cur++;
7137 return str_init;
7141 /* The following cases are about aggregates. If we are not within a full
7142 initializer already, and there is not a CONSTRUCTOR, it means that there
7143 is a missing set of braces (that is, we are processing the case for
7144 which reshape_init exists). */
7145 bool braces_elided_p = false;
7146 if (!first_initializer_p)
7148 if (TREE_CODE (stripped_init) == CONSTRUCTOR)
7150 tree init_type = TREE_TYPE (init);
7151 if (init_type && TYPE_PTRMEMFUNC_P (init_type))
7152 /* There is no need to call reshape_init for pointer-to-member
7153 function initializers, as they are always constructed correctly
7154 by the front end. Here we have e.g. {.__pfn=0B, .__delta=0},
7155 which is missing outermost braces. We should warn below, and
7156 one of the routines below will wrap it in additional { }. */;
7157 /* For a nested compound literal, proceed to specialized routines,
7158 to handle initialization of arrays and similar. */
7159 else if (COMPOUND_LITERAL_P (stripped_init))
7160 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
7161 /* If we have an unresolved designator, we need to find the member it
7162 designates within TYPE, so proceed to the routines below. For
7163 FIELD_DECL or INTEGER_CST designators, we're already initializing
7164 the designated element. */
7165 else if (d->cur->index
7166 && TREE_CODE (d->cur->index) == IDENTIFIER_NODE)
7167 /* Brace elision with designators is only permitted for anonymous
7168 aggregates. */
7169 gcc_checking_assert (ANON_AGGR_TYPE_P (type));
7170 /* A CONSTRUCTOR of the target's type is a previously
7171 digested initializer. */
7172 else if (same_type_ignoring_top_level_qualifiers_p (type, init_type))
7174 ++d->cur;
7175 return init;
7177 else
7179 /* Something that hasn't been reshaped yet. */
7180 ++d->cur;
7181 gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
7182 return reshape_init (type, init, complain);
7186 if (complain & tf_warning)
7187 warning (OPT_Wmissing_braces,
7188 "missing braces around initializer for %qT",
7189 type);
7190 braces_elided_p = true;
7193 /* Dispatch to specialized routines. */
7194 tree new_init;
7195 if (CLASS_TYPE_P (type))
7196 new_init = reshape_init_class (type, d, first_initializer_p, complain);
7197 else if (TREE_CODE (type) == ARRAY_TYPE)
7198 new_init = reshape_init_array (type, d, first_initializer_p, complain);
7199 else if (VECTOR_TYPE_P (type))
7200 new_init = reshape_init_vector (type, d, complain);
7201 else
7202 gcc_unreachable();
7204 if (braces_elided_p
7205 && TREE_CODE (new_init) == CONSTRUCTOR)
7206 CONSTRUCTOR_BRACES_ELIDED_P (new_init) = true;
7208 return new_init;
7211 /* Undo the brace-elision allowed by [dcl.init.aggr] in a
7212 brace-enclosed aggregate initializer.
7214 INIT is the CONSTRUCTOR containing the list of initializers describing
7215 a brace-enclosed initializer for an entity of the indicated aggregate TYPE.
7216 It may not presently match the shape of the TYPE; for example:
7218 struct S { int a; int b; };
7219 struct S a[] = { 1, 2, 3, 4 };
7221 Here INIT will hold a vector of four elements, rather than a
7222 vector of two elements, each itself a vector of two elements. This
7223 routine transforms INIT from the former form into the latter. The
7224 revised CONSTRUCTOR node is returned. */
7226 tree
7227 reshape_init (tree type, tree init, tsubst_flags_t complain)
7229 vec<constructor_elt, va_gc> *v;
7230 reshape_iter d;
7231 tree new_init;
7233 gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (init));
7235 v = CONSTRUCTOR_ELTS (init);
7237 /* An empty constructor does not need reshaping, and it is always a valid
7238 initializer. */
7239 if (vec_safe_is_empty (v))
7240 return init;
7242 if ((*v)[0].index && TREE_CODE ((*v)[0].index) == FIELD_DECL)
7243 /* Already reshaped. */
7244 return init;
7246 /* Brace elision is not performed for a CONSTRUCTOR representing
7247 parenthesized aggregate initialization. */
7248 if (CONSTRUCTOR_IS_PAREN_INIT (init))
7250 tree elt = (*v)[0].value;
7251 /* If we're initializing a char array from a string-literal that is
7252 enclosed in braces, unwrap it here. */
7253 if (TREE_CODE (type) == ARRAY_TYPE
7254 && vec_safe_length (v) == 1
7255 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
7256 && TREE_CODE (tree_strip_any_location_wrapper (elt)) == STRING_CST)
7257 return elt;
7258 return init;
7261 /* Handle [dcl.init.list] direct-list-initialization from
7262 single element of enumeration with a fixed underlying type. */
7263 if (is_direct_enum_init (type, init))
7265 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
7266 type = cv_unqualified (type);
7267 if (check_narrowing (ENUM_UNDERLYING_TYPE (type), elt, complain))
7269 warning_sentinel w (warn_useless_cast);
7270 warning_sentinel w2 (warn_ignored_qualifiers);
7271 return cp_build_c_cast (input_location, type, elt,
7272 tf_warning_or_error);
7274 else
7275 return error_mark_node;
7278 /* Recurse on this CONSTRUCTOR. */
7279 d.cur = &(*v)[0];
7280 d.end = d.cur + v->length ();
7282 new_init = reshape_init_r (type, &d, init, complain);
7283 if (new_init == error_mark_node)
7284 return error_mark_node;
7286 /* Make sure all the element of the constructor were used. Otherwise,
7287 issue an error about exceeding initializers. */
7288 if (d.cur != d.end)
7290 if (complain & tf_error)
7291 error ("too many initializers for %qT", type);
7292 return error_mark_node;
7295 if (CONSTRUCTOR_IS_DIRECT_INIT (init)
7296 && BRACE_ENCLOSED_INITIALIZER_P (new_init))
7297 CONSTRUCTOR_IS_DIRECT_INIT (new_init) = true;
7298 if (CONSTRUCTOR_IS_DESIGNATED_INIT (init)
7299 && BRACE_ENCLOSED_INITIALIZER_P (new_init))
7300 gcc_checking_assert (CONSTRUCTOR_IS_DESIGNATED_INIT (new_init)
7301 || seen_error ());
7303 return new_init;
7306 /* Verify array initializer. Returns true if errors have been reported. */
7308 bool
7309 check_array_initializer (tree decl, tree type, tree init)
7311 tree element_type = TREE_TYPE (type);
7313 /* Structured binding when initialized with an array type needs
7314 to have complete type. */
7315 if (decl
7316 && DECL_DECOMPOSITION_P (decl)
7317 && !DECL_DECOMP_BASE (decl)
7318 && !COMPLETE_TYPE_P (type))
7320 error_at (DECL_SOURCE_LOCATION (decl),
7321 "structured binding has incomplete type %qT", type);
7322 TREE_TYPE (decl) = error_mark_node;
7323 return true;
7326 /* The array type itself need not be complete, because the
7327 initializer may tell us how many elements are in the array.
7328 But, the elements of the array must be complete. */
7329 if (!COMPLETE_TYPE_P (complete_type (element_type)))
7331 if (decl)
7332 error_at (DECL_SOURCE_LOCATION (decl),
7333 "elements of array %q#D have incomplete type", decl);
7334 else
7335 error ("elements of array %q#T have incomplete type", type);
7336 return true;
7339 location_t loc = (decl ? location_of (decl) : input_location);
7340 if (!verify_type_context (loc, TCTX_ARRAY_ELEMENT, element_type))
7341 return true;
7343 /* A compound literal can't have variable size. */
7344 if (init && !decl
7345 && ((COMPLETE_TYPE_P (type) && !TREE_CONSTANT (TYPE_SIZE (type)))
7346 || !TREE_CONSTANT (TYPE_SIZE (element_type))))
7348 error ("variable-sized compound literal");
7349 return true;
7351 return false;
7354 /* Subroutine of check_initializer; args are passed down from that function.
7355 Set stmts_are_full_exprs_p to 1 across a call to build_aggr_init. */
7357 static tree
7358 build_aggr_init_full_exprs (tree decl, tree init, int flags)
7360 gcc_assert (stmts_are_full_exprs_p ());
7361 if (init)
7362 maybe_warn_pessimizing_move (init, TREE_TYPE (decl), /*return_p*/false);
7363 return build_aggr_init (decl, init, flags, tf_warning_or_error);
7366 /* Verify INIT (the initializer for DECL), and record the
7367 initialization in DECL_INITIAL, if appropriate. CLEANUP is as for
7368 grok_reference_init.
7370 If the return value is non-NULL, it is an expression that must be
7371 evaluated dynamically to initialize DECL. */
7373 static tree
7374 check_initializer (tree decl, tree init, int flags, vec<tree, va_gc> **cleanups)
7376 tree type;
7377 tree init_code = NULL;
7378 tree core_type;
7380 /* Things that are going to be initialized need to have complete
7381 type. */
7382 TREE_TYPE (decl) = type = complete_type (TREE_TYPE (decl));
7384 if (DECL_HAS_VALUE_EXPR_P (decl))
7386 /* A variable with DECL_HAS_VALUE_EXPR_P set is just a placeholder,
7387 it doesn't have storage to be initialized. */
7388 gcc_assert (init == NULL_TREE);
7389 return NULL_TREE;
7392 if (type == error_mark_node)
7393 /* We will have already complained. */
7394 return NULL_TREE;
7396 if (TREE_CODE (type) == ARRAY_TYPE)
7398 if (check_array_initializer (decl, type, init))
7399 return NULL_TREE;
7401 else if (!COMPLETE_TYPE_P (type))
7403 error_at (DECL_SOURCE_LOCATION (decl),
7404 "%q#D has incomplete type", decl);
7405 TREE_TYPE (decl) = error_mark_node;
7406 return NULL_TREE;
7408 else
7409 /* There is no way to make a variable-sized class type in GNU C++. */
7410 gcc_assert (TREE_CONSTANT (TYPE_SIZE (type)));
7412 if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
7414 int init_len = CONSTRUCTOR_NELTS (init);
7415 if (SCALAR_TYPE_P (type))
7417 if (init_len == 0)
7419 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
7420 init = build_zero_init (type, NULL_TREE, false);
7422 else if (init_len != 1 && TREE_CODE (type) != COMPLEX_TYPE)
7424 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
7425 "scalar object %qD requires one element in "
7426 "initializer", decl);
7427 TREE_TYPE (decl) = error_mark_node;
7428 return NULL_TREE;
7433 if (TREE_CODE (decl) == CONST_DECL)
7435 gcc_assert (!TYPE_REF_P (type));
7437 DECL_INITIAL (decl) = init;
7439 gcc_assert (init != NULL_TREE);
7440 init = NULL_TREE;
7442 else if (!init && DECL_REALLY_EXTERN (decl))
7444 else if (init || type_build_ctor_call (type)
7445 || TYPE_REF_P (type))
7447 if (TYPE_REF_P (type))
7449 init = grok_reference_init (decl, type, init, flags);
7450 flags |= LOOKUP_ALREADY_DIGESTED;
7452 else if (!init)
7453 check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
7454 tf_warning_or_error);
7455 /* Do not reshape constructors of vectors (they don't need to be
7456 reshaped. */
7457 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
7459 if (is_std_init_list (type))
7461 init = perform_implicit_conversion (type, init,
7462 tf_warning_or_error);
7463 flags |= LOOKUP_ALREADY_DIGESTED;
7465 else if (TYPE_NON_AGGREGATE_CLASS (type))
7467 /* Don't reshape if the class has constructors. */
7468 if (cxx_dialect == cxx98)
7469 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
7470 "in C++98 %qD must be initialized by "
7471 "constructor, not by %<{...}%>",
7472 decl);
7474 else if (VECTOR_TYPE_P (type) && TYPE_VECTOR_OPAQUE (type))
7476 error ("opaque vector types cannot be initialized");
7477 init = error_mark_node;
7479 else
7481 init = reshape_init (type, init, tf_warning_or_error);
7482 flags |= LOOKUP_NO_NARROWING;
7485 /* [dcl.init] "Otherwise, if the destination type is an array, the object
7486 is initialized as follows..." So handle things like
7488 int a[](1, 2, 3);
7490 which is permitted in C++20 by P0960. */
7491 else if (TREE_CODE (init) == TREE_LIST
7492 && TREE_TYPE (init) == NULL_TREE
7493 && TREE_CODE (type) == ARRAY_TYPE
7494 && !DECL_DECOMPOSITION_P (decl)
7495 && (cxx_dialect >= cxx20))
7496 init = do_aggregate_paren_init (init, type);
7497 else if (TREE_CODE (init) == TREE_LIST
7498 && TREE_TYPE (init) != unknown_type_node
7499 && !MAYBE_CLASS_TYPE_P (type))
7501 gcc_assert (TREE_CODE (decl) != RESULT_DECL);
7503 /* We get here with code like `int a (2);' */
7504 init = build_x_compound_expr_from_list (init, ELK_INIT,
7505 tf_warning_or_error);
7508 /* If DECL has an array type without a specific bound, deduce the
7509 array size from the initializer. */
7510 maybe_deduce_size_from_array_init (decl, init);
7511 type = TREE_TYPE (decl);
7512 if (type == error_mark_node)
7513 return NULL_TREE;
7515 if (((type_build_ctor_call (type) || CLASS_TYPE_P (type))
7516 && !(flags & LOOKUP_ALREADY_DIGESTED)
7517 && !(init && BRACE_ENCLOSED_INITIALIZER_P (init)
7518 && CP_AGGREGATE_TYPE_P (type)
7519 && (CLASS_TYPE_P (type)
7520 /* The call to build_aggr_init below could end up
7521 calling build_vec_init, which may break when we
7522 are processing a template. */
7523 || processing_template_decl
7524 || !TYPE_NEEDS_CONSTRUCTING (type)
7525 || type_has_extended_temps (type))))
7526 || (DECL_DECOMPOSITION_P (decl) && TREE_CODE (type) == ARRAY_TYPE))
7528 init_code = build_aggr_init_full_exprs (decl, init, flags);
7530 /* A constructor call is a non-trivial initializer even if
7531 it isn't explicitly written. */
7532 if (TREE_SIDE_EFFECTS (init_code))
7533 DECL_NONTRIVIALLY_INITIALIZED_P (decl) = true;
7535 /* If this is a constexpr initializer, expand_default_init will
7536 have returned an INIT_EXPR rather than a CALL_EXPR. In that
7537 case, pull the initializer back out and pass it down into
7538 store_init_value. */
7539 while (true)
7541 if (TREE_CODE (init_code) == EXPR_STMT
7542 || TREE_CODE (init_code) == STMT_EXPR
7543 || TREE_CODE (init_code) == CONVERT_EXPR)
7544 init_code = TREE_OPERAND (init_code, 0);
7545 else if (TREE_CODE (init_code) == BIND_EXPR)
7546 init_code = BIND_EXPR_BODY (init_code);
7547 else
7548 break;
7550 if (TREE_CODE (init_code) == INIT_EXPR)
7552 /* In C++20, the call to build_aggr_init could have created
7553 an INIT_EXPR with a CONSTRUCTOR as the RHS to handle
7554 A(1, 2). */
7555 tree rhs = TREE_OPERAND (init_code, 1);
7556 if (processing_template_decl && TREE_CODE (rhs) == TARGET_EXPR)
7557 /* Avoid leaking TARGET_EXPR into template trees. */
7558 rhs = build_implicit_conv_flags (type, init, flags);
7559 init = rhs;
7561 init_code = NULL_TREE;
7562 /* Don't call digest_init; it's unnecessary and will complain
7563 about aggregate initialization of non-aggregate classes. */
7564 flags |= LOOKUP_ALREADY_DIGESTED;
7566 else if (DECL_DECLARED_CONSTEXPR_P (decl)
7567 || DECL_DECLARED_CONSTINIT_P (decl))
7569 /* Declared constexpr or constinit, but no suitable initializer;
7570 massage init appropriately so we can pass it into
7571 store_init_value for the error. */
7572 tree new_init = NULL_TREE;
7573 if (!processing_template_decl
7574 && TREE_CODE (init_code) == CALL_EXPR)
7575 new_init = build_cplus_new (type, init_code, tf_none);
7576 else if (CLASS_TYPE_P (type)
7577 && (!init || TREE_CODE (init) == TREE_LIST))
7578 new_init = build_functional_cast (input_location, type,
7579 init, tf_none);
7580 if (new_init)
7582 init = new_init;
7583 if (TREE_CODE (init) == TARGET_EXPR
7584 && !(flags & LOOKUP_ONLYCONVERTING))
7585 TARGET_EXPR_DIRECT_INIT_P (init) = true;
7587 init_code = NULL_TREE;
7589 else
7590 init = NULL_TREE;
7593 if (init && TREE_CODE (init) != TREE_VEC)
7595 init_code = store_init_value (decl, init, cleanups, flags);
7597 if (DECL_INITIAL (decl)
7598 && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
7599 && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl))))
7601 tree elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ().value;
7602 if (TREE_CODE (TREE_TYPE (elt)) == ARRAY_TYPE
7603 && TYPE_SIZE (TREE_TYPE (elt)) == NULL_TREE)
7604 cp_complete_array_type (&TREE_TYPE (elt), elt, false);
7607 if (pedantic && TREE_CODE (type) == ARRAY_TYPE
7608 && DECL_INITIAL (decl)
7609 && TREE_CODE (DECL_INITIAL (decl)) == STRING_CST
7610 && PAREN_STRING_LITERAL_P (DECL_INITIAL (decl)))
7611 warning_at (cp_expr_loc_or_loc (DECL_INITIAL (decl),
7612 DECL_SOURCE_LOCATION (decl)),
7613 0, "array %qD initialized by parenthesized "
7614 "string literal %qE",
7615 decl, DECL_INITIAL (decl));
7616 init = NULL_TREE;
7619 else
7621 if (CLASS_TYPE_P (core_type = strip_array_types (type))
7622 && (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type)
7623 || CLASSTYPE_REF_FIELDS_NEED_INIT (core_type)))
7624 diagnose_uninitialized_cst_or_ref_member (core_type, /*using_new=*/false,
7625 /*complain=*/true);
7627 check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
7628 tf_warning_or_error);
7631 if (init && init != error_mark_node)
7632 init_code = cp_build_init_expr (decl, init);
7634 if (init_code && !TREE_SIDE_EFFECTS (init_code)
7635 && init_code != error_mark_node)
7636 init_code = NULL_TREE;
7638 if (init_code)
7640 /* We might have set these in cp_finish_decl. */
7641 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = false;
7642 TREE_CONSTANT (decl) = false;
7645 if (init_code
7646 && DECL_IN_AGGR_P (decl)
7647 && DECL_INITIALIZED_IN_CLASS_P (decl))
7649 static int explained = 0;
7651 if (cxx_dialect < cxx11)
7652 error ("initializer invalid for static member with constructor");
7653 else if (cxx_dialect < cxx17)
7654 error ("non-constant in-class initialization invalid for static "
7655 "member %qD", decl);
7656 else
7657 error ("non-constant in-class initialization invalid for non-inline "
7658 "static member %qD", decl);
7659 if (!explained)
7661 inform (input_location,
7662 "(an out of class initialization is required)");
7663 explained = 1;
7665 return NULL_TREE;
7668 return init_code;
7671 /* If DECL is not a local variable, give it RTL. */
7673 static void
7674 make_rtl_for_nonlocal_decl (tree decl, tree init, const char* asmspec)
7676 int toplev = toplevel_bindings_p ();
7677 int defer_p;
7679 /* Set the DECL_ASSEMBLER_NAME for the object. */
7680 if (asmspec)
7682 /* The `register' keyword, when used together with an
7683 asm-specification, indicates that the variable should be
7684 placed in a particular register. */
7685 if (VAR_P (decl) && DECL_REGISTER (decl))
7687 set_user_assembler_name (decl, asmspec);
7688 DECL_HARD_REGISTER (decl) = 1;
7690 else
7692 if (TREE_CODE (decl) == FUNCTION_DECL
7693 && fndecl_built_in_p (decl, BUILT_IN_NORMAL))
7694 set_builtin_user_assembler_name (decl, asmspec);
7695 set_user_assembler_name (decl, asmspec);
7696 if (DECL_LOCAL_DECL_P (decl))
7697 if (auto ns_decl = DECL_LOCAL_DECL_ALIAS (decl))
7698 /* We have to propagate the name to the ns-alias.
7699 This is horrible, as we're affecting a
7700 possibly-shared decl. Again, a one-true-decl
7701 model breaks down. */
7702 if (ns_decl != error_mark_node)
7703 set_user_assembler_name (ns_decl, asmspec);
7707 /* Handle non-variables up front. */
7708 if (!VAR_P (decl))
7710 rest_of_decl_compilation (decl, toplev, at_eof);
7711 return;
7714 /* If we see a class member here, it should be a static data
7715 member. */
7716 if (DECL_LANG_SPECIFIC (decl) && DECL_IN_AGGR_P (decl))
7718 gcc_assert (TREE_STATIC (decl));
7719 /* An in-class declaration of a static data member should be
7720 external; it is only a declaration, and not a definition. */
7721 if (init == NULL_TREE)
7722 gcc_assert (DECL_EXTERNAL (decl)
7723 || !TREE_PUBLIC (decl));
7726 /* We don't create any RTL for local variables. */
7727 if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
7728 return;
7730 /* We defer emission of local statics until the corresponding
7731 DECL_EXPR is expanded. But with constexpr its function might never
7732 be expanded, so go ahead and tell cgraph about the variable now. */
7733 defer_p = ((DECL_FUNCTION_SCOPE_P (decl)
7734 && !var_in_maybe_constexpr_fn (decl))
7735 || DECL_VIRTUAL_P (decl));
7737 /* Defer template instantiations. */
7738 if (DECL_LANG_SPECIFIC (decl)
7739 && DECL_IMPLICIT_INSTANTIATION (decl))
7740 defer_p = 1;
7742 /* If we're not deferring, go ahead and assemble the variable. */
7743 if (!defer_p)
7744 rest_of_decl_compilation (decl, toplev, at_eof);
7747 /* walk_tree helper for wrap_temporary_cleanups, below. */
7749 static tree
7750 wrap_cleanups_r (tree *stmt_p, int *walk_subtrees, void *data)
7752 /* Stop at types or full-expression boundaries. */
7753 if (TYPE_P (*stmt_p)
7754 || TREE_CODE (*stmt_p) == CLEANUP_POINT_EXPR)
7756 *walk_subtrees = 0;
7757 return NULL_TREE;
7760 if (TREE_CODE (*stmt_p) == TARGET_EXPR)
7762 tree guard = (tree)data;
7763 tree tcleanup = TARGET_EXPR_CLEANUP (*stmt_p);
7765 if (tcleanup && !CLEANUP_EH_ONLY (*stmt_p)
7766 && !expr_noexcept_p (tcleanup, tf_none))
7768 tcleanup = build2 (TRY_CATCH_EXPR, void_type_node, tcleanup, guard);
7769 /* Tell honor_protect_cleanup_actions to handle this as a separate
7770 cleanup. */
7771 TRY_CATCH_IS_CLEANUP (tcleanup) = 1;
7772 TARGET_EXPR_CLEANUP (*stmt_p) = tcleanup;
7776 return NULL_TREE;
7779 /* We're initializing a local variable which has a cleanup GUARD. If there
7780 are any temporaries used in the initializer INIT of this variable, we
7781 need to wrap their cleanups with TRY_CATCH_EXPR (, GUARD) so that the
7782 variable will be cleaned up properly if one of them throws.
7784 Unfortunately, there's no way to express this properly in terms of
7785 nesting, as the regions for the temporaries overlap the region for the
7786 variable itself; if there are two temporaries, the variable needs to be
7787 the first thing destroyed if either of them throws. However, we only
7788 want to run the variable's cleanup if it actually got constructed. So
7789 we need to guard the temporary cleanups with the variable's cleanup if
7790 they are run on the normal path, but not if they are run on the
7791 exceptional path. We implement this by telling
7792 honor_protect_cleanup_actions to strip the variable cleanup from the
7793 exceptional path.
7795 Another approach could be to make the variable cleanup region enclose
7796 initialization, but depend on a flag to indicate that the variable is
7797 initialized; that's effectively what we do for arrays. But the current
7798 approach works fine for non-arrays, and has no code overhead in the usual
7799 case where the temporary destructors are noexcept. */
7801 static void
7802 wrap_temporary_cleanups (tree init, tree guard)
7804 if (TREE_CODE (guard) == BIND_EXPR)
7806 /* An array cleanup region already encloses any temporary cleanups,
7807 don't wrap it around them again. */
7808 gcc_checking_assert (BIND_EXPR_VEC_DTOR (guard));
7809 return;
7811 cp_walk_tree_without_duplicates (&init, wrap_cleanups_r, (void *)guard);
7814 /* Generate code to initialize DECL (a local variable). */
7816 static void
7817 initialize_local_var (tree decl, tree init)
7819 tree type = TREE_TYPE (decl);
7820 tree cleanup;
7821 int already_used;
7823 gcc_assert (VAR_P (decl)
7824 || TREE_CODE (decl) == RESULT_DECL);
7825 gcc_assert (!TREE_STATIC (decl));
7827 if (DECL_SIZE (decl) == NULL_TREE)
7829 /* If we used it already as memory, it must stay in memory. */
7830 DECL_INITIAL (decl) = NULL_TREE;
7831 TREE_ADDRESSABLE (decl) = TREE_USED (decl);
7832 return;
7835 if (type == error_mark_node)
7836 return;
7838 /* Compute and store the initial value. */
7839 already_used = TREE_USED (decl) || TREE_USED (type);
7840 if (TREE_USED (type))
7841 DECL_READ_P (decl) = 1;
7843 /* Generate a cleanup, if necessary. */
7844 cleanup = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
7846 /* Perform the initialization. */
7847 if (init)
7849 tree rinit = (TREE_CODE (init) == INIT_EXPR
7850 ? TREE_OPERAND (init, 1) : NULL_TREE);
7851 if (rinit && !TREE_SIDE_EFFECTS (rinit)
7852 && TREE_OPERAND (init, 0) == decl)
7854 /* Stick simple initializers in DECL_INITIAL so that
7855 -Wno-init-self works (c++/34772). */
7856 DECL_INITIAL (decl) = rinit;
7858 if (warn_init_self && TYPE_REF_P (type))
7860 STRIP_NOPS (rinit);
7861 if (rinit == decl)
7862 warning_at (DECL_SOURCE_LOCATION (decl),
7863 OPT_Winit_self,
7864 "reference %qD is initialized with itself", decl);
7867 else
7869 int saved_stmts_are_full_exprs_p;
7871 /* If we're only initializing a single object, guard the
7872 destructors of any temporaries used in its initializer with
7873 its destructor. */
7874 if (cleanup)
7875 wrap_temporary_cleanups (init, cleanup);
7877 gcc_assert (building_stmt_list_p ());
7878 saved_stmts_are_full_exprs_p = stmts_are_full_exprs_p ();
7879 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
7880 finish_expr_stmt (init);
7881 current_stmt_tree ()->stmts_are_full_exprs_p =
7882 saved_stmts_are_full_exprs_p;
7886 /* Set this to 0 so we can tell whether an aggregate which was
7887 initialized was ever used. Don't do this if it has a
7888 destructor, so we don't complain about the 'resource
7889 allocation is initialization' idiom. Now set
7890 attribute((unused)) on types so decls of that type will be
7891 marked used. (see TREE_USED, above.) */
7892 if (TYPE_NEEDS_CONSTRUCTING (type)
7893 && ! already_used
7894 && TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
7895 && DECL_NAME (decl))
7896 TREE_USED (decl) = 0;
7897 else if (already_used)
7898 TREE_USED (decl) = 1;
7900 if (cleanup)
7901 finish_decl_cleanup (decl, cleanup);
7904 /* DECL is a VAR_DECL for a compiler-generated variable with static
7905 storage duration (like a virtual table) whose initializer is a
7906 compile-time constant. Initialize the variable and provide it to the
7907 back end. */
7909 void
7910 initialize_artificial_var (tree decl, vec<constructor_elt, va_gc> *v)
7912 tree init;
7913 gcc_assert (DECL_ARTIFICIAL (decl));
7914 init = build_constructor (TREE_TYPE (decl), v);
7915 gcc_assert (TREE_CODE (init) == CONSTRUCTOR);
7916 DECL_INITIAL (decl) = init;
7917 DECL_INITIALIZED_P (decl) = 1;
7918 /* Mark the decl as constexpr so that we can access its content
7919 at compile time. */
7920 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
7921 DECL_DECLARED_CONSTEXPR_P (decl) = true;
7922 determine_visibility (decl);
7923 layout_var_decl (decl);
7924 maybe_commonize_var (decl);
7925 make_rtl_for_nonlocal_decl (decl, init, /*asmspec=*/NULL);
7928 /* INIT is the initializer for a variable, as represented by the
7929 parser. Returns true iff INIT is value-dependent. */
7931 static bool
7932 value_dependent_init_p (tree init)
7934 if (TREE_CODE (init) == TREE_LIST)
7935 /* A parenthesized initializer, e.g.: int i (3, 2); ? */
7936 return any_value_dependent_elements_p (init);
7937 else if (TREE_CODE (init) == CONSTRUCTOR)
7938 /* A brace-enclosed initializer, e.g.: int i = { 3 }; ? */
7940 if (dependent_type_p (TREE_TYPE (init)))
7941 return true;
7943 vec<constructor_elt, va_gc> *elts;
7944 size_t nelts;
7945 size_t i;
7947 elts = CONSTRUCTOR_ELTS (init);
7948 nelts = vec_safe_length (elts);
7949 for (i = 0; i < nelts; ++i)
7950 if (value_dependent_init_p ((*elts)[i].value))
7951 return true;
7953 else
7954 /* It must be a simple expression, e.g., int i = 3; */
7955 return value_dependent_expression_p (init);
7957 return false;
7960 // Returns true if a DECL is VAR_DECL with the concept specifier.
7961 static inline bool
7962 is_concept_var (tree decl)
7964 return (VAR_P (decl)
7965 // Not all variables have DECL_LANG_SPECIFIC.
7966 && DECL_LANG_SPECIFIC (decl)
7967 && DECL_DECLARED_CONCEPT_P (decl));
7970 /* A helper function to be called via walk_tree. If any label exists
7971 under *TP, it is (going to be) forced. Set has_forced_label_in_static. */
7973 static tree
7974 notice_forced_label_r (tree *tp, int *walk_subtrees, void *)
7976 if (TYPE_P (*tp))
7977 *walk_subtrees = 0;
7978 if (TREE_CODE (*tp) == LABEL_DECL)
7979 cfun->has_forced_label_in_static = 1;
7980 return NULL_TREE;
7983 /* Return true if DECL has either a trivial destructor, or for C++20
7984 is constexpr and has a constexpr destructor. */
7986 static bool
7987 decl_maybe_constant_destruction (tree decl, tree type)
7989 return (TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
7990 || (cxx_dialect >= cxx20
7991 && VAR_P (decl)
7992 && DECL_DECLARED_CONSTEXPR_P (decl)
7993 && type_has_constexpr_destructor (strip_array_types (type))));
7996 static tree declare_simd_adjust_this (tree *, int *, void *);
7998 /* Helper function of omp_declare_variant_finalize. Finalize one
7999 "omp declare variant base" attribute. Return true if it should be
8000 removed. */
8002 static bool
8003 omp_declare_variant_finalize_one (tree decl, tree attr)
8005 if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
8007 walk_tree (&TREE_VALUE (TREE_VALUE (attr)), declare_simd_adjust_this,
8008 DECL_ARGUMENTS (decl), NULL);
8009 walk_tree (&TREE_PURPOSE (TREE_VALUE (attr)), declare_simd_adjust_this,
8010 DECL_ARGUMENTS (decl), NULL);
8013 tree ctx = TREE_VALUE (TREE_VALUE (attr));
8014 tree simd = omp_get_context_selector (ctx, "construct", "simd");
8015 if (simd)
8017 TREE_VALUE (simd)
8018 = c_omp_declare_simd_clauses_to_numbers (DECL_ARGUMENTS (decl),
8019 TREE_VALUE (simd));
8020 /* FIXME, adjusting simd args unimplemented. */
8021 return true;
8024 tree chain = TREE_CHAIN (TREE_VALUE (attr));
8025 location_t varid_loc
8026 = cp_expr_loc_or_input_loc (TREE_PURPOSE (TREE_CHAIN (chain)));
8027 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
8028 cp_id_kind idk = (cp_id_kind) tree_to_uhwi (TREE_VALUE (chain));
8029 tree variant = TREE_PURPOSE (TREE_VALUE (attr));
8031 location_t save_loc = input_location;
8032 input_location = varid_loc;
8034 releasing_vec args;
8035 tree parm = DECL_ARGUMENTS (decl);
8036 if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
8037 parm = DECL_CHAIN (parm);
8038 for (; parm; parm = DECL_CHAIN (parm))
8039 if (type_dependent_expression_p (parm))
8040 vec_safe_push (args, build_constructor (TREE_TYPE (parm), NULL));
8041 else if (MAYBE_CLASS_TYPE_P (TREE_TYPE (parm)))
8042 vec_safe_push (args, build_local_temp (TREE_TYPE (parm)));
8043 else
8044 vec_safe_push (args, build_zero_cst (TREE_TYPE (parm)));
8046 bool koenig_p = false;
8047 if (idk == CP_ID_KIND_UNQUALIFIED || idk == CP_ID_KIND_TEMPLATE_ID)
8049 if (identifier_p (variant)
8050 /* In C++20, we may need to perform ADL for a template
8051 name. */
8052 || (TREE_CODE (variant) == TEMPLATE_ID_EXPR
8053 && identifier_p (TREE_OPERAND (variant, 0))))
8055 if (!args->is_empty ())
8057 koenig_p = true;
8058 if (!any_type_dependent_arguments_p (args))
8059 variant = perform_koenig_lookup (variant, args,
8060 tf_warning_or_error);
8062 else
8063 variant = unqualified_fn_lookup_error (variant);
8065 else if (!args->is_empty () && is_overloaded_fn (variant))
8067 tree fn = get_first_fn (variant);
8068 fn = STRIP_TEMPLATE (fn);
8069 if (!((TREE_CODE (fn) == USING_DECL && DECL_DEPENDENT_P (fn))
8070 || DECL_FUNCTION_MEMBER_P (fn)
8071 || DECL_LOCAL_DECL_P (fn)))
8073 koenig_p = true;
8074 if (!any_type_dependent_arguments_p (args))
8075 variant = perform_koenig_lookup (variant, args,
8076 tf_warning_or_error);
8081 if (idk == CP_ID_KIND_QUALIFIED)
8082 variant = finish_call_expr (variant, &args, /*disallow_virtual=*/true,
8083 koenig_p, tf_warning_or_error);
8084 else
8085 variant = finish_call_expr (variant, &args, /*disallow_virtual=*/false,
8086 koenig_p, tf_warning_or_error);
8087 if (variant == error_mark_node && !processing_template_decl)
8088 return true;
8090 variant = cp_get_callee_fndecl_nofold (variant);
8091 input_location = save_loc;
8093 if (variant)
8095 const char *varname = IDENTIFIER_POINTER (DECL_NAME (variant));
8096 if (!comptypes (TREE_TYPE (decl), TREE_TYPE (variant), 0))
8098 error_at (varid_loc, "variant %qD and base %qD have incompatible "
8099 "types", variant, decl);
8100 return true;
8102 if (fndecl_built_in_p (variant)
8103 && (startswith (varname, "__builtin_")
8104 || startswith (varname, "__sync_")
8105 || startswith (varname, "__atomic_")))
8107 error_at (varid_loc, "variant %qD is a built-in", variant);
8108 return true;
8110 else
8112 tree construct = omp_get_context_selector (ctx, "construct", NULL);
8113 omp_mark_declare_variant (match_loc, variant, construct);
8114 if (!omp_context_selector_matches (ctx))
8115 return true;
8116 TREE_PURPOSE (TREE_VALUE (attr)) = variant;
8119 else if (!processing_template_decl)
8121 error_at (varid_loc, "could not find variant declaration");
8122 return true;
8125 return false;
8128 /* Helper function, finish up "omp declare variant base" attribute
8129 now that there is a DECL. ATTR is the first "omp declare variant base"
8130 attribute. */
8132 void
8133 omp_declare_variant_finalize (tree decl, tree attr)
8135 size_t attr_len = strlen ("omp declare variant base");
8136 tree *list = &DECL_ATTRIBUTES (decl);
8137 bool remove_all = false;
8138 location_t match_loc = DECL_SOURCE_LOCATION (decl);
8139 if (TREE_CHAIN (TREE_VALUE (attr))
8140 && TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))
8141 && EXPR_HAS_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))))
8142 match_loc = EXPR_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr))));
8143 if (DECL_CONSTRUCTOR_P (decl))
8145 error_at (match_loc, "%<declare variant%> on constructor %qD", decl);
8146 remove_all = true;
8148 else if (DECL_DESTRUCTOR_P (decl))
8150 error_at (match_loc, "%<declare variant%> on destructor %qD", decl);
8151 remove_all = true;
8153 else if (DECL_DEFAULTED_FN (decl))
8155 error_at (match_loc, "%<declare variant%> on defaulted %qD", decl);
8156 remove_all = true;
8158 else if (DECL_DELETED_FN (decl))
8160 error_at (match_loc, "%<declare variant%> on deleted %qD", decl);
8161 remove_all = true;
8163 else if (DECL_VIRTUAL_P (decl))
8165 error_at (match_loc, "%<declare variant%> on virtual %qD", decl);
8166 remove_all = true;
8168 /* This loop is like private_lookup_attribute, except that it works
8169 with tree * rather than tree, as we might want to remove the
8170 attributes that are diagnosed as errorneous. */
8171 while (*list)
8173 tree attr = get_attribute_name (*list);
8174 size_t ident_len = IDENTIFIER_LENGTH (attr);
8175 if (cmp_attribs ("omp declare variant base", attr_len,
8176 IDENTIFIER_POINTER (attr), ident_len))
8178 if (remove_all || omp_declare_variant_finalize_one (decl, *list))
8180 *list = TREE_CHAIN (*list);
8181 continue;
8184 list = &TREE_CHAIN (*list);
8188 /* Finish processing of a declaration;
8189 install its line number and initial value.
8190 If the length of an array type is not known before,
8191 it must be determined now, from the initial value, or it is an error.
8193 INIT is the initializer (if any) for DECL. If INIT_CONST_EXPR_P is
8194 true, then INIT is an integral constant expression.
8196 FLAGS is LOOKUP_ONLYCONVERTING if the = init syntax was used, else 0
8197 if the (init) syntax was used. */
8199 void
8200 cp_finish_decl (tree decl, tree init, bool init_const_expr_p,
8201 tree asmspec_tree, int flags)
8203 vec<tree, va_gc> *cleanups = NULL;
8204 const char *asmspec = NULL;
8205 int was_readonly = 0;
8206 bool var_definition_p = false;
8207 tree auto_node;
8209 if (decl == error_mark_node)
8210 return;
8211 else if (! decl)
8213 if (init)
8214 error ("assignment (not initialization) in declaration");
8215 return;
8218 gcc_assert (TREE_CODE (decl) != RESULT_DECL);
8219 /* Parameters are handled by store_parm_decls, not cp_finish_decl. */
8220 gcc_assert (TREE_CODE (decl) != PARM_DECL);
8222 tree type = TREE_TYPE (decl);
8223 if (type == error_mark_node)
8224 return;
8226 if (VAR_P (decl) && is_copy_initialization (init))
8227 flags |= LOOKUP_ONLYCONVERTING;
8229 /* Warn about register storage specifiers except when in GNU global
8230 or local register variable extension. */
8231 if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec_tree == NULL_TREE)
8233 if (cxx_dialect >= cxx17)
8234 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
8235 "ISO C++17 does not allow %<register%> storage "
8236 "class specifier");
8237 else
8238 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
8239 "%<register%> storage class specifier used");
8242 /* If a name was specified, get the string. */
8243 if (at_namespace_scope_p ())
8244 asmspec_tree = maybe_apply_renaming_pragma (decl, asmspec_tree);
8245 if (asmspec_tree && asmspec_tree != error_mark_node)
8246 asmspec = TREE_STRING_POINTER (asmspec_tree);
8248 bool in_class_decl
8249 = (current_class_type
8250 && CP_DECL_CONTEXT (decl) == current_class_type
8251 && TYPE_BEING_DEFINED (current_class_type)
8252 && !CLASSTYPE_TEMPLATE_INSTANTIATION (current_class_type));
8254 if (in_class_decl
8255 && (DECL_INITIAL (decl) || init))
8256 DECL_INITIALIZED_IN_CLASS_P (decl) = 1;
8258 if (VAR_P (decl)
8259 && (auto_node = type_uses_auto (type)))
8261 tree d_init;
8262 if (init == NULL_TREE)
8264 if (DECL_LANG_SPECIFIC (decl)
8265 && DECL_TEMPLATE_INSTANTIATION (decl)
8266 && !DECL_TEMPLATE_INSTANTIATED (decl))
8268 /* init is null because we're deferring instantiating the
8269 initializer until we need it. Well, we need it now. */
8270 instantiate_decl (decl, /*defer_ok*/true, /*expl*/false);
8271 return;
8274 if (CLASS_PLACEHOLDER_TEMPLATE (auto_node))
8275 /* Class deduction with no initializer is OK. */;
8276 else
8278 /* Ordinary auto deduction without an initializer, a situation
8279 which grokdeclarator already detects and rejects for the most
8280 part. But we can still get here if we're instantiating a
8281 variable template before we've fully parsed (and attached) its
8282 initializer, e.g. template<class> auto x = x<int>; */
8283 error_at (DECL_SOURCE_LOCATION (decl),
8284 "declaration of %q#D has no initializer", decl);
8285 TREE_TYPE (decl) = error_mark_node;
8286 return;
8289 d_init = init;
8290 if (d_init)
8292 if (TREE_CODE (d_init) == TREE_LIST
8293 && !CLASS_PLACEHOLDER_TEMPLATE (auto_node))
8294 d_init = build_x_compound_expr_from_list (d_init, ELK_INIT,
8295 tf_warning_or_error);
8296 d_init = resolve_nondeduced_context (d_init, tf_warning_or_error);
8297 /* Force auto deduction now. Use tf_none to avoid redundant warnings
8298 on deprecated-14.C. */
8299 mark_single_function (d_init, tf_none);
8301 enum auto_deduction_context adc = adc_variable_type;
8302 if (DECL_DECOMPOSITION_P (decl))
8303 adc = adc_decomp_type;
8304 tree outer_targs = NULL_TREE;
8305 if (PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node)
8306 && DECL_LANG_SPECIFIC (decl)
8307 && DECL_TEMPLATE_INFO (decl)
8308 && !DECL_FUNCTION_SCOPE_P (decl))
8309 /* The outer template arguments might be needed for satisfaction.
8310 (For function scope variables, do_auto_deduction will obtain the
8311 outer template arguments from current_function_decl.) */
8312 outer_targs = DECL_TI_ARGS (decl);
8313 type = TREE_TYPE (decl) = do_auto_deduction (type, d_init, auto_node,
8314 tf_warning_or_error, adc,
8315 outer_targs, flags);
8316 if (type == error_mark_node)
8317 return;
8318 if (TREE_CODE (type) == FUNCTION_TYPE)
8320 error ("initializer for %<decltype(auto) %D%> has function type; "
8321 "did you forget the %<()%>?", decl);
8322 TREE_TYPE (decl) = error_mark_node;
8323 return;
8325 /* As in start_decl_1, complete so TREE_READONLY is set properly. */
8326 if (!processing_template_decl
8327 && !type_uses_auto (type)
8328 && !COMPLETE_TYPE_P (complete_type (type)))
8330 error_at (location_of (decl),
8331 "deduced type %qT for %qD is incomplete", type, decl);
8332 cxx_incomplete_type_inform (type);
8333 TREE_TYPE (decl) = error_mark_node;
8334 return;
8336 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
8338 /* Update the type of the corresponding TEMPLATE_DECL to match. */
8339 if (DECL_LANG_SPECIFIC (decl)
8340 && DECL_TEMPLATE_INFO (decl)
8341 && DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (decl)) == decl)
8342 TREE_TYPE (DECL_TI_TEMPLATE (decl)) = type;
8345 if (ensure_literal_type_for_constexpr_object (decl) == error_mark_node)
8347 DECL_DECLARED_CONSTEXPR_P (decl) = 0;
8348 if (VAR_P (decl) && DECL_CLASS_SCOPE_P (decl))
8350 init = NULL_TREE;
8351 DECL_EXTERNAL (decl) = 1;
8355 if (VAR_P (decl)
8356 && DECL_CLASS_SCOPE_P (decl)
8357 && verify_type_context (DECL_SOURCE_LOCATION (decl),
8358 TCTX_STATIC_STORAGE, type)
8359 && DECL_INITIALIZED_IN_CLASS_P (decl))
8360 check_static_variable_definition (decl, type);
8362 if (!processing_template_decl && VAR_P (decl) && is_global_var (decl))
8364 type_context_kind context = (DECL_THREAD_LOCAL_P (decl)
8365 ? TCTX_THREAD_STORAGE
8366 : TCTX_STATIC_STORAGE);
8367 verify_type_context (input_location, context, TREE_TYPE (decl));
8370 if (init && TREE_CODE (decl) == FUNCTION_DECL)
8372 tree clone;
8373 if (init == ridpointers[(int)RID_DELETE])
8375 /* FIXME check this is 1st decl. */
8376 DECL_DELETED_FN (decl) = 1;
8377 DECL_DECLARED_INLINE_P (decl) = 1;
8378 DECL_INITIAL (decl) = error_mark_node;
8379 FOR_EACH_CLONE (clone, decl)
8381 DECL_DELETED_FN (clone) = 1;
8382 DECL_DECLARED_INLINE_P (clone) = 1;
8383 DECL_INITIAL (clone) = error_mark_node;
8385 init = NULL_TREE;
8387 else if (init == ridpointers[(int)RID_DEFAULT])
8389 if (defaultable_fn_check (decl))
8390 DECL_DEFAULTED_FN (decl) = 1;
8391 else
8392 DECL_INITIAL (decl) = NULL_TREE;
8396 if (init && VAR_P (decl))
8398 DECL_NONTRIVIALLY_INITIALIZED_P (decl) = 1;
8399 /* If DECL is a reference, then we want to know whether init is a
8400 reference constant; init_const_expr_p as passed tells us whether
8401 it's an rvalue constant. */
8402 if (TYPE_REF_P (type))
8403 init_const_expr_p = potential_constant_expression (init);
8404 if (init_const_expr_p)
8406 /* Set these flags now for templates. We'll update the flags in
8407 store_init_value for instantiations. */
8408 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
8409 if (decl_maybe_constant_var_p (decl)
8410 /* FIXME setting TREE_CONSTANT on refs breaks the back end. */
8411 && !TYPE_REF_P (type))
8412 TREE_CONSTANT (decl) = true;
8414 /* This is handled mostly by gimplify.cc, but we have to deal with
8415 not warning about int x = x; as it is a GCC extension to turn off
8416 this warning but only if warn_init_self is zero. */
8417 if (!DECL_EXTERNAL (decl)
8418 && !TREE_STATIC (decl)
8419 && decl == tree_strip_any_location_wrapper (init)
8420 && !warning_enabled_at (DECL_SOURCE_LOCATION (decl), OPT_Winit_self))
8421 suppress_warning (decl, OPT_Winit_self);
8423 else if (VAR_P (decl)
8424 && COMPLETE_TYPE_P (type)
8425 && !TYPE_REF_P (type)
8426 && !dependent_type_p (type)
8427 && is_really_empty_class (type, /*ignore_vptr*/false))
8428 /* We have no initializer but there's nothing to initialize anyway.
8429 Treat DECL as constant due to c++/109876. */
8430 TREE_CONSTANT (decl) = true;
8432 if (flag_openmp
8433 && TREE_CODE (decl) == FUNCTION_DECL
8434 /* #pragma omp declare variant on methods handled in finish_struct
8435 instead. */
8436 && (!DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
8437 || COMPLETE_TYPE_P (DECL_CONTEXT (decl))))
8438 if (tree attr = lookup_attribute ("omp declare variant base",
8439 DECL_ATTRIBUTES (decl)))
8440 omp_declare_variant_finalize (decl, attr);
8442 if (processing_template_decl)
8444 bool type_dependent_p;
8446 /* Add this declaration to the statement-tree. */
8447 if (at_function_scope_p ())
8448 add_decl_expr (decl);
8450 type_dependent_p = dependent_type_p (type);
8452 if (check_for_bare_parameter_packs (init))
8454 init = NULL_TREE;
8455 DECL_INITIAL (decl) = NULL_TREE;
8458 /* Generally, initializers in templates are expanded when the
8459 template is instantiated. But, if DECL is a variable constant
8460 then it can be used in future constant expressions, so its value
8461 must be available. */
8463 bool dep_init = false;
8465 if (!VAR_P (decl) || type_dependent_p)
8466 /* We can't do anything if the decl has dependent type. */;
8467 else if (!init && is_concept_var (decl))
8469 error ("variable concept has no initializer");
8470 init = boolean_true_node;
8472 else if (init
8473 && (init_const_expr_p || DECL_DECLARED_CONSTEXPR_P (decl))
8474 && !TYPE_REF_P (type)
8475 && decl_maybe_constant_var_p (decl)
8476 && !(dep_init = value_dependent_init_p (init)))
8478 /* This variable seems to be a non-dependent constant, so process
8479 its initializer. If check_initializer returns non-null the
8480 initialization wasn't constant after all. */
8481 tree init_code;
8482 cleanups = make_tree_vector ();
8483 init_code = check_initializer (decl, init, flags, &cleanups);
8484 if (init_code == NULL_TREE)
8485 init = NULL_TREE;
8486 release_tree_vector (cleanups);
8488 else
8490 gcc_assert (!DECL_PRETTY_FUNCTION_P (decl));
8491 /* Try to deduce array size. */
8492 maybe_deduce_size_from_array_init (decl, init);
8493 /* And complain about multiple initializers. */
8494 if (init && TREE_CODE (init) == TREE_LIST && TREE_CHAIN (init)
8495 && !MAYBE_CLASS_TYPE_P (type))
8496 init = build_x_compound_expr_from_list (init, ELK_INIT,
8497 tf_warning_or_error);
8500 if (init)
8501 DECL_INITIAL (decl) = init;
8503 if (dep_init)
8505 retrofit_lang_decl (decl);
8506 SET_DECL_DEPENDENT_INIT_P (decl, true);
8509 if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec)
8511 set_user_assembler_name (decl, asmspec);
8512 DECL_HARD_REGISTER (decl) = 1;
8514 return;
8517 /* Just store non-static data member initializers for later. */
8518 if (init && TREE_CODE (decl) == FIELD_DECL)
8519 DECL_INITIAL (decl) = init;
8521 /* Take care of TYPE_DECLs up front. */
8522 if (TREE_CODE (decl) == TYPE_DECL)
8524 if (type != error_mark_node
8525 && MAYBE_CLASS_TYPE_P (type) && DECL_NAME (decl))
8527 if (TREE_TYPE (DECL_NAME (decl)) && TREE_TYPE (decl) != type)
8528 warning (0, "shadowing previous type declaration of %q#D", decl);
8529 set_identifier_type_value (DECL_NAME (decl), decl);
8532 /* If we have installed this as the canonical typedef for this
8533 type, and that type has not been defined yet, delay emitting
8534 the debug information for it, as we will emit it later. */
8535 if (TYPE_MAIN_DECL (TREE_TYPE (decl)) == decl
8536 && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
8537 TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
8539 rest_of_decl_compilation (decl, DECL_FILE_SCOPE_P (decl),
8540 at_eof);
8541 return;
8544 /* A reference will be modified here, as it is initialized. */
8545 if (! DECL_EXTERNAL (decl)
8546 && TREE_READONLY (decl)
8547 && TYPE_REF_P (type))
8549 was_readonly = 1;
8550 TREE_READONLY (decl) = 0;
8553 /* This needs to happen before extend_ref_init_temps. */
8554 if (VAR_OR_FUNCTION_DECL_P (decl))
8556 if (VAR_P (decl))
8557 maybe_commonize_var (decl);
8558 determine_visibility (decl);
8561 if (VAR_P (decl))
8563 duration_kind dk = decl_storage_duration (decl);
8564 /* [dcl.constinit]/1 "The constinit specifier shall be applied
8565 only to a declaration of a variable with static or thread storage
8566 duration." */
8567 if (DECL_DECLARED_CONSTINIT_P (decl)
8568 && !(dk == dk_thread || dk == dk_static))
8570 error_at (DECL_SOURCE_LOCATION (decl),
8571 "%<constinit%> can only be applied to a variable with "
8572 "static or thread storage duration");
8573 return;
8576 /* If this is a local variable that will need a mangled name,
8577 register it now. We must do this before processing the
8578 initializer for the variable, since the initialization might
8579 require a guard variable, and since the mangled name of the
8580 guard variable will depend on the mangled name of this
8581 variable. */
8582 if (DECL_FUNCTION_SCOPE_P (decl)
8583 && TREE_STATIC (decl)
8584 && !DECL_ARTIFICIAL (decl))
8586 /* The variable holding an anonymous union will have had its
8587 discriminator set in finish_anon_union, after which it's
8588 NAME will have been cleared. */
8589 if (DECL_NAME (decl))
8590 determine_local_discriminator (decl);
8591 /* Normally has_forced_label_in_static is set during GIMPLE
8592 lowering, but [cd]tors are never actually compiled directly.
8593 We need to set this early so we can deal with the label
8594 address extension. */
8595 if ((DECL_CONSTRUCTOR_P (current_function_decl)
8596 || DECL_DESTRUCTOR_P (current_function_decl))
8597 && init)
8599 walk_tree (&init, notice_forced_label_r, NULL, NULL);
8600 add_local_decl (cfun, decl);
8602 /* And make sure it's in the symbol table for
8603 c_parse_final_cleanups to find. */
8604 varpool_node::get_create (decl);
8607 /* Convert the initializer to the type of DECL, if we have not
8608 already initialized DECL. */
8609 if (!DECL_INITIALIZED_P (decl)
8610 /* If !DECL_EXTERNAL then DECL is being defined. In the
8611 case of a static data member initialized inside the
8612 class-specifier, there can be an initializer even if DECL
8613 is *not* defined. */
8614 && (!DECL_EXTERNAL (decl) || init))
8616 cleanups = make_tree_vector ();
8617 init = check_initializer (decl, init, flags, &cleanups);
8619 /* Handle:
8621 [dcl.init]
8623 The memory occupied by any object of static storage
8624 duration is zero-initialized at program startup before
8625 any other initialization takes place.
8627 We cannot create an appropriate initializer until after
8628 the type of DECL is finalized. If DECL_INITIAL is set,
8629 then the DECL is statically initialized, and any
8630 necessary zero-initialization has already been performed. */
8631 if (TREE_STATIC (decl) && !DECL_INITIAL (decl))
8632 DECL_INITIAL (decl) = build_zero_init (TREE_TYPE (decl),
8633 /*nelts=*/NULL_TREE,
8634 /*static_storage_p=*/true);
8635 /* Remember that the initialization for this variable has
8636 taken place. */
8637 DECL_INITIALIZED_P (decl) = 1;
8638 /* This declaration is the definition of this variable,
8639 unless we are initializing a static data member within
8640 the class specifier. */
8641 if (!DECL_EXTERNAL (decl))
8642 var_definition_p = true;
8644 /* If the variable has an array type, lay out the type, even if
8645 there is no initializer. It is valid to index through the
8646 array, and we must get TYPE_ALIGN set correctly on the array
8647 type. */
8648 else if (TREE_CODE (type) == ARRAY_TYPE)
8649 layout_type (type);
8651 if (TREE_STATIC (decl)
8652 && !at_function_scope_p ()
8653 && current_function_decl == NULL)
8654 /* So decl is a global variable or a static member of a
8655 non local class. Record the types it uses
8656 so that we can decide later to emit debug info for them. */
8657 record_types_used_by_current_var_decl (decl);
8660 /* Add this declaration to the statement-tree. This needs to happen
8661 after the call to check_initializer so that the DECL_EXPR for a
8662 reference temp is added before the DECL_EXPR for the reference itself. */
8663 if (DECL_FUNCTION_SCOPE_P (decl))
8665 /* If we're building a variable sized type, and we might be
8666 reachable other than via the top of the current binding
8667 level, then create a new BIND_EXPR so that we deallocate
8668 the object at the right time. */
8669 if (VAR_P (decl)
8670 && DECL_SIZE (decl)
8671 && !TREE_CONSTANT (DECL_SIZE (decl))
8672 && STATEMENT_LIST_HAS_LABEL (cur_stmt_list))
8674 tree bind;
8675 bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL);
8676 TREE_SIDE_EFFECTS (bind) = 1;
8677 add_stmt (bind);
8678 BIND_EXPR_BODY (bind) = push_stmt_list ();
8680 add_decl_expr (decl);
8683 /* Let the middle end know about variables and functions -- but not
8684 static data members in uninstantiated class templates. */
8685 if (VAR_OR_FUNCTION_DECL_P (decl))
8687 if (VAR_P (decl))
8689 layout_var_decl (decl);
8690 if (!flag_weak)
8691 /* Check again now that we have an initializer. */
8692 maybe_commonize_var (decl);
8693 /* A class-scope constexpr variable with an out-of-class declaration.
8694 C++17 makes them implicitly inline, but still force it out. */
8695 if (DECL_INLINE_VAR_P (decl)
8696 && !DECL_VAR_DECLARED_INLINE_P (decl)
8697 && !DECL_TEMPLATE_INSTANTIATION (decl)
8698 && !in_class_decl)
8699 mark_needed (decl);
8702 if (var_definition_p
8703 /* With -fmerge-all-constants, gimplify_init_constructor
8704 might add TREE_STATIC to aggregate variables. */
8705 && (TREE_STATIC (decl)
8706 || (flag_merge_constants >= 2
8707 && AGGREGATE_TYPE_P (type))))
8709 /* If a TREE_READONLY variable needs initialization
8710 at runtime, it is no longer readonly and we need to
8711 avoid MEM_READONLY_P being set on RTL created for it. */
8712 if (init)
8714 if (TREE_READONLY (decl))
8715 TREE_READONLY (decl) = 0;
8716 was_readonly = 0;
8718 else if (was_readonly)
8719 TREE_READONLY (decl) = 1;
8721 /* Likewise if it needs destruction. */
8722 if (!decl_maybe_constant_destruction (decl, type))
8723 TREE_READONLY (decl) = 0;
8725 else if (VAR_P (decl)
8726 && CP_DECL_THREAD_LOCAL_P (decl)
8727 && (!DECL_EXTERNAL (decl) || flag_extern_tls_init)
8728 && (was_readonly || TREE_READONLY (decl))
8729 && var_needs_tls_wrapper (decl))
8731 /* TLS variables need dynamic initialization by the TLS wrapper
8732 function, we don't want to hoist accesses to it before the
8733 wrapper. */
8734 was_readonly = 0;
8735 TREE_READONLY (decl) = 0;
8738 make_rtl_for_nonlocal_decl (decl, init, asmspec);
8740 /* Check for abstractness of the type. */
8741 if (var_definition_p)
8742 abstract_virtuals_error (decl, type);
8744 if (TREE_TYPE (decl) == error_mark_node)
8745 /* No initialization required. */
8747 else if (TREE_CODE (decl) == FUNCTION_DECL)
8749 if (init)
8751 if (init == ridpointers[(int)RID_DEFAULT])
8753 /* An out-of-class default definition is defined at
8754 the point where it is explicitly defaulted. */
8755 if (DECL_DELETED_FN (decl))
8756 maybe_explain_implicit_delete (decl);
8757 else if (DECL_INITIAL (decl) == error_mark_node)
8758 synthesize_method (decl);
8760 else
8761 error_at (cp_expr_loc_or_loc (init,
8762 DECL_SOURCE_LOCATION (decl)),
8763 "function %q#D is initialized like a variable",
8764 decl);
8766 /* else no initialization required. */
8768 else if (DECL_EXTERNAL (decl)
8769 && ! (DECL_LANG_SPECIFIC (decl)
8770 && DECL_NOT_REALLY_EXTERN (decl)))
8772 /* check_initializer will have done any constant initialization. */
8774 /* A variable definition. */
8775 else if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
8776 /* Initialize the local variable. */
8777 initialize_local_var (decl, init);
8779 /* If a variable is defined, and then a subsequent
8780 definition with external linkage is encountered, we will
8781 get here twice for the same variable. We want to avoid
8782 calling expand_static_init more than once. For variables
8783 that are not static data members, we can call
8784 expand_static_init only when we actually process the
8785 initializer. It is not legal to redeclare a static data
8786 member, so this issue does not arise in that case. */
8787 else if (var_definition_p && TREE_STATIC (decl))
8788 expand_static_init (decl, init);
8791 /* If a CLEANUP_STMT was created to destroy a temporary bound to a
8792 reference, insert it in the statement-tree now. */
8793 if (cleanups)
8795 for (tree t : *cleanups)
8797 push_cleanup (NULL_TREE, t, false);
8798 /* As in initialize_local_var. */
8799 wrap_temporary_cleanups (init, t);
8801 release_tree_vector (cleanups);
8804 if (was_readonly)
8805 TREE_READONLY (decl) = 1;
8807 if (flag_openmp
8808 && VAR_P (decl)
8809 && lookup_attribute ("omp declare target implicit",
8810 DECL_ATTRIBUTES (decl)))
8812 DECL_ATTRIBUTES (decl)
8813 = remove_attribute ("omp declare target implicit",
8814 DECL_ATTRIBUTES (decl));
8815 complete_type (TREE_TYPE (decl));
8816 if (!omp_mappable_type (TREE_TYPE (decl)))
8818 error ("%q+D in declare target directive does not have mappable"
8819 " type", decl);
8820 if (TREE_TYPE (decl) != error_mark_node
8821 && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
8822 cxx_incomplete_type_inform (TREE_TYPE (decl));
8824 else if (!lookup_attribute ("omp declare target",
8825 DECL_ATTRIBUTES (decl))
8826 && !lookup_attribute ("omp declare target link",
8827 DECL_ATTRIBUTES (decl)))
8829 DECL_ATTRIBUTES (decl)
8830 = tree_cons (get_identifier ("omp declare target"),
8831 NULL_TREE, DECL_ATTRIBUTES (decl));
8832 symtab_node *node = symtab_node::get (decl);
8833 if (node != NULL)
8835 node->offloadable = 1;
8836 if (ENABLE_OFFLOADING)
8838 g->have_offload = true;
8839 if (is_a <varpool_node *> (node))
8840 vec_safe_push (offload_vars, decl);
8846 /* This is the last point we can lower alignment so give the target the
8847 chance to do so. */
8848 if (VAR_P (decl)
8849 && !is_global_var (decl)
8850 && !DECL_HARD_REGISTER (decl))
8851 targetm.lower_local_decl_alignment (decl);
8853 invoke_plugin_callbacks (PLUGIN_FINISH_DECL, decl);
8856 /* For class TYPE return itself or some its bases that contain
8857 any direct non-static data members. Return error_mark_node if an
8858 error has been diagnosed. */
8860 static tree
8861 find_decomp_class_base (location_t loc, tree type, tree ret)
8863 bool member_seen = false;
8864 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
8865 if (TREE_CODE (field) != FIELD_DECL
8866 || DECL_ARTIFICIAL (field)
8867 || DECL_UNNAMED_BIT_FIELD (field))
8868 continue;
8869 else if (ret)
8870 return type;
8871 else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
8873 if (TREE_CODE (TREE_TYPE (field)) == RECORD_TYPE)
8874 error_at (loc, "cannot decompose class type %qT because it has an "
8875 "anonymous struct member", type);
8876 else
8877 error_at (loc, "cannot decompose class type %qT because it has an "
8878 "anonymous union member", type);
8879 inform (DECL_SOURCE_LOCATION (field), "declared here");
8880 return error_mark_node;
8882 else if (!accessible_p (type, field, true))
8884 error_at (loc, "cannot decompose inaccessible member %qD of %qT",
8885 field, type);
8886 inform (DECL_SOURCE_LOCATION (field),
8887 TREE_PRIVATE (field)
8888 ? G_("declared private here")
8889 : G_("declared protected here"));
8890 return error_mark_node;
8892 else
8893 member_seen = true;
8895 tree base_binfo, binfo;
8896 tree orig_ret = ret;
8897 int i;
8898 if (member_seen)
8899 ret = type;
8900 for (binfo = TYPE_BINFO (type), i = 0;
8901 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
8903 tree t = find_decomp_class_base (loc, TREE_TYPE (base_binfo), ret);
8904 if (t == error_mark_node)
8905 return error_mark_node;
8906 if (t != NULL_TREE && t != ret)
8908 if (ret == type)
8910 error_at (loc, "cannot decompose class type %qT: both it and "
8911 "its base class %qT have non-static data members",
8912 type, t);
8913 return error_mark_node;
8915 else if (orig_ret != NULL_TREE)
8916 return t;
8917 else if (ret != NULL_TREE)
8919 error_at (loc, "cannot decompose class type %qT: its base "
8920 "classes %qT and %qT have non-static data "
8921 "members", type, ret, t);
8922 return error_mark_node;
8924 else
8925 ret = t;
8928 return ret;
8931 /* Return std::tuple_size<TYPE>::value. */
8933 static tree
8934 get_tuple_size (tree type)
8936 tree args = make_tree_vec (1);
8937 TREE_VEC_ELT (args, 0) = type;
8938 tree inst = lookup_template_class (tuple_size_identifier, args,
8939 /*in_decl*/NULL_TREE,
8940 /*context*/std_node,
8941 /*entering_scope*/false, tf_none);
8942 inst = complete_type (inst);
8943 if (inst == error_mark_node || !COMPLETE_TYPE_P (inst))
8944 return NULL_TREE;
8945 tree val = lookup_qualified_name (inst, value_identifier,
8946 LOOK_want::NORMAL, /*complain*/false);
8947 if (VAR_P (val) || TREE_CODE (val) == CONST_DECL)
8948 val = maybe_constant_value (val);
8949 if (TREE_CODE (val) == INTEGER_CST)
8950 return val;
8951 else
8952 return error_mark_node;
8955 /* Return std::tuple_element<I,TYPE>::type. */
8957 static tree
8958 get_tuple_element_type (tree type, unsigned i)
8960 tree args = make_tree_vec (2);
8961 TREE_VEC_ELT (args, 0) = build_int_cst (integer_type_node, i);
8962 TREE_VEC_ELT (args, 1) = type;
8963 tree inst = lookup_template_class (tuple_element_identifier, args,
8964 /*in_decl*/NULL_TREE,
8965 /*context*/std_node,
8966 /*entering_scope*/false,
8967 tf_warning_or_error);
8968 return make_typename_type (inst, type_identifier,
8969 none_type, tf_warning_or_error);
8972 /* Return e.get<i>() or get<i>(e). */
8974 static tree
8975 get_tuple_decomp_init (tree decl, unsigned i)
8977 tree targs = make_tree_vec (1);
8978 TREE_VEC_ELT (targs, 0) = build_int_cst (integer_type_node, i);
8980 tree etype = TREE_TYPE (decl);
8981 tree e = convert_from_reference (decl);
8983 /* [The id-expression] e is an lvalue if the type of the entity e is an
8984 lvalue reference and an xvalue otherwise. */
8985 if (!TYPE_REF_P (etype)
8986 || TYPE_REF_IS_RVALUE (etype))
8987 e = move (e);
8989 tree fns = lookup_qualified_name (TREE_TYPE (e), get__identifier,
8990 LOOK_want::NORMAL, /*complain*/false);
8991 bool use_member_get = false;
8993 /* To use a member get, member lookup must find at least one
8994 declaration that is a function template
8995 whose first template parameter is a non-type parameter. */
8996 for (lkp_iterator iter (MAYBE_BASELINK_FUNCTIONS (fns)); iter; ++iter)
8998 tree fn = *iter;
8999 if (TREE_CODE (fn) == TEMPLATE_DECL)
9001 tree tparms = DECL_TEMPLATE_PARMS (fn);
9002 tree parm = TREE_VEC_ELT (INNERMOST_TEMPLATE_PARMS (tparms), 0);
9003 if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
9005 use_member_get = true;
9006 break;
9011 if (use_member_get)
9013 fns = lookup_template_function (fns, targs);
9014 return build_new_method_call (e, fns, /*args*/NULL,
9015 /*path*/NULL_TREE, LOOKUP_NORMAL,
9016 /*fn_p*/NULL, tf_warning_or_error);
9018 else
9020 releasing_vec args (make_tree_vector_single (e));
9021 fns = lookup_template_function (get__identifier, targs);
9022 fns = perform_koenig_lookup (fns, args, tf_warning_or_error);
9023 return finish_call_expr (fns, &args, /*novirt*/false,
9024 /*koenig*/true, tf_warning_or_error);
9028 /* It's impossible to recover the decltype of a tuple decomposition variable
9029 based on the actual type of the variable, so store it in a hash table. */
9031 static GTY((cache)) decl_tree_cache_map *decomp_type_table;
9033 tree
9034 lookup_decomp_type (tree v)
9036 return *decomp_type_table->get (v);
9039 /* Mangle a decomposition declaration if needed. Arguments like
9040 in cp_finish_decomp. */
9042 void
9043 cp_maybe_mangle_decomp (tree decl, tree first, unsigned int count)
9045 if (!processing_template_decl
9046 && !error_operand_p (decl)
9047 && TREE_STATIC (decl))
9049 auto_vec<tree, 16> v;
9050 v.safe_grow (count, true);
9051 tree d = first;
9052 for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
9053 v[count - i - 1] = d;
9054 SET_DECL_ASSEMBLER_NAME (decl, mangle_decomp (decl, v));
9055 maybe_apply_pragma_weak (decl);
9059 /* Finish a decomposition declaration. DECL is the underlying declaration
9060 "e", FIRST is the head of a chain of decls for the individual identifiers
9061 chained through DECL_CHAIN in reverse order and COUNT is the number of
9062 those decls. */
9064 void
9065 cp_finish_decomp (tree decl, tree first, unsigned int count)
9067 if (error_operand_p (decl))
9069 error_out:
9070 while (count--)
9072 TREE_TYPE (first) = error_mark_node;
9073 if (DECL_HAS_VALUE_EXPR_P (first))
9075 SET_DECL_VALUE_EXPR (first, NULL_TREE);
9076 DECL_HAS_VALUE_EXPR_P (first) = 0;
9078 first = DECL_CHAIN (first);
9080 if (DECL_P (decl) && DECL_NAMESPACE_SCOPE_P (decl))
9081 SET_DECL_ASSEMBLER_NAME (decl, get_identifier ("<decomp>"));
9082 return;
9085 location_t loc = DECL_SOURCE_LOCATION (decl);
9086 if (type_dependent_expression_p (decl)
9087 /* This happens for range for when not in templates.
9088 Still add the DECL_VALUE_EXPRs for later processing. */
9089 || (!processing_template_decl
9090 && type_uses_auto (TREE_TYPE (decl))))
9092 for (unsigned int i = 0; i < count; i++)
9094 if (!DECL_HAS_VALUE_EXPR_P (first))
9096 tree v = build_nt (ARRAY_REF, decl,
9097 size_int (count - i - 1),
9098 NULL_TREE, NULL_TREE);
9099 SET_DECL_VALUE_EXPR (first, v);
9100 DECL_HAS_VALUE_EXPR_P (first) = 1;
9102 if (processing_template_decl)
9103 fit_decomposition_lang_decl (first, decl);
9104 first = DECL_CHAIN (first);
9106 return;
9109 auto_vec<tree, 16> v;
9110 v.safe_grow (count, true);
9111 tree d = first;
9112 for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
9114 v[count - i - 1] = d;
9115 fit_decomposition_lang_decl (d, decl);
9118 tree type = TREE_TYPE (decl);
9119 tree dexp = decl;
9121 if (TYPE_REF_P (type))
9123 dexp = convert_from_reference (dexp);
9124 type = complete_type (TREE_TYPE (type));
9125 if (type == error_mark_node)
9126 goto error_out;
9127 if (!COMPLETE_TYPE_P (type))
9129 error_at (loc, "structured binding refers to incomplete type %qT",
9130 type);
9131 goto error_out;
9135 tree eltype = NULL_TREE;
9136 unsigned HOST_WIDE_INT eltscnt = 0;
9137 if (TREE_CODE (type) == ARRAY_TYPE)
9139 tree nelts;
9140 nelts = array_type_nelts_top (type);
9141 if (nelts == error_mark_node)
9142 goto error_out;
9143 if (!tree_fits_uhwi_p (nelts))
9145 error_at (loc, "cannot decompose variable length array %qT", type);
9146 goto error_out;
9148 eltscnt = tree_to_uhwi (nelts);
9149 if (count != eltscnt)
9151 cnt_mismatch:
9152 if (count > eltscnt)
9153 error_n (loc, count,
9154 "%u name provided for structured binding",
9155 "%u names provided for structured binding", count);
9156 else
9157 error_n (loc, count,
9158 "only %u name provided for structured binding",
9159 "only %u names provided for structured binding", count);
9160 inform_n (loc, eltscnt,
9161 "while %qT decomposes into %wu element",
9162 "while %qT decomposes into %wu elements",
9163 type, eltscnt);
9164 goto error_out;
9166 eltype = TREE_TYPE (type);
9167 for (unsigned int i = 0; i < count; i++)
9169 TREE_TYPE (v[i]) = eltype;
9170 layout_decl (v[i], 0);
9171 if (processing_template_decl)
9172 continue;
9173 tree t = unshare_expr (dexp);
9174 t = build4 (ARRAY_REF, eltype, t, size_int (i), NULL_TREE, NULL_TREE);
9175 SET_DECL_VALUE_EXPR (v[i], t);
9176 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9179 /* 2 GNU extensions. */
9180 else if (TREE_CODE (type) == COMPLEX_TYPE)
9182 eltscnt = 2;
9183 if (count != eltscnt)
9184 goto cnt_mismatch;
9185 eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
9186 for (unsigned int i = 0; i < count; i++)
9188 TREE_TYPE (v[i]) = eltype;
9189 layout_decl (v[i], 0);
9190 if (processing_template_decl)
9191 continue;
9192 tree t = unshare_expr (dexp);
9193 t = build1 (i ? IMAGPART_EXPR : REALPART_EXPR, eltype, t);
9194 SET_DECL_VALUE_EXPR (v[i], t);
9195 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9198 else if (TREE_CODE (type) == VECTOR_TYPE)
9200 if (!TYPE_VECTOR_SUBPARTS (type).is_constant (&eltscnt))
9202 error_at (loc, "cannot decompose variable length vector %qT", type);
9203 goto error_out;
9205 if (count != eltscnt)
9206 goto cnt_mismatch;
9207 eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
9208 for (unsigned int i = 0; i < count; i++)
9210 TREE_TYPE (v[i]) = eltype;
9211 layout_decl (v[i], 0);
9212 if (processing_template_decl)
9213 continue;
9214 tree t = unshare_expr (dexp);
9215 convert_vector_to_array_for_subscript (DECL_SOURCE_LOCATION (v[i]),
9216 &t, size_int (i));
9217 t = build4 (ARRAY_REF, eltype, t, size_int (i), NULL_TREE, NULL_TREE);
9218 SET_DECL_VALUE_EXPR (v[i], t);
9219 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9222 else if (tree tsize = get_tuple_size (type))
9224 if (tsize == error_mark_node)
9226 error_at (loc, "%<std::tuple_size<%T>::value%> is not an integral "
9227 "constant expression", type);
9228 goto error_out;
9230 if (!tree_fits_uhwi_p (tsize))
9232 error_n (loc, count,
9233 "%u name provided for structured binding",
9234 "%u names provided for structured binding", count);
9235 inform (loc, "while %qT decomposes into %E elements",
9236 type, tsize);
9237 goto error_out;
9239 eltscnt = tree_to_uhwi (tsize);
9240 if (count != eltscnt)
9241 goto cnt_mismatch;
9242 int save_read = DECL_READ_P (decl);
9243 for (unsigned i = 0; i < count; ++i)
9245 location_t sloc = input_location;
9246 location_t dloc = DECL_SOURCE_LOCATION (v[i]);
9248 input_location = dloc;
9249 tree init = get_tuple_decomp_init (decl, i);
9250 tree eltype = (init == error_mark_node ? error_mark_node
9251 : get_tuple_element_type (type, i));
9252 input_location = sloc;
9254 if (VOID_TYPE_P (eltype))
9256 error ("%<std::tuple_element<%u, %T>::type%> is %<void%>",
9257 i, type);
9258 eltype = error_mark_node;
9260 if (init == error_mark_node || eltype == error_mark_node)
9262 inform (dloc, "in initialization of structured binding "
9263 "variable %qD", v[i]);
9264 goto error_out;
9266 /* Save the decltype away before reference collapse. */
9267 hash_map_safe_put<hm_ggc> (decomp_type_table, v[i], eltype);
9268 eltype = cp_build_reference_type (eltype, !lvalue_p (init));
9269 TREE_TYPE (v[i]) = eltype;
9270 layout_decl (v[i], 0);
9271 if (DECL_HAS_VALUE_EXPR_P (v[i]))
9273 /* In this case the names are variables, not just proxies. */
9274 SET_DECL_VALUE_EXPR (v[i], NULL_TREE);
9275 DECL_HAS_VALUE_EXPR_P (v[i]) = 0;
9277 if (!processing_template_decl)
9279 copy_linkage (v[i], decl);
9280 cp_finish_decl (v[i], init, /*constexpr*/false,
9281 /*asm*/NULL_TREE, LOOKUP_NORMAL);
9284 /* Ignore reads from the underlying decl performed during initialization
9285 of the individual variables. If those will be read, we'll mark
9286 the underlying decl as read at that point. */
9287 DECL_READ_P (decl) = save_read;
9289 else if (TREE_CODE (type) == UNION_TYPE)
9291 error_at (loc, "cannot decompose union type %qT", type);
9292 goto error_out;
9294 else if (!CLASS_TYPE_P (type))
9296 error_at (loc, "cannot decompose non-array non-class type %qT", type);
9297 goto error_out;
9299 else if (LAMBDA_TYPE_P (type))
9301 error_at (loc, "cannot decompose lambda closure type %qT", type);
9302 goto error_out;
9304 else if (processing_template_decl && complete_type (type) == error_mark_node)
9305 goto error_out;
9306 else if (processing_template_decl && !COMPLETE_TYPE_P (type))
9307 pedwarn (loc, 0, "structured binding refers to incomplete class type %qT",
9308 type);
9309 else
9311 tree btype = find_decomp_class_base (loc, type, NULL_TREE);
9312 if (btype == error_mark_node)
9313 goto error_out;
9314 else if (btype == NULL_TREE)
9316 error_at (loc, "cannot decompose class type %qT without non-static "
9317 "data members", type);
9318 goto error_out;
9320 for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
9321 if (TREE_CODE (field) != FIELD_DECL
9322 || DECL_ARTIFICIAL (field)
9323 || DECL_UNNAMED_BIT_FIELD (field))
9324 continue;
9325 else
9326 eltscnt++;
9327 if (count != eltscnt)
9328 goto cnt_mismatch;
9329 tree t = dexp;
9330 if (type != btype)
9332 t = convert_to_base (t, btype, /*check_access*/true,
9333 /*nonnull*/false, tf_warning_or_error);
9334 type = btype;
9336 unsigned int i = 0;
9337 for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
9338 if (TREE_CODE (field) != FIELD_DECL
9339 || DECL_ARTIFICIAL (field)
9340 || DECL_UNNAMED_BIT_FIELD (field))
9341 continue;
9342 else
9344 tree tt = finish_non_static_data_member (field, unshare_expr (t),
9345 NULL_TREE);
9346 if (REFERENCE_REF_P (tt))
9347 tt = TREE_OPERAND (tt, 0);
9348 TREE_TYPE (v[i]) = TREE_TYPE (tt);
9349 layout_decl (v[i], 0);
9350 if (!processing_template_decl)
9352 SET_DECL_VALUE_EXPR (v[i], tt);
9353 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9355 i++;
9358 if (processing_template_decl)
9360 for (unsigned int i = 0; i < count; i++)
9361 if (!DECL_HAS_VALUE_EXPR_P (v[i]))
9363 tree a = build_nt (ARRAY_REF, decl, size_int (i),
9364 NULL_TREE, NULL_TREE);
9365 SET_DECL_VALUE_EXPR (v[i], a);
9366 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9371 /* Returns a declaration for a VAR_DECL as if:
9373 extern "C" TYPE NAME;
9375 had been seen. Used to create compiler-generated global
9376 variables. */
9378 static tree
9379 declare_global_var (tree name, tree type)
9381 auto cookie = push_abi_namespace (global_namespace);
9382 tree decl = build_decl (input_location, VAR_DECL, name, type);
9383 TREE_PUBLIC (decl) = 1;
9384 DECL_EXTERNAL (decl) = 1;
9385 DECL_ARTIFICIAL (decl) = 1;
9386 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
9387 /* If the user has explicitly declared this variable (perhaps
9388 because the code we are compiling is part of a low-level runtime
9389 library), then it is possible that our declaration will be merged
9390 with theirs by pushdecl. */
9391 decl = pushdecl (decl);
9392 cp_finish_decl (decl, NULL_TREE, false, NULL_TREE, 0);
9393 pop_abi_namespace (cookie, global_namespace);
9395 return decl;
9398 /* Returns the type for the argument to "__cxa_atexit" (or "atexit",
9399 if "__cxa_atexit" is not being used) corresponding to the function
9400 to be called when the program exits. */
9402 static tree
9403 get_atexit_fn_ptr_type (void)
9405 tree fn_type;
9407 if (!atexit_fn_ptr_type_node)
9409 tree arg_type;
9410 if (flag_use_cxa_atexit
9411 && !targetm.cxx.use_atexit_for_cxa_atexit ())
9412 /* The parameter to "__cxa_atexit" is "void (*)(void *)". */
9413 arg_type = ptr_type_node;
9414 else
9415 /* The parameter to "atexit" is "void (*)(void)". */
9416 arg_type = NULL_TREE;
9418 fn_type = build_function_type_list (void_type_node,
9419 arg_type, NULL_TREE);
9420 atexit_fn_ptr_type_node = build_pointer_type (fn_type);
9423 return atexit_fn_ptr_type_node;
9426 /* Returns a pointer to the `atexit' function. Note that if
9427 FLAG_USE_CXA_ATEXIT is nonzero, then this will actually be the new
9428 `__cxa_atexit' function specified in the IA64 C++ ABI. */
9430 static tree
9431 get_atexit_node (void)
9433 tree atexit_fndecl;
9434 tree fn_type;
9435 tree fn_ptr_type;
9436 const char *name;
9437 bool use_aeabi_atexit;
9438 tree ctx = global_namespace;
9440 if (atexit_node)
9441 return atexit_node;
9443 if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
9445 /* The declaration for `__cxa_atexit' is:
9447 int __cxa_atexit (void (*)(void *), void *, void *)
9449 We build up the argument types and then the function type
9450 itself. */
9451 tree argtype0, argtype1, argtype2;
9453 use_aeabi_atexit = targetm.cxx.use_aeabi_atexit ();
9454 /* First, build the pointer-to-function type for the first
9455 argument. */
9456 fn_ptr_type = get_atexit_fn_ptr_type ();
9457 /* Then, build the rest of the argument types. */
9458 argtype2 = ptr_type_node;
9459 if (use_aeabi_atexit)
9461 argtype1 = fn_ptr_type;
9462 argtype0 = ptr_type_node;
9464 else
9466 argtype1 = ptr_type_node;
9467 argtype0 = fn_ptr_type;
9469 /* And the final __cxa_atexit type. */
9470 fn_type = build_function_type_list (integer_type_node,
9471 argtype0, argtype1, argtype2,
9472 NULL_TREE);
9473 /* ... which needs noexcept. */
9474 fn_type = build_exception_variant (fn_type, noexcept_true_spec);
9475 if (use_aeabi_atexit)
9477 name = "__aeabi_atexit";
9478 push_to_top_level ();
9479 int n = push_namespace (get_identifier ("__aeabiv1"), false);
9480 ctx = current_namespace;
9481 while (n--)
9482 pop_namespace ();
9483 pop_from_top_level ();
9485 else
9487 name = "__cxa_atexit";
9488 ctx = abi_node;
9491 else
9493 /* The declaration for `atexit' is:
9495 int atexit (void (*)());
9497 We build up the argument types and then the function type
9498 itself. */
9499 fn_ptr_type = get_atexit_fn_ptr_type ();
9500 /* Build the final atexit type. */
9501 fn_type = build_function_type_list (integer_type_node,
9502 fn_ptr_type, NULL_TREE);
9503 /* ... which needs noexcept. */
9504 fn_type = build_exception_variant (fn_type, noexcept_true_spec);
9505 name = "atexit";
9508 /* Now, build the function declaration. */
9509 push_lang_context (lang_name_c);
9510 auto cookie = push_abi_namespace (ctx);
9511 atexit_fndecl = build_library_fn_ptr (name, fn_type, ECF_LEAF | ECF_NOTHROW);
9512 DECL_CONTEXT (atexit_fndecl) = FROB_CONTEXT (current_namespace);
9513 /* Install as hidden builtin so we're (a) more relaxed about
9514 exception spec matching and (b) will not give a confusing location
9515 in diagnostic and (c) won't magically appear in user-visible name
9516 lookups. */
9517 DECL_SOURCE_LOCATION (atexit_fndecl) = BUILTINS_LOCATION;
9518 atexit_fndecl = pushdecl (atexit_fndecl, /*hiding=*/true);
9519 pop_abi_namespace (cookie, ctx);
9520 mark_used (atexit_fndecl);
9521 pop_lang_context ();
9522 atexit_node = decay_conversion (atexit_fndecl, tf_warning_or_error);
9524 return atexit_node;
9527 /* Like get_atexit_node, but for thread-local cleanups. */
9529 static tree
9530 get_thread_atexit_node (void)
9532 /* The declaration for `__cxa_thread_atexit' is:
9534 int __cxa_thread_atexit (void (*)(void *), void *, void *) */
9535 tree fn_type = build_function_type_list (integer_type_node,
9536 get_atexit_fn_ptr_type (),
9537 ptr_type_node, ptr_type_node,
9538 NULL_TREE);
9540 /* Now, build the function declaration. */
9541 tree atexit_fndecl = build_library_fn_ptr ("__cxa_thread_atexit", fn_type,
9542 ECF_LEAF | ECF_NOTHROW);
9543 return decay_conversion (atexit_fndecl, tf_warning_or_error);
9546 /* Returns the __dso_handle VAR_DECL. */
9548 static tree
9549 get_dso_handle_node (void)
9551 if (dso_handle_node)
9552 return dso_handle_node;
9554 /* Declare the variable. */
9555 dso_handle_node = declare_global_var (get_identifier ("__dso_handle"),
9556 ptr_type_node);
9558 #ifdef HAVE_GAS_HIDDEN
9559 if (dso_handle_node != error_mark_node)
9561 DECL_VISIBILITY (dso_handle_node) = VISIBILITY_HIDDEN;
9562 DECL_VISIBILITY_SPECIFIED (dso_handle_node) = 1;
9564 #endif
9566 return dso_handle_node;
9569 /* Begin a new function with internal linkage whose job will be simply
9570 to destroy some particular variable. */
9572 static GTY(()) int start_cleanup_cnt;
9574 static tree
9575 start_cleanup_fn (void)
9577 char name[32];
9579 push_to_top_level ();
9581 /* No need to mangle this. */
9582 push_lang_context (lang_name_c);
9584 /* Build the name of the function. */
9585 sprintf (name, "__tcf_%d", start_cleanup_cnt++);
9586 /* Build the function declaration. */
9587 tree fntype = TREE_TYPE (get_atexit_fn_ptr_type ());
9588 tree fndecl = build_lang_decl (FUNCTION_DECL, get_identifier (name), fntype);
9589 DECL_CONTEXT (fndecl) = FROB_CONTEXT (current_namespace);
9590 /* It's a function with internal linkage, generated by the
9591 compiler. */
9592 TREE_PUBLIC (fndecl) = 0;
9593 DECL_ARTIFICIAL (fndecl) = 1;
9594 /* Make the function `inline' so that it is only emitted if it is
9595 actually needed. It is unlikely that it will be inlined, since
9596 it is only called via a function pointer, but we avoid unnecessary
9597 emissions this way. */
9598 DECL_DECLARED_INLINE_P (fndecl) = 1;
9599 DECL_INTERFACE_KNOWN (fndecl) = 1;
9600 if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
9602 /* Build the parameter. */
9603 tree parmdecl = cp_build_parm_decl (fndecl, NULL_TREE, ptr_type_node);
9604 TREE_USED (parmdecl) = 1;
9605 DECL_READ_P (parmdecl) = 1;
9606 DECL_ARGUMENTS (fndecl) = parmdecl;
9609 fndecl = pushdecl (fndecl, /*hidden=*/true);
9610 start_preparsed_function (fndecl, NULL_TREE, SF_PRE_PARSED);
9612 pop_lang_context ();
9614 return current_function_decl;
9617 /* Finish the cleanup function begun by start_cleanup_fn. */
9619 static void
9620 end_cleanup_fn (void)
9622 expand_or_defer_fn (finish_function (/*inline_p=*/false));
9624 pop_from_top_level ();
9627 /* Generate code to handle the destruction of DECL, an object with
9628 static storage duration. */
9630 tree
9631 register_dtor_fn (tree decl)
9633 tree cleanup;
9634 tree addr;
9635 tree compound_stmt;
9636 tree fcall;
9637 tree type;
9638 bool ob_parm, dso_parm, use_dtor;
9639 tree arg0, arg1, arg2;
9640 tree atex_node;
9642 type = TREE_TYPE (decl);
9643 if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
9644 return void_node;
9646 if (decl_maybe_constant_destruction (decl, type)
9647 && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
9649 cxx_maybe_build_cleanup (decl, tf_warning_or_error);
9650 return void_node;
9653 /* If we're using "__cxa_atexit" (or "__cxa_thread_atexit" or
9654 "__aeabi_atexit"), and DECL is a class object, we can just pass the
9655 destructor to "__cxa_atexit"; we don't have to build a temporary
9656 function to do the cleanup. */
9657 dso_parm = (flag_use_cxa_atexit
9658 && !targetm.cxx.use_atexit_for_cxa_atexit ());
9659 ob_parm = (CP_DECL_THREAD_LOCAL_P (decl) || dso_parm);
9660 use_dtor = ob_parm && CLASS_TYPE_P (type);
9661 if (use_dtor)
9663 cleanup = get_class_binding (type, complete_dtor_identifier);
9665 /* Make sure it is accessible. */
9666 perform_or_defer_access_check (TYPE_BINFO (type), cleanup, cleanup,
9667 tf_warning_or_error);
9669 else
9671 /* Call build_cleanup before we enter the anonymous function so
9672 that any access checks will be done relative to the current
9673 scope, rather than the scope of the anonymous function. */
9674 build_cleanup (decl);
9676 /* Now start the function. */
9677 cleanup = start_cleanup_fn ();
9679 /* Now, recompute the cleanup. It may contain SAVE_EXPRs that refer
9680 to the original function, rather than the anonymous one. That
9681 will make the back end think that nested functions are in use,
9682 which causes confusion. */
9683 push_deferring_access_checks (dk_no_check);
9684 fcall = build_cleanup (decl);
9685 pop_deferring_access_checks ();
9687 /* Create the body of the anonymous function. */
9688 compound_stmt = begin_compound_stmt (BCS_FN_BODY);
9689 finish_expr_stmt (fcall);
9690 finish_compound_stmt (compound_stmt);
9691 end_cleanup_fn ();
9694 /* Call atexit with the cleanup function. */
9695 mark_used (cleanup);
9696 cleanup = build_address (cleanup);
9698 if (CP_DECL_THREAD_LOCAL_P (decl))
9699 atex_node = get_thread_atexit_node ();
9700 else
9701 atex_node = get_atexit_node ();
9703 if (use_dtor)
9705 /* We must convert CLEANUP to the type that "__cxa_atexit"
9706 expects. */
9707 cleanup = build_nop (get_atexit_fn_ptr_type (), cleanup);
9708 /* "__cxa_atexit" will pass the address of DECL to the
9709 cleanup function. */
9710 mark_used (decl);
9711 addr = build_address (decl);
9712 /* The declared type of the parameter to "__cxa_atexit" is
9713 "void *". For plain "T*", we could just let the
9714 machinery in cp_build_function_call convert it -- but if the
9715 type is "cv-qualified T *", then we need to convert it
9716 before passing it in, to avoid spurious errors. */
9717 addr = build_nop (ptr_type_node, addr);
9719 else
9720 /* Since the cleanup functions we build ignore the address
9721 they're given, there's no reason to pass the actual address
9722 in, and, in general, it's cheaper to pass NULL than any
9723 other value. */
9724 addr = null_pointer_node;
9726 if (dso_parm)
9727 arg2 = cp_build_addr_expr (get_dso_handle_node (),
9728 tf_warning_or_error);
9729 else if (ob_parm)
9730 /* Just pass NULL to the dso handle parm if we don't actually
9731 have a DSO handle on this target. */
9732 arg2 = null_pointer_node;
9733 else
9734 arg2 = NULL_TREE;
9736 if (ob_parm)
9738 if (!CP_DECL_THREAD_LOCAL_P (decl)
9739 && targetm.cxx.use_aeabi_atexit ())
9741 arg1 = cleanup;
9742 arg0 = addr;
9744 else
9746 arg1 = addr;
9747 arg0 = cleanup;
9750 else
9752 arg0 = cleanup;
9753 arg1 = NULL_TREE;
9755 return cp_build_function_call_nary (atex_node, tf_warning_or_error,
9756 arg0, arg1, arg2, NULL_TREE);
9759 /* DECL is a VAR_DECL with static storage duration. INIT, if present,
9760 is its initializer. Generate code to handle the construction
9761 and destruction of DECL. */
9763 static void
9764 expand_static_init (tree decl, tree init)
9766 gcc_assert (VAR_P (decl));
9767 gcc_assert (TREE_STATIC (decl));
9769 /* Some variables require no dynamic initialization. */
9770 if (decl_maybe_constant_destruction (decl, TREE_TYPE (decl)))
9772 /* Make sure the destructor is callable. */
9773 cxx_maybe_build_cleanup (decl, tf_warning_or_error);
9774 if (!init)
9775 return;
9778 if (CP_DECL_THREAD_LOCAL_P (decl) && DECL_GNU_TLS_P (decl)
9779 && !DECL_FUNCTION_SCOPE_P (decl))
9781 location_t dloc = DECL_SOURCE_LOCATION (decl);
9782 if (init)
9783 error_at (dloc, "non-local variable %qD declared %<__thread%> "
9784 "needs dynamic initialization", decl);
9785 else
9786 error_at (dloc, "non-local variable %qD declared %<__thread%> "
9787 "has a non-trivial destructor", decl);
9788 static bool informed;
9789 if (!informed)
9791 inform (dloc, "C++11 %<thread_local%> allows dynamic "
9792 "initialization and destruction");
9793 informed = true;
9795 return;
9798 if (DECL_FUNCTION_SCOPE_P (decl))
9800 /* Emit code to perform this initialization but once. */
9801 tree if_stmt = NULL_TREE, inner_if_stmt = NULL_TREE;
9802 tree then_clause = NULL_TREE, inner_then_clause = NULL_TREE;
9803 tree guard, guard_addr;
9804 tree flag, begin;
9805 /* We don't need thread-safety code for thread-local vars. */
9806 bool thread_guard = (flag_threadsafe_statics
9807 && !CP_DECL_THREAD_LOCAL_P (decl));
9809 /* Emit code to perform this initialization but once. This code
9810 looks like:
9812 static <type> guard;
9813 if (!__atomic_load (guard.first_byte)) {
9814 if (__cxa_guard_acquire (&guard)) {
9815 bool flag = false;
9816 try {
9817 // Do initialization.
9818 flag = true; __cxa_guard_release (&guard);
9819 // Register variable for destruction at end of program.
9820 } catch {
9821 if (!flag) __cxa_guard_abort (&guard);
9826 Note that the `flag' variable is only set to 1 *after* the
9827 initialization is complete. This ensures that an exception,
9828 thrown during the construction, will cause the variable to
9829 reinitialized when we pass through this code again, as per:
9831 [stmt.dcl]
9833 If the initialization exits by throwing an exception, the
9834 initialization is not complete, so it will be tried again
9835 the next time control enters the declaration.
9837 This process should be thread-safe, too; multiple threads
9838 should not be able to initialize the variable more than
9839 once. */
9841 /* Create the guard variable. */
9842 guard = get_guard (decl);
9844 /* Begin the conditional initialization. */
9845 if_stmt = begin_if_stmt ();
9847 finish_if_stmt_cond (get_guard_cond (guard, thread_guard), if_stmt);
9848 then_clause = begin_compound_stmt (BCS_NO_SCOPE);
9850 if (thread_guard)
9852 tree vfntype = NULL_TREE;
9853 tree acquire_name, release_name, abort_name;
9854 tree acquire_fn, release_fn, abort_fn;
9855 guard_addr = build_address (guard);
9857 acquire_name = get_identifier ("__cxa_guard_acquire");
9858 release_name = get_identifier ("__cxa_guard_release");
9859 abort_name = get_identifier ("__cxa_guard_abort");
9860 acquire_fn = get_global_binding (acquire_name);
9861 release_fn = get_global_binding (release_name);
9862 abort_fn = get_global_binding (abort_name);
9863 if (!acquire_fn)
9864 acquire_fn = push_library_fn
9865 (acquire_name, build_function_type_list (integer_type_node,
9866 TREE_TYPE (guard_addr),
9867 NULL_TREE),
9868 NULL_TREE, ECF_NOTHROW);
9869 if (!release_fn || !abort_fn)
9870 vfntype = build_function_type_list (void_type_node,
9871 TREE_TYPE (guard_addr),
9872 NULL_TREE);
9873 if (!release_fn)
9874 release_fn = push_library_fn (release_name, vfntype, NULL_TREE,
9875 ECF_NOTHROW);
9876 if (!abort_fn)
9877 abort_fn = push_library_fn (abort_name, vfntype, NULL_TREE,
9878 ECF_NOTHROW | ECF_LEAF);
9880 inner_if_stmt = begin_if_stmt ();
9881 finish_if_stmt_cond (build_call_n (acquire_fn, 1, guard_addr),
9882 inner_if_stmt);
9884 inner_then_clause = begin_compound_stmt (BCS_NO_SCOPE);
9885 begin = get_target_expr (boolean_false_node);
9886 flag = TARGET_EXPR_SLOT (begin);
9888 TARGET_EXPR_CLEANUP (begin)
9889 = build3 (COND_EXPR, void_type_node, flag,
9890 void_node,
9891 build_call_n (abort_fn, 1, guard_addr));
9892 CLEANUP_EH_ONLY (begin) = 1;
9894 /* Do the initialization itself. */
9895 init = add_stmt_to_compound (begin, init);
9896 init = add_stmt_to_compound (init,
9897 build2 (MODIFY_EXPR, void_type_node,
9898 flag, boolean_true_node));
9900 /* Use atexit to register a function for destroying this static
9901 variable. Do this before calling __cxa_guard_release. */
9902 init = add_stmt_to_compound (init, register_dtor_fn (decl));
9904 init = add_stmt_to_compound (init, build_call_n (release_fn, 1,
9905 guard_addr));
9907 else
9909 init = add_stmt_to_compound (init, set_guard (guard));
9911 /* Use atexit to register a function for destroying this static
9912 variable. */
9913 init = add_stmt_to_compound (init, register_dtor_fn (decl));
9916 finish_expr_stmt (init);
9918 if (thread_guard)
9920 finish_compound_stmt (inner_then_clause);
9921 finish_then_clause (inner_if_stmt);
9922 finish_if_stmt (inner_if_stmt);
9925 finish_compound_stmt (then_clause);
9926 finish_then_clause (if_stmt);
9927 finish_if_stmt (if_stmt);
9929 else if (CP_DECL_THREAD_LOCAL_P (decl))
9930 tls_aggregates = tree_cons (init, decl, tls_aggregates);
9931 else
9932 static_aggregates = tree_cons (init, decl, static_aggregates);
9936 /* Make TYPE a complete type based on INITIAL_VALUE.
9937 Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
9938 2 if there was no information (in which case assume 0 if DO_DEFAULT),
9939 3 if the initializer list is empty (in pedantic mode). */
9942 cp_complete_array_type (tree *ptype, tree initial_value, bool do_default)
9944 int failure;
9945 tree type, elt_type;
9947 /* Don't get confused by a CONSTRUCTOR for some other type. */
9948 if (initial_value && TREE_CODE (initial_value) == CONSTRUCTOR
9949 && !BRACE_ENCLOSED_INITIALIZER_P (initial_value)
9950 && TREE_CODE (TREE_TYPE (initial_value)) != ARRAY_TYPE)
9951 return 1;
9953 if (initial_value)
9955 /* An array of character type can be initialized from a
9956 brace-enclosed string constant so call reshape_init to
9957 remove the optional braces from a braced string literal. */
9958 if (char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (*ptype)))
9959 && BRACE_ENCLOSED_INITIALIZER_P (initial_value))
9960 initial_value = reshape_init (*ptype, initial_value,
9961 tf_warning_or_error);
9963 /* If any of the elements are parameter packs, we can't actually
9964 complete this type now because the array size is dependent. */
9965 if (TREE_CODE (initial_value) == CONSTRUCTOR)
9966 for (auto &e: CONSTRUCTOR_ELTS (initial_value))
9967 if (PACK_EXPANSION_P (e.value))
9968 return 0;
9971 failure = complete_array_type (ptype, initial_value, do_default);
9973 /* We can create the array before the element type is complete, which
9974 means that we didn't have these two bits set in the original type
9975 either. In completing the type, we are expected to propagate these
9976 bits. See also complete_type which does the same thing for arrays
9977 of fixed size. */
9978 type = *ptype;
9979 if (type != error_mark_node && TYPE_DOMAIN (type))
9981 elt_type = TREE_TYPE (type);
9982 TYPE_NEEDS_CONSTRUCTING (type) = TYPE_NEEDS_CONSTRUCTING (elt_type);
9983 TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
9984 = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (elt_type);
9987 return failure;
9990 /* As above, but either give an error or reject zero-size arrays, depending
9991 on COMPLAIN. */
9994 cp_complete_array_type_or_error (tree *ptype, tree initial_value,
9995 bool do_default, tsubst_flags_t complain)
9997 int failure;
9998 bool sfinae = !(complain & tf_error);
9999 /* In SFINAE context we can't be lenient about zero-size arrays. */
10000 if (sfinae)
10001 ++pedantic;
10002 failure = cp_complete_array_type (ptype, initial_value, do_default);
10003 if (sfinae)
10004 --pedantic;
10005 if (failure)
10007 if (sfinae)
10008 /* Not an error. */;
10009 else if (failure == 1)
10010 error ("initializer fails to determine size of %qT", *ptype);
10011 else if (failure == 2)
10013 if (do_default)
10014 error ("array size missing in %qT", *ptype);
10016 else if (failure == 3)
10017 error ("zero-size array %qT", *ptype);
10018 *ptype = error_mark_node;
10020 return failure;
10023 /* Return zero if something is declared to be a member of type
10024 CTYPE when in the context of CUR_TYPE. STRING is the error
10025 message to print in that case. Otherwise, quietly return 1. */
10027 static int
10028 member_function_or_else (tree ctype, tree cur_type, enum overload_flags flags)
10030 if (ctype && ctype != cur_type)
10032 if (flags == DTOR_FLAG)
10033 error ("destructor for alien class %qT cannot be a member", ctype);
10034 else
10035 error ("constructor for alien class %qT cannot be a member", ctype);
10036 return 0;
10038 return 1;
10041 /* Subroutine of `grokdeclarator'. */
10043 /* Generate errors possibly applicable for a given set of specifiers.
10044 This is for ARM $7.1.2. */
10046 static void
10047 bad_specifiers (tree object,
10048 enum bad_spec_place type,
10049 int virtualp,
10050 int quals,
10051 int inlinep,
10052 int friendp,
10053 int raises,
10054 const location_t* locations)
10056 switch (type)
10058 case BSP_VAR:
10059 if (virtualp)
10060 error_at (locations[ds_virtual],
10061 "%qD declared as a %<virtual%> variable", object);
10062 if (quals)
10063 error ("%<const%> and %<volatile%> function specifiers on "
10064 "%qD invalid in variable declaration", object);
10065 break;
10066 case BSP_PARM:
10067 if (virtualp)
10068 error_at (locations[ds_virtual],
10069 "%qD declared as a %<virtual%> parameter", object);
10070 if (inlinep)
10071 error_at (locations[ds_inline],
10072 "%qD declared as an %<inline%> parameter", object);
10073 if (quals)
10074 error ("%<const%> and %<volatile%> function specifiers on "
10075 "%qD invalid in parameter declaration", object);
10076 break;
10077 case BSP_TYPE:
10078 if (virtualp)
10079 error_at (locations[ds_virtual],
10080 "%qD declared as a %<virtual%> type", object);
10081 if (inlinep)
10082 error_at (locations[ds_inline],
10083 "%qD declared as an %<inline%> type", object);
10084 if (quals)
10085 error ("%<const%> and %<volatile%> function specifiers on "
10086 "%qD invalid in type declaration", object);
10087 break;
10088 case BSP_FIELD:
10089 if (virtualp)
10090 error_at (locations[ds_virtual],
10091 "%qD declared as a %<virtual%> field", object);
10092 if (inlinep)
10093 error_at (locations[ds_inline],
10094 "%qD declared as an %<inline%> field", object);
10095 if (quals)
10096 error ("%<const%> and %<volatile%> function specifiers on "
10097 "%qD invalid in field declaration", object);
10098 break;
10099 default:
10100 gcc_unreachable();
10102 if (friendp)
10103 error ("%q+D declared as a friend", object);
10104 if (raises
10105 && !flag_noexcept_type
10106 && (TREE_CODE (object) == TYPE_DECL
10107 || (!TYPE_PTRFN_P (TREE_TYPE (object))
10108 && !TYPE_REFFN_P (TREE_TYPE (object))
10109 && !TYPE_PTRMEMFUNC_P (TREE_TYPE (object)))))
10110 error ("%q+D declared with an exception specification", object);
10113 /* DECL is a member function or static data member and is presently
10114 being defined. Check that the definition is taking place in a
10115 valid namespace. */
10117 static void
10118 check_class_member_definition_namespace (tree decl)
10120 /* These checks only apply to member functions and static data
10121 members. */
10122 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
10123 /* We check for problems with specializations in pt.cc in
10124 check_specialization_namespace, where we can issue better
10125 diagnostics. */
10126 if (processing_specialization)
10127 return;
10128 /* We check this in check_explicit_instantiation_namespace. */
10129 if (processing_explicit_instantiation)
10130 return;
10131 /* [class.mfct]
10133 A member function definition that appears outside of the
10134 class definition shall appear in a namespace scope enclosing
10135 the class definition.
10137 [class.static.data]
10139 The definition for a static data member shall appear in a
10140 namespace scope enclosing the member's class definition. */
10141 if (!is_ancestor (current_namespace, DECL_CONTEXT (decl)))
10142 permerror (input_location, "definition of %qD is not in namespace enclosing %qT",
10143 decl, DECL_CONTEXT (decl));
10146 /* Build a PARM_DECL for the "this" parameter of FN. TYPE is the
10147 METHOD_TYPE for a non-static member function; QUALS are the
10148 cv-qualifiers that apply to the function. */
10150 tree
10151 build_this_parm (tree fn, tree type, cp_cv_quals quals)
10153 tree this_type;
10154 tree qual_type;
10155 tree parm;
10156 cp_cv_quals this_quals;
10158 if (CLASS_TYPE_P (type))
10160 this_type
10161 = cp_build_qualified_type (type, quals & ~TYPE_QUAL_RESTRICT);
10162 this_type = build_pointer_type (this_type);
10164 else
10165 this_type = type_of_this_parm (type);
10166 /* The `this' parameter is implicitly `const'; it cannot be
10167 assigned to. */
10168 this_quals = (quals & TYPE_QUAL_RESTRICT) | TYPE_QUAL_CONST;
10169 qual_type = cp_build_qualified_type (this_type, this_quals);
10170 parm = build_artificial_parm (fn, this_identifier, qual_type);
10171 cp_apply_type_quals_to_decl (this_quals, parm);
10172 return parm;
10175 /* DECL is a static member function. Complain if it was declared
10176 with function-cv-quals. */
10178 static void
10179 check_static_quals (tree decl, cp_cv_quals quals)
10181 if (quals != TYPE_UNQUALIFIED)
10182 error ("static member function %q#D declared with type qualifiers",
10183 decl);
10186 // Check that FN takes no arguments and returns bool.
10187 static void
10188 check_concept_fn (tree fn)
10190 // A constraint is nullary.
10191 if (DECL_ARGUMENTS (fn))
10192 error_at (DECL_SOURCE_LOCATION (fn),
10193 "concept %q#D declared with function parameters", fn);
10195 // The declared return type of the concept shall be bool, and
10196 // it shall not be deduced from it definition.
10197 tree type = TREE_TYPE (TREE_TYPE (fn));
10198 if (is_auto (type))
10199 error_at (DECL_SOURCE_LOCATION (fn),
10200 "concept %q#D declared with a deduced return type", fn);
10201 else if (type != boolean_type_node)
10202 error_at (DECL_SOURCE_LOCATION (fn),
10203 "concept %q#D with non-%<bool%> return type %qT", fn, type);
10206 /* Helper function. Replace the temporary this parameter injected
10207 during cp_finish_omp_declare_simd with the real this parameter. */
10209 static tree
10210 declare_simd_adjust_this (tree *tp, int *walk_subtrees, void *data)
10212 tree this_parm = (tree) data;
10213 if (TREE_CODE (*tp) == PARM_DECL
10214 && DECL_NAME (*tp) == this_identifier
10215 && *tp != this_parm)
10216 *tp = this_parm;
10217 else if (TYPE_P (*tp))
10218 *walk_subtrees = 0;
10219 return NULL_TREE;
10222 /* CTYPE is class type, or null if non-class.
10223 TYPE is type this FUNCTION_DECL should have, either FUNCTION_TYPE
10224 or METHOD_TYPE.
10225 DECLARATOR is the function's name.
10226 PARMS is a chain of PARM_DECLs for the function.
10227 VIRTUALP is truthvalue of whether the function is virtual or not.
10228 FLAGS are to be passed through to `grokclassfn'.
10229 QUALS are qualifiers indicating whether the function is `const'
10230 or `volatile'.
10231 RAISES is a list of exceptions that this function can raise.
10232 CHECK is 1 if we must find this method in CTYPE, 0 if we should
10233 not look, and -1 if we should not call `grokclassfn' at all.
10235 SFK is the kind of special function (if any) for the new function.
10237 Returns `NULL_TREE' if something goes wrong, after issuing
10238 applicable error messages. */
10240 static tree
10241 grokfndecl (tree ctype,
10242 tree type,
10243 tree declarator,
10244 tree parms,
10245 tree orig_declarator,
10246 const cp_decl_specifier_seq *declspecs,
10247 tree decl_reqs,
10248 int virtualp,
10249 enum overload_flags flags,
10250 cp_cv_quals quals,
10251 cp_ref_qualifier rqual,
10252 tree raises,
10253 int check,
10254 int friendp,
10255 int publicp,
10256 int inlinep,
10257 bool deletedp,
10258 special_function_kind sfk,
10259 bool funcdef_flag,
10260 bool late_return_type_p,
10261 int template_count,
10262 tree in_namespace,
10263 tree* attrlist,
10264 location_t location)
10266 tree decl;
10267 int staticp = ctype && TREE_CODE (type) == FUNCTION_TYPE;
10268 tree t;
10270 if (location == UNKNOWN_LOCATION)
10271 location = input_location;
10273 /* Was the concept specifier present? */
10274 bool concept_p = inlinep & 4;
10276 /* Concept declarations must have a corresponding definition. */
10277 if (concept_p && !funcdef_flag)
10279 error_at (location, "concept %qD has no definition", declarator);
10280 return NULL_TREE;
10283 type = build_cp_fntype_variant (type, rqual, raises, late_return_type_p);
10285 decl = build_lang_decl_loc (location, FUNCTION_DECL, declarator, type);
10287 /* Set the constraints on the declaration. */
10288 if (flag_concepts)
10290 tree tmpl_reqs = NULL_TREE;
10291 tree ctx = friendp ? current_class_type : ctype;
10292 bool block_local = TREE_CODE (current_scope ()) == FUNCTION_DECL;
10293 bool memtmpl = (!block_local
10294 && (current_template_depth
10295 > template_class_depth (ctx)));
10296 if (memtmpl)
10298 if (!current_template_parms)
10299 /* If there are no template parameters, something must have
10300 gone wrong. */
10301 gcc_assert (seen_error ());
10302 else
10303 tmpl_reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
10305 tree ci = build_constraints (tmpl_reqs, decl_reqs);
10306 if (concept_p && ci)
10308 error_at (location, "a function concept cannot be constrained");
10309 ci = NULL_TREE;
10311 /* C++20 CA378: Remove non-templated constrained functions. */
10312 if (ci
10313 && (block_local
10314 || (!flag_concepts_ts
10315 && (!processing_template_decl
10316 || (friendp && !memtmpl && !funcdef_flag)))))
10318 error_at (location, "constraints on a non-templated function");
10319 ci = NULL_TREE;
10321 set_constraints (decl, ci);
10324 if (TREE_CODE (type) == METHOD_TYPE)
10326 tree parm = build_this_parm (decl, type, quals);
10327 DECL_CHAIN (parm) = parms;
10328 parms = parm;
10330 /* Allocate space to hold the vptr bit if needed. */
10331 SET_DECL_ALIGN (decl, MINIMUM_METHOD_BOUNDARY);
10334 DECL_ARGUMENTS (decl) = parms;
10335 for (t = parms; t; t = DECL_CHAIN (t))
10336 DECL_CONTEXT (t) = decl;
10338 /* Propagate volatile out from type to decl. */
10339 if (TYPE_VOLATILE (type))
10340 TREE_THIS_VOLATILE (decl) = 1;
10342 /* Setup decl according to sfk. */
10343 switch (sfk)
10345 case sfk_constructor:
10346 case sfk_copy_constructor:
10347 case sfk_move_constructor:
10348 DECL_CXX_CONSTRUCTOR_P (decl) = 1;
10349 DECL_NAME (decl) = ctor_identifier;
10350 break;
10351 case sfk_destructor:
10352 DECL_CXX_DESTRUCTOR_P (decl) = 1;
10353 DECL_NAME (decl) = dtor_identifier;
10354 break;
10355 default:
10356 break;
10359 if (friendp && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)
10361 if (funcdef_flag)
10362 error_at (location,
10363 "defining explicit specialization %qD in friend declaration",
10364 orig_declarator);
10365 else
10367 tree fns = TREE_OPERAND (orig_declarator, 0);
10368 tree args = TREE_OPERAND (orig_declarator, 1);
10370 if (PROCESSING_REAL_TEMPLATE_DECL_P ())
10372 /* Something like `template <class T> friend void f<T>()'. */
10373 error_at (location,
10374 "invalid use of template-id %qD in declaration "
10375 "of primary template",
10376 orig_declarator);
10377 return NULL_TREE;
10380 /* A friend declaration of the form friend void f<>(). Record
10381 the information in the TEMPLATE_ID_EXPR. */
10382 SET_DECL_IMPLICIT_INSTANTIATION (decl);
10384 gcc_assert (identifier_p (fns) || OVL_P (fns));
10385 DECL_TEMPLATE_INFO (decl) = build_template_info (fns, args);
10387 for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
10388 if (TREE_PURPOSE (t)
10389 && TREE_CODE (TREE_PURPOSE (t)) == DEFERRED_PARSE)
10391 error_at (defparse_location (TREE_PURPOSE (t)),
10392 "default arguments are not allowed in declaration "
10393 "of friend template specialization %qD",
10394 decl);
10395 return NULL_TREE;
10398 if (inlinep & 1)
10400 error_at (declspecs->locations[ds_inline],
10401 "%<inline%> is not allowed in declaration of friend "
10402 "template specialization %qD",
10403 decl);
10404 return NULL_TREE;
10409 /* C++17 11.3.6/4: "If a friend declaration specifies a default argument
10410 expression, that declaration shall be a definition..." */
10411 if (friendp && !funcdef_flag)
10413 for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
10414 t && t != void_list_node; t = TREE_CHAIN (t))
10415 if (TREE_PURPOSE (t))
10417 permerror (DECL_SOURCE_LOCATION (decl),
10418 "friend declaration of %qD specifies default "
10419 "arguments and isn%'t a definition", decl);
10420 break;
10424 /* If this decl has namespace scope, set that up. */
10425 if (in_namespace)
10426 set_decl_namespace (decl, in_namespace, friendp);
10427 else if (ctype)
10428 DECL_CONTEXT (decl) = ctype;
10429 else
10430 DECL_CONTEXT (decl) = FROB_CONTEXT (current_decl_namespace ());
10432 /* `main' and builtins have implicit 'C' linkage. */
10433 if (ctype == NULL_TREE
10434 && DECL_FILE_SCOPE_P (decl)
10435 && current_lang_name == lang_name_cplusplus
10436 && (MAIN_NAME_P (declarator)
10437 || (IDENTIFIER_LENGTH (declarator) > 10
10438 && IDENTIFIER_POINTER (declarator)[0] == '_'
10439 && IDENTIFIER_POINTER (declarator)[1] == '_'
10440 && startswith (IDENTIFIER_POINTER (declarator) + 2,
10441 "builtin_"))
10442 || (targetcm.cxx_implicit_extern_c
10443 && (targetcm.cxx_implicit_extern_c
10444 (IDENTIFIER_POINTER (declarator))))))
10445 SET_DECL_LANGUAGE (decl, lang_c);
10447 /* Should probably propagate const out from type to decl I bet (mrs). */
10448 if (staticp)
10450 DECL_STATIC_FUNCTION_P (decl) = 1;
10451 DECL_CONTEXT (decl) = ctype;
10454 if (deletedp)
10455 DECL_DELETED_FN (decl) = 1;
10457 if (ctype && funcdef_flag)
10458 check_class_member_definition_namespace (decl);
10460 if (ctype == NULL_TREE && DECL_MAIN_P (decl))
10462 if (PROCESSING_REAL_TEMPLATE_DECL_P())
10463 error_at (location, "cannot declare %<::main%> to be a template");
10464 if (inlinep & 1)
10465 error_at (declspecs->locations[ds_inline],
10466 "cannot declare %<::main%> to be inline");
10467 if (inlinep & 2)
10468 error_at (declspecs->locations[ds_constexpr],
10469 "cannot declare %<::main%> to be %qs", "constexpr");
10470 if (inlinep & 8)
10471 error_at (declspecs->locations[ds_consteval],
10472 "cannot declare %<::main%> to be %qs", "consteval");
10473 if (!publicp)
10474 error_at (location, "cannot declare %<::main%> to be static");
10475 inlinep = 0;
10476 publicp = 1;
10479 /* Members of anonymous types and local classes have no linkage; make
10480 them internal. If a typedef is made later, this will be changed. */
10481 if (ctype && (!TREE_PUBLIC (TYPE_MAIN_DECL (ctype))
10482 || decl_function_context (TYPE_MAIN_DECL (ctype))))
10483 publicp = 0;
10485 if (publicp && cxx_dialect == cxx98)
10487 /* [basic.link]: A name with no linkage (notably, the name of a class
10488 or enumeration declared in a local scope) shall not be used to
10489 declare an entity with linkage.
10491 DR 757 relaxes this restriction for C++0x. */
10492 no_linkage_error (decl);
10495 TREE_PUBLIC (decl) = publicp;
10496 if (! publicp)
10498 DECL_INTERFACE_KNOWN (decl) = 1;
10499 DECL_NOT_REALLY_EXTERN (decl) = 1;
10502 /* If the declaration was declared inline, mark it as such. */
10503 if (inlinep)
10505 DECL_DECLARED_INLINE_P (decl) = 1;
10506 if (publicp)
10507 DECL_COMDAT (decl) = 1;
10509 if (inlinep & 2)
10510 DECL_DECLARED_CONSTEXPR_P (decl) = true;
10511 else if (inlinep & 8)
10513 DECL_DECLARED_CONSTEXPR_P (decl) = true;
10514 SET_DECL_IMMEDIATE_FUNCTION_P (decl);
10517 // If the concept declaration specifier was found, check
10518 // that the declaration satisfies the necessary requirements.
10519 if (concept_p)
10521 DECL_DECLARED_CONCEPT_P (decl) = true;
10522 check_concept_fn (decl);
10525 DECL_EXTERNAL (decl) = 1;
10526 if (TREE_CODE (type) == FUNCTION_TYPE)
10528 if (quals || rqual)
10529 TREE_TYPE (decl) = apply_memfn_quals (TREE_TYPE (decl),
10530 TYPE_UNQUALIFIED,
10531 REF_QUAL_NONE);
10533 if (quals)
10535 error (ctype
10536 ? G_("static member function %qD cannot have cv-qualifier")
10537 : G_("non-member function %qD cannot have cv-qualifier"),
10538 decl);
10539 quals = TYPE_UNQUALIFIED;
10542 if (rqual)
10544 error (ctype
10545 ? G_("static member function %qD cannot have ref-qualifier")
10546 : G_("non-member function %qD cannot have ref-qualifier"),
10547 decl);
10548 rqual = REF_QUAL_NONE;
10552 if (deduction_guide_p (decl))
10554 tree type = TREE_TYPE (DECL_NAME (decl));
10555 if (in_namespace == NULL_TREE
10556 && CP_DECL_CONTEXT (decl) != CP_TYPE_CONTEXT (type))
10558 error_at (location, "deduction guide %qD must be declared in the "
10559 "same scope as %qT", decl, type);
10560 inform (location_of (type), " declared here");
10561 return NULL_TREE;
10563 if (DECL_CLASS_SCOPE_P (decl)
10564 && current_access_specifier != declared_access (TYPE_NAME (type)))
10566 error_at (location, "deduction guide %qD must have the same access "
10567 "as %qT", decl, type);
10568 inform (location_of (type), " declared here");
10570 if (funcdef_flag)
10571 error_at (location,
10572 "deduction guide %qD must not have a function body", decl);
10574 else if (IDENTIFIER_ANY_OP_P (DECL_NAME (decl))
10575 && !grok_op_properties (decl, /*complain=*/true))
10576 return NULL_TREE;
10577 else if (UDLIT_OPER_P (DECL_NAME (decl)))
10579 bool long_long_unsigned_p;
10580 bool long_double_p;
10581 const char *suffix = NULL;
10582 /* [over.literal]/6: Literal operators shall not have C linkage. */
10583 if (DECL_LANGUAGE (decl) == lang_c)
10585 error_at (location, "literal operator with C linkage");
10586 maybe_show_extern_c_location ();
10587 return NULL_TREE;
10590 if (DECL_NAMESPACE_SCOPE_P (decl))
10592 if (!check_literal_operator_args (decl, &long_long_unsigned_p,
10593 &long_double_p))
10595 error_at (location, "%qD has invalid argument list", decl);
10596 return NULL_TREE;
10599 suffix = UDLIT_OP_SUFFIX (DECL_NAME (decl));
10600 if (long_long_unsigned_p)
10602 if (cpp_interpret_int_suffix (parse_in, suffix, strlen (suffix)))
10603 warning_at (location, 0, "integer suffix %qs"
10604 " shadowed by implementation", suffix);
10606 else if (long_double_p)
10608 if (cpp_interpret_float_suffix (parse_in, suffix, strlen (suffix)))
10609 warning_at (location, 0, "floating-point suffix %qs"
10610 " shadowed by implementation", suffix);
10612 /* 17.6.3.3.5 */
10613 if (suffix[0] != '_'
10614 && !current_function_decl && !(friendp && !funcdef_flag))
10615 warning_at (location, OPT_Wliteral_suffix,
10616 "literal operator suffixes not preceded by %<_%>"
10617 " are reserved for future standardization");
10619 else
10621 error_at (location, "%qD must be a non-member function", decl);
10622 return NULL_TREE;
10626 if (funcdef_flag)
10627 /* Make the init_value nonzero so pushdecl knows this is not
10628 tentative. error_mark_node is replaced later with the BLOCK. */
10629 DECL_INITIAL (decl) = error_mark_node;
10631 if (TYPE_NOTHROW_P (type) || nothrow_libfn_p (decl))
10632 TREE_NOTHROW (decl) = 1;
10634 if (flag_openmp || flag_openmp_simd)
10636 /* Adjust "omp declare simd" attributes. */
10637 tree ods = lookup_attribute ("omp declare simd", *attrlist);
10638 if (ods)
10640 tree attr;
10641 for (attr = ods; attr;
10642 attr = lookup_attribute ("omp declare simd", TREE_CHAIN (attr)))
10644 if (TREE_CODE (type) == METHOD_TYPE)
10645 walk_tree (&TREE_VALUE (attr), declare_simd_adjust_this,
10646 DECL_ARGUMENTS (decl), NULL);
10647 if (TREE_VALUE (attr) != NULL_TREE)
10649 tree cl = TREE_VALUE (TREE_VALUE (attr));
10650 cl = c_omp_declare_simd_clauses_to_numbers
10651 (DECL_ARGUMENTS (decl), cl);
10652 if (cl)
10653 TREE_VALUE (TREE_VALUE (attr)) = cl;
10654 else
10655 TREE_VALUE (attr) = NULL_TREE;
10661 /* Caller will do the rest of this. */
10662 if (check < 0)
10663 return decl;
10665 if (ctype != NULL_TREE)
10666 grokclassfn (ctype, decl, flags);
10668 /* 12.4/3 */
10669 if (cxx_dialect >= cxx11
10670 && DECL_DESTRUCTOR_P (decl)
10671 && !TYPE_BEING_DEFINED (DECL_CONTEXT (decl))
10672 && !processing_template_decl)
10673 deduce_noexcept_on_destructor (decl);
10675 set_originating_module (decl);
10677 decl = check_explicit_specialization (orig_declarator, decl,
10678 template_count,
10679 2 * funcdef_flag +
10680 4 * (friendp != 0) +
10681 8 * concept_p,
10682 *attrlist);
10683 if (decl == error_mark_node)
10684 return NULL_TREE;
10686 if (DECL_STATIC_FUNCTION_P (decl))
10687 check_static_quals (decl, quals);
10689 if (attrlist)
10691 cplus_decl_attributes (&decl, *attrlist, 0);
10692 *attrlist = NULL_TREE;
10695 if (DECL_HAS_CONTRACTS_P (decl))
10696 rebuild_postconditions (decl);
10698 /* Check main's type after attributes have been applied. */
10699 if (ctype == NULL_TREE && DECL_MAIN_P (decl))
10701 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
10702 integer_type_node))
10704 tree oldtypeargs = TYPE_ARG_TYPES (TREE_TYPE (decl));
10705 tree newtype;
10706 error_at (declspecs->locations[ds_type_spec],
10707 "%<::main%> must return %<int%>");
10708 newtype = build_function_type (integer_type_node, oldtypeargs);
10709 TREE_TYPE (decl) = newtype;
10711 if (warn_main)
10712 check_main_parameter_types (decl);
10715 if (ctype != NULL_TREE && check)
10717 tree old_decl = check_classfn (ctype, decl,
10718 (current_template_depth
10719 > template_class_depth (ctype))
10720 ? current_template_parms
10721 : NULL_TREE);
10723 if (old_decl == error_mark_node)
10724 return NULL_TREE;
10726 if (old_decl)
10728 tree ok;
10729 tree pushed_scope;
10731 if (TREE_CODE (old_decl) == TEMPLATE_DECL)
10732 /* Because grokfndecl is always supposed to return a
10733 FUNCTION_DECL, we pull out the DECL_TEMPLATE_RESULT
10734 here. We depend on our callers to figure out that its
10735 really a template that's being returned. */
10736 old_decl = DECL_TEMPLATE_RESULT (old_decl);
10738 if (DECL_STATIC_FUNCTION_P (old_decl)
10739 && TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
10741 /* Remove the `this' parm added by grokclassfn. */
10742 revert_static_member_fn (decl);
10743 check_static_quals (decl, quals);
10745 if (DECL_ARTIFICIAL (old_decl))
10747 error ("definition of implicitly-declared %qD", old_decl);
10748 return NULL_TREE;
10750 else if (DECL_DEFAULTED_FN (old_decl))
10752 error ("definition of explicitly-defaulted %q+D", decl);
10753 inform (DECL_SOURCE_LOCATION (old_decl),
10754 "%q#D explicitly defaulted here", old_decl);
10755 return NULL_TREE;
10758 /* Since we've smashed OLD_DECL to its
10759 DECL_TEMPLATE_RESULT, we must do the same to DECL. */
10760 if (TREE_CODE (decl) == TEMPLATE_DECL)
10761 decl = DECL_TEMPLATE_RESULT (decl);
10763 /* Attempt to merge the declarations. This can fail, in
10764 the case of some invalid specialization declarations. */
10765 pushed_scope = push_scope (ctype);
10766 ok = duplicate_decls (decl, old_decl);
10767 if (pushed_scope)
10768 pop_scope (pushed_scope);
10769 if (!ok)
10771 error ("no %q#D member function declared in class %qT",
10772 decl, ctype);
10773 return NULL_TREE;
10775 if (ok == error_mark_node)
10776 return NULL_TREE;
10777 return old_decl;
10781 if (DECL_CONSTRUCTOR_P (decl) && !grok_ctor_properties (ctype, decl))
10782 return NULL_TREE;
10784 if (ctype == NULL_TREE || check)
10785 return decl;
10787 if (virtualp)
10788 DECL_VIRTUAL_P (decl) = 1;
10790 return decl;
10793 /* decl is a FUNCTION_DECL.
10794 specifiers are the parsed virt-specifiers.
10796 Set flags to reflect the virt-specifiers.
10798 Returns decl. */
10800 static tree
10801 set_virt_specifiers (tree decl, cp_virt_specifiers specifiers)
10803 if (decl == NULL_TREE)
10804 return decl;
10805 if (specifiers & VIRT_SPEC_OVERRIDE)
10806 DECL_OVERRIDE_P (decl) = 1;
10807 if (specifiers & VIRT_SPEC_FINAL)
10808 DECL_FINAL_P (decl) = 1;
10809 return decl;
10812 /* DECL is a VAR_DECL for a static data member. Set flags to reflect
10813 the linkage that DECL will receive in the object file. */
10815 static void
10816 set_linkage_for_static_data_member (tree decl)
10818 /* A static data member always has static storage duration and
10819 external linkage. Note that static data members are forbidden in
10820 local classes -- the only situation in which a class has
10821 non-external linkage. */
10822 TREE_PUBLIC (decl) = 1;
10823 TREE_STATIC (decl) = 1;
10824 /* For non-template classes, static data members are always put
10825 out in exactly those files where they are defined, just as
10826 with ordinary namespace-scope variables. */
10827 if (!processing_template_decl)
10828 DECL_INTERFACE_KNOWN (decl) = 1;
10831 /* Create a VAR_DECL named NAME with the indicated TYPE.
10833 If SCOPE is non-NULL, it is the class type or namespace containing
10834 the variable. If SCOPE is NULL, the variable should is created in
10835 the innermost enclosing scope. */
10837 static tree
10838 grokvardecl (tree type,
10839 tree name,
10840 tree orig_declarator,
10841 const cp_decl_specifier_seq *declspecs,
10842 int initialized,
10843 int type_quals,
10844 int inlinep,
10845 bool conceptp,
10846 int template_count,
10847 tree scope,
10848 location_t location)
10850 tree decl;
10851 tree explicit_scope;
10853 gcc_assert (!name || identifier_p (name));
10855 bool constp = (type_quals & TYPE_QUAL_CONST) != 0;
10856 bool volatilep = (type_quals & TYPE_QUAL_VOLATILE) != 0;
10858 /* Compute the scope in which to place the variable, but remember
10859 whether or not that scope was explicitly specified by the user. */
10860 explicit_scope = scope;
10861 if (!scope)
10863 /* An explicit "extern" specifier indicates a namespace-scope
10864 variable. */
10865 if (declspecs->storage_class == sc_extern)
10866 scope = current_decl_namespace ();
10867 else if (!at_function_scope_p ())
10868 scope = current_scope ();
10871 if (scope
10872 && (/* If the variable is a namespace-scope variable declared in a
10873 template, we need DECL_LANG_SPECIFIC. */
10874 (TREE_CODE (scope) == NAMESPACE_DECL && processing_template_decl)
10875 /* Similarly for namespace-scope variables with language linkage
10876 other than C++. */
10877 || (TREE_CODE (scope) == NAMESPACE_DECL
10878 && current_lang_name != lang_name_cplusplus)
10879 /* Similarly for static data members. */
10880 || TYPE_P (scope)
10881 /* Similarly for explicit specializations. */
10882 || (orig_declarator
10883 && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)))
10884 decl = build_lang_decl_loc (location, VAR_DECL, name, type);
10885 else
10886 decl = build_decl (location, VAR_DECL, name, type);
10888 if (explicit_scope && TREE_CODE (explicit_scope) == NAMESPACE_DECL)
10889 set_decl_namespace (decl, explicit_scope, 0);
10890 else
10891 DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
10893 if (declspecs->storage_class == sc_extern)
10895 DECL_THIS_EXTERN (decl) = 1;
10896 DECL_EXTERNAL (decl) = !initialized;
10899 if (DECL_CLASS_SCOPE_P (decl))
10901 set_linkage_for_static_data_member (decl);
10902 /* This function is only called with out-of-class definitions. */
10903 DECL_EXTERNAL (decl) = 0;
10904 check_class_member_definition_namespace (decl);
10906 /* At top level, either `static' or no s.c. makes a definition
10907 (perhaps tentative), and absence of `static' makes it public. */
10908 else if (toplevel_bindings_p ())
10910 TREE_PUBLIC (decl) = (declspecs->storage_class != sc_static
10911 && (DECL_THIS_EXTERN (decl)
10912 || ! constp
10913 || volatilep
10914 || inlinep));
10915 TREE_STATIC (decl) = ! DECL_EXTERNAL (decl);
10917 /* Not at top level, only `static' makes a static definition. */
10918 else
10920 TREE_STATIC (decl) = declspecs->storage_class == sc_static;
10921 TREE_PUBLIC (decl) = DECL_EXTERNAL (decl);
10924 set_originating_module (decl);
10926 if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
10928 if (DECL_EXTERNAL (decl) || TREE_STATIC (decl))
10930 CP_DECL_THREAD_LOCAL_P (decl) = true;
10931 if (!processing_template_decl)
10932 set_decl_tls_model (decl, decl_default_tls_model (decl));
10934 if (declspecs->gnu_thread_keyword_p)
10935 SET_DECL_GNU_TLS_P (decl);
10938 /* If the type of the decl has no linkage, make sure that we'll
10939 notice that in mark_used. */
10940 if (cxx_dialect > cxx98
10941 && decl_linkage (decl) != lk_none
10942 && DECL_LANG_SPECIFIC (decl) == NULL
10943 && !DECL_EXTERN_C_P (decl)
10944 && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
10945 retrofit_lang_decl (decl);
10947 if (TREE_PUBLIC (decl))
10949 /* [basic.link]: A name with no linkage (notably, the name of a class
10950 or enumeration declared in a local scope) shall not be used to
10951 declare an entity with linkage.
10953 DR 757 relaxes this restriction for C++0x. */
10954 if (cxx_dialect < cxx11)
10955 no_linkage_error (decl);
10957 else
10958 DECL_INTERFACE_KNOWN (decl) = 1;
10960 if (DECL_NAME (decl)
10961 && MAIN_NAME_P (DECL_NAME (decl))
10962 && scope == global_namespace)
10963 error_at (DECL_SOURCE_LOCATION (decl),
10964 "cannot declare %<::main%> to be a global variable");
10966 /* Check that the variable can be safely declared as a concept.
10967 Note that this also forbids explicit specializations. */
10968 if (conceptp)
10970 if (!processing_template_decl)
10972 error_at (declspecs->locations[ds_concept],
10973 "a non-template variable cannot be %<concept%>");
10974 return NULL_TREE;
10976 else if (!at_namespace_scope_p ())
10978 error_at (declspecs->locations[ds_concept],
10979 "concept must be defined at namespace scope");
10980 return NULL_TREE;
10982 else
10983 DECL_DECLARED_CONCEPT_P (decl) = true;
10984 if (!same_type_ignoring_top_level_qualifiers_p (type, boolean_type_node))
10985 error_at (declspecs->locations[ds_type_spec],
10986 "concept must have type %<bool%>");
10987 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
10989 error_at (location, "a variable concept cannot be constrained");
10990 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
10993 else if (flag_concepts
10994 && current_template_depth > template_class_depth (scope))
10996 tree ci = current_template_constraints ();
10997 set_constraints (decl, ci);
11000 // Handle explicit specializations and instantiations of variable templates.
11001 if (orig_declarator)
11002 decl = check_explicit_specialization (orig_declarator, decl,
11003 template_count, conceptp * 8);
11005 return decl != error_mark_node ? decl : NULL_TREE;
11008 /* Create and return a canonical pointer to member function type, for
11009 TYPE, which is a POINTER_TYPE to a METHOD_TYPE. */
11011 tree
11012 build_ptrmemfunc_type (tree type)
11014 tree field, fields;
11015 tree t;
11017 if (type == error_mark_node)
11018 return type;
11020 /* Make sure that we always have the unqualified pointer-to-member
11021 type first. */
11022 if (cp_cv_quals quals = cp_type_quals (type))
11024 tree unqual = build_ptrmemfunc_type (TYPE_MAIN_VARIANT (type));
11025 return cp_build_qualified_type (unqual, quals);
11028 /* If a canonical type already exists for this type, use it. We use
11029 this method instead of type_hash_canon, because it only does a
11030 simple equality check on the list of field members. */
11032 t = TYPE_PTRMEMFUNC_TYPE (type);
11033 if (t)
11034 return t;
11036 t = make_node (RECORD_TYPE);
11038 /* Let the front end know this is a pointer to member function. */
11039 TYPE_PTRMEMFUNC_FLAG (t) = 1;
11041 field = build_decl (input_location, FIELD_DECL, pfn_identifier, type);
11042 DECL_NONADDRESSABLE_P (field) = 1;
11043 fields = field;
11045 field = build_decl (input_location, FIELD_DECL, delta_identifier,
11046 delta_type_node);
11047 DECL_NONADDRESSABLE_P (field) = 1;
11048 DECL_CHAIN (field) = fields;
11049 fields = field;
11051 finish_builtin_struct (t, "__ptrmemfunc_type", fields, ptr_type_node);
11053 /* Zap out the name so that the back end will give us the debugging
11054 information for this anonymous RECORD_TYPE. */
11055 TYPE_NAME (t) = NULL_TREE;
11057 /* Cache this pointer-to-member type so that we can find it again
11058 later. */
11059 TYPE_PTRMEMFUNC_TYPE (type) = t;
11061 if (TYPE_STRUCTURAL_EQUALITY_P (type))
11062 SET_TYPE_STRUCTURAL_EQUALITY (t);
11063 else if (TYPE_CANONICAL (type) != type)
11064 TYPE_CANONICAL (t) = build_ptrmemfunc_type (TYPE_CANONICAL (type));
11066 return t;
11069 /* Create and return a pointer to data member type. */
11071 tree
11072 build_ptrmem_type (tree class_type, tree member_type)
11074 if (TREE_CODE (member_type) == METHOD_TYPE)
11076 cp_cv_quals quals = type_memfn_quals (member_type);
11077 cp_ref_qualifier rqual = type_memfn_rqual (member_type);
11078 member_type = build_memfn_type (member_type, class_type, quals, rqual);
11079 return build_ptrmemfunc_type (build_pointer_type (member_type));
11081 else
11083 gcc_assert (TREE_CODE (member_type) != FUNCTION_TYPE);
11084 return build_offset_type (class_type, member_type);
11088 /* DECL is a VAR_DECL defined in-class, whose TYPE is also given.
11089 Check to see that the definition is valid. Issue appropriate error
11090 messages. */
11092 static void
11093 check_static_variable_definition (tree decl, tree type)
11095 /* Avoid redundant diagnostics on out-of-class definitions. */
11096 if (!current_class_type || !TYPE_BEING_DEFINED (current_class_type))
11098 /* Can't check yet if we don't know the type. */
11099 else if (dependent_type_p (type))
11101 /* If DECL is declared constexpr, we'll do the appropriate checks
11102 in check_initializer. Similarly for inline static data members. */
11103 else if (DECL_P (decl)
11104 && (DECL_DECLARED_CONSTEXPR_P (decl)
11105 || DECL_VAR_DECLARED_INLINE_P (decl)))
11107 else if (cxx_dialect >= cxx11 && !INTEGRAL_OR_ENUMERATION_TYPE_P (type))
11109 if (!COMPLETE_TYPE_P (type))
11110 error_at (DECL_SOURCE_LOCATION (decl),
11111 "in-class initialization of static data member %q#D of "
11112 "incomplete type", decl);
11113 else if (literal_type_p (type))
11114 permerror (DECL_SOURCE_LOCATION (decl),
11115 "%<constexpr%> needed for in-class initialization of "
11116 "static data member %q#D of non-integral type", decl);
11117 else
11118 error_at (DECL_SOURCE_LOCATION (decl),
11119 "in-class initialization of static data member %q#D of "
11120 "non-literal type", decl);
11122 /* Motion 10 at San Diego: If a static const integral data member is
11123 initialized with an integral constant expression, the initializer
11124 may appear either in the declaration (within the class), or in
11125 the definition, but not both. If it appears in the class, the
11126 member is a member constant. The file-scope definition is always
11127 required. */
11128 else if (!ARITHMETIC_TYPE_P (type) && TREE_CODE (type) != ENUMERAL_TYPE)
11129 error_at (DECL_SOURCE_LOCATION (decl),
11130 "invalid in-class initialization of static data member "
11131 "of non-integral type %qT",
11132 type);
11133 else if (!CP_TYPE_CONST_P (type))
11134 error_at (DECL_SOURCE_LOCATION (decl),
11135 "ISO C++ forbids in-class initialization of non-const "
11136 "static member %qD",
11137 decl);
11138 else if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type))
11139 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
11140 "ISO C++ forbids initialization of member constant "
11141 "%qD of non-integral type %qT", decl, type);
11144 /* *expr_p is part of the TYPE_SIZE of a variably-sized array. If any
11145 SAVE_EXPRs in *expr_p wrap expressions with side-effects, break those
11146 expressions out into temporary variables so that walk_tree doesn't
11147 step into them (c++/15764). */
11149 static tree
11150 stabilize_save_expr_r (tree *expr_p, int *walk_subtrees, void *data)
11152 hash_set<tree> *pset = (hash_set<tree> *)data;
11153 tree expr = *expr_p;
11154 if (TREE_CODE (expr) == SAVE_EXPR)
11156 tree op = TREE_OPERAND (expr, 0);
11157 cp_walk_tree (&op, stabilize_save_expr_r, data, pset);
11158 if (TREE_SIDE_EFFECTS (op))
11159 TREE_OPERAND (expr, 0) = get_temp_regvar (TREE_TYPE (op), op);
11160 *walk_subtrees = 0;
11162 else if (!EXPR_P (expr) || !TREE_SIDE_EFFECTS (expr))
11163 *walk_subtrees = 0;
11164 return NULL;
11167 /* Entry point for the above. */
11169 static void
11170 stabilize_vla_size (tree size)
11172 hash_set<tree> pset;
11173 /* Break out any function calls into temporary variables. */
11174 cp_walk_tree (&size, stabilize_save_expr_r, &pset, &pset);
11177 /* Reduce a SIZEOF_EXPR to its value. */
11179 tree
11180 fold_sizeof_expr (tree t)
11182 tree r;
11183 if (SIZEOF_EXPR_TYPE_P (t))
11184 r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
11185 TREE_TYPE (TREE_OPERAND (t, 0)),
11186 SIZEOF_EXPR, false, false);
11187 else if (TYPE_P (TREE_OPERAND (t, 0)))
11188 r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
11189 TREE_OPERAND (t, 0), SIZEOF_EXPR,
11190 false, false);
11191 else
11192 r = cxx_sizeof_or_alignof_expr (EXPR_LOCATION (t),
11193 TREE_OPERAND (t, 0), SIZEOF_EXPR,
11194 false, false);
11195 if (r == error_mark_node)
11196 r = size_one_node;
11197 return r;
11200 /* Given the SIZE (i.e., number of elements) in an array, compute
11201 an appropriate index type for the array. If non-NULL, NAME is
11202 the name of the entity being declared. */
11204 static tree
11205 compute_array_index_type_loc (location_t name_loc, tree name, tree size,
11206 tsubst_flags_t complain)
11208 if (error_operand_p (size))
11209 return error_mark_node;
11211 /* The type of the index being computed. */
11212 tree itype;
11214 /* The original numeric size as seen in the source code before
11215 conversion to size_t. */
11216 tree origsize = size;
11218 location_t loc = cp_expr_loc_or_loc (size, name ? name_loc : input_location);
11220 if (!type_dependent_expression_p (size))
11222 origsize = size = mark_rvalue_use (size);
11224 if (cxx_dialect < cxx11 && TREE_CODE (size) == NOP_EXPR
11225 && TREE_SIDE_EFFECTS (size))
11226 /* In C++98, we mark a non-constant array bound with a magic
11227 NOP_EXPR with TREE_SIDE_EFFECTS; don't fold in that case. */;
11228 else
11230 size = build_converted_constant_expr (size_type_node, size, complain);
11231 /* Pedantically a constant expression is required here and so
11232 __builtin_is_constant_evaluated () should fold to true if it
11233 is successfully folded into a constant. */
11234 size = fold_non_dependent_expr (size, complain,
11235 /*manifestly_const_eval=*/true);
11237 if (!TREE_CONSTANT (size))
11238 size = origsize;
11241 if (error_operand_p (size))
11242 return error_mark_node;
11244 /* The array bound must be an integer type. */
11245 tree type = TREE_TYPE (size);
11246 if (!INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
11248 if (!(complain & tf_error))
11249 return error_mark_node;
11250 if (name)
11251 error_at (loc, "size of array %qD has non-integral type %qT",
11252 name, type);
11253 else
11254 error_at (loc, "size of array has non-integral type %qT", type);
11255 size = integer_one_node;
11259 /* A type is dependent if it is...an array type constructed from any
11260 dependent type or whose size is specified by a constant expression
11261 that is value-dependent. */
11262 /* We can only call value_dependent_expression_p on integral constant
11263 expressions. */
11264 if (processing_template_decl
11265 && potential_constant_expression (size)
11266 && value_dependent_expression_p (size))
11268 /* Just build the index type and mark that it requires
11269 structural equality checks. */
11270 in_template:
11271 itype = build_index_type (build_min (MINUS_EXPR, sizetype,
11272 size, size_one_node));
11273 TYPE_DEPENDENT_P (itype) = 1;
11274 TYPE_DEPENDENT_P_VALID (itype) = 1;
11275 SET_TYPE_STRUCTURAL_EQUALITY (itype);
11276 return itype;
11279 if (TREE_CODE (size) != INTEGER_CST)
11281 tree folded = cp_fully_fold (size);
11282 if (TREE_CODE (folded) == INTEGER_CST)
11284 if (name)
11285 pedwarn (loc, OPT_Wpedantic, "size of array %qD is not an "
11286 "integral constant-expression", name);
11287 else
11288 pedwarn (loc, OPT_Wpedantic,
11289 "size of array is not an integral constant-expression");
11291 if (TREE_CONSTANT (size) && !TREE_CONSTANT (folded))
11292 /* We might have lost the TREE_CONSTANT flag e.g. when we are
11293 folding a conversion from a pointer to integral type. In that
11294 case issue an error below and don't treat this as a VLA. */;
11295 else
11296 /* Use the folded result for VLAs, too; it will have resolved
11297 SIZEOF_EXPR. */
11298 size = folded;
11301 /* Normally, the array-bound will be a constant. */
11302 if (TREE_CODE (size) == INTEGER_CST)
11304 /* The size to use in diagnostics that reflects the constant
11305 size used in the source, rather than SIZE massaged above. */
11306 tree diagsize = size;
11308 /* If the original size before conversion to size_t was signed
11309 and negative, convert it to ssizetype to restore the sign. */
11310 if (!TYPE_UNSIGNED (TREE_TYPE (origsize))
11311 && TREE_CODE (size) == INTEGER_CST
11312 && tree_int_cst_sign_bit (size))
11314 diagsize = fold_convert (ssizetype, size);
11316 /* Clear the overflow bit that may have been set as a result
11317 of the conversion from the sizetype of the new size to
11318 ssizetype. */
11319 TREE_OVERFLOW (diagsize) = false;
11322 /* Verify that the array has a positive number of elements
11323 and issue the appropriate diagnostic if it doesn't. */
11324 if (!valid_array_size_p (loc, diagsize, name, (complain & tf_error)))
11326 if (!(complain & tf_error))
11327 return error_mark_node;
11328 size = integer_one_node;
11330 /* As an extension we allow zero-sized arrays. */
11331 else if (integer_zerop (size))
11333 if (!(complain & tf_error))
11334 /* We must fail if performing argument deduction (as
11335 indicated by the state of complain), so that
11336 another substitution can be found. */
11337 return error_mark_node;
11338 else if (name)
11339 pedwarn (loc, OPT_Wpedantic,
11340 "ISO C++ forbids zero-size array %qD", name);
11341 else
11342 pedwarn (loc, OPT_Wpedantic,
11343 "ISO C++ forbids zero-size array");
11346 else if (TREE_CONSTANT (size)
11347 /* We don't allow VLAs at non-function scopes, or during
11348 tentative template substitution. */
11349 || !at_function_scope_p ()
11350 || !(complain & tf_error))
11352 if (!(complain & tf_error))
11353 return error_mark_node;
11354 /* `(int) &fn' is not a valid array bound. */
11355 if (name)
11356 error_at (loc,
11357 "size of array %qD is not an integral constant-expression",
11358 name);
11359 else
11360 error_at (loc, "size of array is not an integral constant-expression");
11361 size = integer_one_node;
11363 else if (pedantic && warn_vla != 0)
11365 if (name)
11366 pedwarn (name_loc, OPT_Wvla,
11367 "ISO C++ forbids variable length array %qD", name);
11368 else
11369 pedwarn (input_location, OPT_Wvla,
11370 "ISO C++ forbids variable length array");
11372 else if (warn_vla > 0)
11374 if (name)
11375 warning_at (name_loc, OPT_Wvla,
11376 "variable length array %qD is used", name);
11377 else
11378 warning (OPT_Wvla,
11379 "variable length array is used");
11382 if (processing_template_decl && !TREE_CONSTANT (size))
11383 goto in_template;
11384 else
11386 if (!TREE_CONSTANT (size))
11388 /* A variable sized array. Arrange for the SAVE_EXPR on the inside
11389 of the MINUS_EXPR, which allows the -1 to get folded with the +1
11390 that happens when building TYPE_SIZE. */
11391 size = variable_size (size);
11392 stabilize_vla_size (size);
11395 /* Compute the index of the largest element in the array. It is
11396 one less than the number of elements in the array. We save
11397 and restore PROCESSING_TEMPLATE_DECL so that computations in
11398 cp_build_binary_op will be appropriately folded. */
11400 processing_template_decl_sentinel s;
11401 itype = cp_build_binary_op (input_location,
11402 MINUS_EXPR,
11403 cp_convert (ssizetype, size, complain),
11404 cp_convert (ssizetype, integer_one_node,
11405 complain),
11406 complain);
11407 itype = maybe_constant_value (itype, NULL_TREE, mce_true);
11410 if (!TREE_CONSTANT (itype))
11412 if (sanitize_flags_p (SANITIZE_VLA)
11413 && current_function_decl != NULL_TREE)
11415 /* We have to add 1 -- in the ubsan routine we generate
11416 LE_EXPR rather than LT_EXPR. */
11417 tree t = fold_build2 (PLUS_EXPR, TREE_TYPE (itype), itype,
11418 build_one_cst (TREE_TYPE (itype)));
11419 t = ubsan_instrument_vla (input_location, t);
11420 finish_expr_stmt (t);
11423 /* Make sure that there was no overflow when creating to a signed
11424 index type. (For example, on a 32-bit machine, an array with
11425 size 2^32 - 1 is too big.) */
11426 else if (TREE_CODE (itype) == INTEGER_CST
11427 && TREE_OVERFLOW (itype))
11429 if (!(complain & tf_error))
11430 return error_mark_node;
11431 error ("overflow in array dimension");
11432 TREE_OVERFLOW (itype) = 0;
11436 /* Create and return the appropriate index type. */
11437 itype = build_index_type (itype);
11439 /* If the index type were dependent, we would have returned early, so
11440 remember that it isn't. */
11441 TYPE_DEPENDENT_P (itype) = 0;
11442 TYPE_DEPENDENT_P_VALID (itype) = 1;
11443 return itype;
11446 tree
11447 compute_array_index_type (tree name, tree size, tsubst_flags_t complain)
11449 return compute_array_index_type_loc (input_location, name, size, complain);
11452 /* Returns the scope (if any) in which the entity declared by
11453 DECLARATOR will be located. If the entity was declared with an
11454 unqualified name, NULL_TREE is returned. */
11456 tree
11457 get_scope_of_declarator (const cp_declarator *declarator)
11459 while (declarator && declarator->kind != cdk_id)
11460 declarator = declarator->declarator;
11462 /* If the declarator-id is a SCOPE_REF, the scope in which the
11463 declaration occurs is the first operand. */
11464 if (declarator
11465 && declarator->u.id.qualifying_scope)
11466 return declarator->u.id.qualifying_scope;
11468 /* Otherwise, the declarator is not a qualified name; the entity will
11469 be declared in the current scope. */
11470 return NULL_TREE;
11473 /* Returns an ARRAY_TYPE for an array with SIZE elements of the
11474 indicated TYPE. If non-NULL, NAME is the NAME of the declaration
11475 with this type. */
11477 static tree
11478 create_array_type_for_decl (tree name, tree type, tree size, location_t loc)
11480 tree itype = NULL_TREE;
11482 /* If things have already gone awry, bail now. */
11483 if (type == error_mark_node || size == error_mark_node)
11484 return error_mark_node;
11486 /* [dcl.type.class.deduct] prohibits forming an array of placeholder
11487 for a deduced class type. */
11488 if (template_placeholder_p (type))
11490 if (name)
11491 error_at (loc, "%qD declared as array of template placeholder "
11492 "type %qT", name, type);
11493 else
11494 error ("creating array of template placeholder type %qT", type);
11495 return error_mark_node;
11498 /* If there are some types which cannot be array elements,
11499 issue an error-message and return. */
11500 switch (TREE_CODE (type))
11502 case VOID_TYPE:
11503 if (name)
11504 error_at (loc, "declaration of %qD as array of void", name);
11505 else
11506 error ("creating array of void");
11507 return error_mark_node;
11509 case FUNCTION_TYPE:
11510 if (name)
11511 error_at (loc, "declaration of %qD as array of functions", name);
11512 else
11513 error ("creating array of functions");
11514 return error_mark_node;
11516 case REFERENCE_TYPE:
11517 if (name)
11518 error_at (loc, "declaration of %qD as array of references", name);
11519 else
11520 error ("creating array of references");
11521 return error_mark_node;
11523 case METHOD_TYPE:
11524 if (name)
11525 error_at (loc, "declaration of %qD as array of function members",
11526 name);
11527 else
11528 error ("creating array of function members");
11529 return error_mark_node;
11531 default:
11532 break;
11535 if (!verify_type_context (name ? loc : input_location,
11536 TCTX_ARRAY_ELEMENT, type))
11537 return error_mark_node;
11539 /* [dcl.array]
11541 The constant expressions that specify the bounds of the arrays
11542 can be omitted only for the first member of the sequence. */
11543 if (TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type))
11545 if (name)
11546 error_at (loc, "declaration of %qD as multidimensional array must "
11547 "have bounds for all dimensions except the first",
11548 name);
11549 else
11550 error ("multidimensional array must have bounds for all "
11551 "dimensions except the first");
11553 return error_mark_node;
11556 /* Figure out the index type for the array. */
11557 if (size)
11559 itype = compute_array_index_type_loc (loc, name, size,
11560 tf_warning_or_error);
11561 if (type_uses_auto (type)
11562 && variably_modified_type_p (itype, /*fn=*/NULL_TREE))
11564 sorry_at (loc, "variable-length array of %<auto%>");
11565 return error_mark_node;
11569 return build_cplus_array_type (type, itype);
11572 /* Returns the smallest location that is not UNKNOWN_LOCATION. */
11574 static location_t
11575 min_location (location_t loca, location_t locb)
11577 if (loca == UNKNOWN_LOCATION
11578 || (locb != UNKNOWN_LOCATION
11579 && linemap_location_before_p (line_table, locb, loca)))
11580 return locb;
11581 return loca;
11584 /* Returns the smallest location != UNKNOWN_LOCATION among the
11585 three stored in LOCATIONS[ds_const], LOCATIONS[ds_volatile],
11586 and LOCATIONS[ds_restrict]. */
11588 static location_t
11589 smallest_type_quals_location (int type_quals, const location_t* locations)
11591 location_t loc = UNKNOWN_LOCATION;
11593 if (type_quals & TYPE_QUAL_CONST)
11594 loc = locations[ds_const];
11596 if (type_quals & TYPE_QUAL_VOLATILE)
11597 loc = min_location (loc, locations[ds_volatile]);
11599 if (type_quals & TYPE_QUAL_RESTRICT)
11600 loc = min_location (loc, locations[ds_restrict]);
11602 return loc;
11605 /* Returns the smallest among the latter and locations[ds_type_spec]. */
11607 static location_t
11608 smallest_type_location (int type_quals, const location_t* locations)
11610 location_t loc = smallest_type_quals_location (type_quals, locations);
11611 return min_location (loc, locations[ds_type_spec]);
11614 static location_t
11615 smallest_type_location (const cp_decl_specifier_seq *declspecs)
11617 int type_quals = get_type_quals (declspecs);
11618 return smallest_type_location (type_quals, declspecs->locations);
11621 /* Check that it's OK to declare a function with the indicated TYPE
11622 and TYPE_QUALS. SFK indicates the kind of special function (if any)
11623 that this function is. OPTYPE is the type given in a conversion
11624 operator declaration, or the class type for a constructor/destructor.
11625 Returns the actual return type of the function; that may be different
11626 than TYPE if an error occurs, or for certain special functions. */
11628 static tree
11629 check_special_function_return_type (special_function_kind sfk,
11630 tree type,
11631 tree optype,
11632 int type_quals,
11633 const location_t* locations)
11635 switch (sfk)
11637 case sfk_constructor:
11638 if (type)
11639 error_at (smallest_type_location (type_quals, locations),
11640 "return type specification for constructor invalid");
11641 else if (type_quals != TYPE_UNQUALIFIED)
11642 error_at (smallest_type_quals_location (type_quals, locations),
11643 "qualifiers are not allowed on constructor declaration");
11645 if (targetm.cxx.cdtor_returns_this ())
11646 type = build_pointer_type (optype);
11647 else
11648 type = void_type_node;
11649 break;
11651 case sfk_destructor:
11652 if (type)
11653 error_at (smallest_type_location (type_quals, locations),
11654 "return type specification for destructor invalid");
11655 else if (type_quals != TYPE_UNQUALIFIED)
11656 error_at (smallest_type_quals_location (type_quals, locations),
11657 "qualifiers are not allowed on destructor declaration");
11659 /* We can't use the proper return type here because we run into
11660 problems with ambiguous bases and covariant returns. */
11661 if (targetm.cxx.cdtor_returns_this ())
11662 type = build_pointer_type (void_type_node);
11663 else
11664 type = void_type_node;
11665 break;
11667 case sfk_conversion:
11668 if (type)
11669 error_at (smallest_type_location (type_quals, locations),
11670 "return type specified for %<operator %T%>", optype);
11671 else if (type_quals != TYPE_UNQUALIFIED)
11672 error_at (smallest_type_quals_location (type_quals, locations),
11673 "qualifiers are not allowed on declaration of "
11674 "%<operator %T%>", optype);
11676 type = optype;
11677 break;
11679 case sfk_deduction_guide:
11680 if (type)
11681 error_at (smallest_type_location (type_quals, locations),
11682 "return type specified for deduction guide");
11683 else if (type_quals != TYPE_UNQUALIFIED)
11684 error_at (smallest_type_quals_location (type_quals, locations),
11685 "qualifiers are not allowed on declaration of "
11686 "deduction guide");
11687 if (TREE_CODE (optype) == TEMPLATE_TEMPLATE_PARM)
11689 error ("template template parameter %qT in declaration of "
11690 "deduction guide", optype);
11691 type = error_mark_node;
11693 else
11694 type = make_template_placeholder (CLASSTYPE_TI_TEMPLATE (optype));
11695 for (int i = 0; i < ds_last; ++i)
11696 if (i != ds_explicit && locations[i])
11697 error_at (locations[i],
11698 "%<decl-specifier%> in declaration of deduction guide");
11699 break;
11701 default:
11702 gcc_unreachable ();
11705 return type;
11708 /* A variable or data member (whose unqualified name is IDENTIFIER)
11709 has been declared with the indicated TYPE. If the TYPE is not
11710 acceptable, issue an error message and return a type to use for
11711 error-recovery purposes. */
11713 tree
11714 check_var_type (tree identifier, tree type, location_t loc)
11716 if (VOID_TYPE_P (type))
11718 if (!identifier)
11719 error_at (loc, "unnamed variable or field declared void");
11720 else if (identifier_p (identifier))
11722 gcc_assert (!IDENTIFIER_ANY_OP_P (identifier));
11723 error_at (loc, "variable or field %qE declared void",
11724 identifier);
11726 else
11727 error_at (loc, "variable or field declared void");
11728 type = error_mark_node;
11731 return type;
11734 /* Handle declaring DECL as an inline variable. */
11736 static void
11737 mark_inline_variable (tree decl, location_t loc)
11739 bool inlinep = true;
11740 if (! toplevel_bindings_p ())
11742 error_at (loc, "%<inline%> specifier invalid for variable "
11743 "%qD declared at block scope", decl);
11744 inlinep = false;
11746 else if (cxx_dialect < cxx17)
11747 pedwarn (loc, OPT_Wc__17_extensions, "inline variables are only available "
11748 "with %<-std=c++17%> or %<-std=gnu++17%>");
11749 if (inlinep)
11751 retrofit_lang_decl (decl);
11752 SET_DECL_VAR_DECLARED_INLINE_P (decl);
11757 /* Assign a typedef-given name to a class or enumeration type declared
11758 as anonymous at first. This was split out of grokdeclarator
11759 because it is also used in libcc1. */
11761 void
11762 name_unnamed_type (tree type, tree decl)
11764 gcc_assert (TYPE_UNNAMED_P (type));
11766 /* Replace the anonymous decl with the real decl. Be careful not to
11767 rename other typedefs (such as the self-reference) of type. */
11768 tree orig = TYPE_NAME (type);
11769 for (tree t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
11770 if (TYPE_NAME (t) == orig)
11771 TYPE_NAME (t) = decl;
11773 /* If this is a typedef within a template class, the nested
11774 type is a (non-primary) template. The name for the
11775 template needs updating as well. */
11776 if (TYPE_LANG_SPECIFIC (type) && CLASSTYPE_TEMPLATE_INFO (type))
11777 DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)) = DECL_NAME (decl);
11779 /* Adjust linkage now that we aren't unnamed anymore. */
11780 reset_type_linkage (type);
11782 /* FIXME remangle member functions; member functions of a
11783 type with external linkage have external linkage. */
11785 /* Check that our job is done, and that it would fail if we
11786 attempted to do it again. */
11787 gcc_assert (!TYPE_UNNAMED_P (type));
11790 /* Check that decltype(auto) was well-formed: only plain decltype(auto)
11791 is allowed. TYPE might contain a decltype(auto). Returns true if
11792 there was a problem, false otherwise. */
11794 static bool
11795 check_decltype_auto (location_t loc, tree type)
11797 if (tree a = type_uses_auto (type))
11799 if (AUTO_IS_DECLTYPE (a))
11801 if (a != type)
11803 error_at (loc, "%qT as type rather than plain "
11804 "%<decltype(auto)%>", type);
11805 return true;
11807 else if (TYPE_QUALS (type) != TYPE_UNQUALIFIED)
11809 error_at (loc, "%<decltype(auto)%> cannot be cv-qualified");
11810 return true;
11814 return false;
11817 /* Given declspecs and a declarator (abstract or otherwise), determine
11818 the name and type of the object declared and construct a DECL node
11819 for it.
11821 DECLSPECS points to the representation of declaration-specifier
11822 sequence that precedes declarator.
11824 DECL_CONTEXT says which syntactic context this declaration is in:
11825 NORMAL for most contexts. Make a VAR_DECL or FUNCTION_DECL or TYPE_DECL.
11826 FUNCDEF for a function definition. Like NORMAL but a few different
11827 error messages in each case. Return value may be zero meaning
11828 this definition is too screwy to try to parse.
11829 MEMFUNCDEF for a function definition. Like FUNCDEF but prepares to
11830 handle member functions (which have FIELD context).
11831 Return value may be zero meaning this definition is too screwy to
11832 try to parse.
11833 PARM for a parameter declaration (either within a function prototype
11834 or before a function body). Make a PARM_DECL, or return void_type_node.
11835 TPARM for a template parameter declaration.
11836 CATCHPARM for a parameter declaration before a catch clause.
11837 TYPENAME if for a typename (in a cast or sizeof).
11838 Don't make a DECL node; just return the ..._TYPE node.
11839 FIELD for a struct or union field; make a FIELD_DECL.
11840 BITFIELD for a field with specified width.
11842 INITIALIZED is as for start_decl.
11844 ATTRLIST is a pointer to the list of attributes, which may be NULL
11845 if there are none; *ATTRLIST may be modified if attributes from inside
11846 the declarator should be applied to the declaration.
11848 When this function is called, scoping variables (such as
11849 CURRENT_CLASS_TYPE) should reflect the scope in which the
11850 declaration occurs, not the scope in which the new declaration will
11851 be placed. For example, on:
11853 void S::f() { ... }
11855 when grokdeclarator is called for `S::f', the CURRENT_CLASS_TYPE
11856 should not be `S'.
11858 Returns a DECL (if a declarator is present), a TYPE (if there is no
11859 declarator, in cases like "struct S;"), or the ERROR_MARK_NODE if an
11860 error occurs. */
11862 tree
11863 grokdeclarator (const cp_declarator *declarator,
11864 cp_decl_specifier_seq *declspecs,
11865 enum decl_context decl_context,
11866 int initialized,
11867 tree* attrlist)
11869 tree type = NULL_TREE;
11870 int longlong = 0;
11871 int explicit_intN = 0;
11872 int int_n_alt = 0;
11873 int virtualp, explicitp, friendp, inlinep, staticp;
11874 int explicit_int = 0;
11875 int explicit_char = 0;
11876 int defaulted_int = 0;
11878 tree typedef_decl = NULL_TREE;
11879 const char *name = NULL;
11880 tree typedef_type = NULL_TREE;
11881 /* True if this declarator is a function definition. */
11882 bool funcdef_flag = false;
11883 cp_declarator_kind innermost_code = cdk_error;
11884 int bitfield = 0;
11885 #if 0
11886 /* See the code below that used this. */
11887 tree decl_attr = NULL_TREE;
11888 #endif
11890 /* Keep track of what sort of function is being processed
11891 so that we can warn about default return values, or explicit
11892 return values which do not match prescribed defaults. */
11893 special_function_kind sfk = sfk_none;
11895 tree dname = NULL_TREE;
11896 tree ctor_return_type = NULL_TREE;
11897 enum overload_flags flags = NO_SPECIAL;
11898 /* cv-qualifiers that apply to the declarator, for a declaration of
11899 a member function. */
11900 cp_cv_quals memfn_quals = TYPE_UNQUALIFIED;
11901 /* virt-specifiers that apply to the declarator, for a declaration of
11902 a member function. */
11903 cp_virt_specifiers virt_specifiers = VIRT_SPEC_UNSPECIFIED;
11904 /* ref-qualifier that applies to the declarator, for a declaration of
11905 a member function. */
11906 cp_ref_qualifier rqual = REF_QUAL_NONE;
11907 /* cv-qualifiers that apply to the type specified by the DECLSPECS. */
11908 int type_quals = get_type_quals (declspecs);
11909 tree raises = NULL_TREE;
11910 int template_count = 0;
11911 tree returned_attrs = NULL_TREE;
11912 tree parms = NULL_TREE;
11913 const cp_declarator *id_declarator;
11914 /* The unqualified name of the declarator; either an
11915 IDENTIFIER_NODE, BIT_NOT_EXPR, or TEMPLATE_ID_EXPR. */
11916 tree unqualified_id;
11917 /* The class type, if any, in which this entity is located,
11918 or NULL_TREE if none. Note that this value may be different from
11919 the current class type; for example if an attempt is made to declare
11920 "A::f" inside "B", this value will be "A". */
11921 tree ctype = current_class_type;
11922 /* The NAMESPACE_DECL for the namespace in which this entity is
11923 located. If an unqualified name is used to declare the entity,
11924 this value will be NULL_TREE, even if the entity is located at
11925 namespace scope. */
11926 tree in_namespace = NULL_TREE;
11927 cp_storage_class storage_class;
11928 bool unsigned_p, signed_p, short_p, long_p, thread_p;
11929 bool type_was_error_mark_node = false;
11930 bool parameter_pack_p = declarator ? declarator->parameter_pack_p : false;
11931 bool template_type_arg = false;
11932 bool template_parm_flag = false;
11933 bool typedef_p = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
11934 bool constexpr_p = decl_spec_seq_has_spec_p (declspecs, ds_constexpr);
11935 bool constinit_p = decl_spec_seq_has_spec_p (declspecs, ds_constinit);
11936 bool consteval_p = decl_spec_seq_has_spec_p (declspecs, ds_consteval);
11937 bool late_return_type_p = false;
11938 bool array_parameter_p = false;
11939 tree reqs = NULL_TREE;
11941 signed_p = decl_spec_seq_has_spec_p (declspecs, ds_signed);
11942 unsigned_p = decl_spec_seq_has_spec_p (declspecs, ds_unsigned);
11943 short_p = decl_spec_seq_has_spec_p (declspecs, ds_short);
11944 long_p = decl_spec_seq_has_spec_p (declspecs, ds_long);
11945 longlong = decl_spec_seq_has_spec_p (declspecs, ds_long_long);
11946 explicit_intN = declspecs->explicit_intN_p;
11947 int_n_alt = declspecs->int_n_alt;
11948 thread_p = decl_spec_seq_has_spec_p (declspecs, ds_thread);
11950 // Was concept_p specified? Note that ds_concept
11951 // implies ds_constexpr!
11952 bool concept_p = decl_spec_seq_has_spec_p (declspecs, ds_concept);
11953 if (concept_p)
11954 constexpr_p = true;
11956 if (decl_context == FUNCDEF)
11957 funcdef_flag = true, decl_context = NORMAL;
11958 else if (decl_context == MEMFUNCDEF)
11959 funcdef_flag = true, decl_context = FIELD;
11960 else if (decl_context == BITFIELD)
11961 bitfield = 1, decl_context = FIELD;
11962 else if (decl_context == TEMPLATE_TYPE_ARG)
11963 template_type_arg = true, decl_context = TYPENAME;
11964 else if (decl_context == TPARM)
11965 template_parm_flag = true, decl_context = PARM;
11967 if (initialized == SD_DEFAULTED || initialized == SD_DELETED)
11968 funcdef_flag = true;
11970 location_t typespec_loc = loc_or_input_loc (smallest_type_location
11971 (type_quals,
11972 declspecs->locations));
11973 location_t id_loc;
11974 location_t init_loc;
11975 if (declarator)
11977 id_loc = loc_or_input_loc (declarator->id_loc);
11978 init_loc = loc_or_input_loc (declarator->init_loc);
11980 else
11981 init_loc = id_loc = input_location;
11983 /* Look inside a declarator for the name being declared
11984 and get it as a string, for an error message. */
11985 for (id_declarator = declarator;
11986 id_declarator;
11987 id_declarator = id_declarator->declarator)
11989 if (id_declarator->kind != cdk_id)
11990 innermost_code = id_declarator->kind;
11992 switch (id_declarator->kind)
11994 case cdk_function:
11995 if (id_declarator->declarator
11996 && id_declarator->declarator->kind == cdk_id)
11998 sfk = id_declarator->declarator->u.id.sfk;
11999 if (sfk == sfk_destructor)
12000 flags = DTOR_FLAG;
12002 break;
12004 case cdk_id:
12006 tree qualifying_scope = id_declarator->u.id.qualifying_scope;
12007 tree decl = id_declarator->u.id.unqualified_name;
12008 if (!decl)
12009 break;
12010 if (qualifying_scope)
12012 if (check_for_bare_parameter_packs (qualifying_scope,
12013 id_declarator->id_loc))
12014 return error_mark_node;
12015 if (at_function_scope_p ())
12017 /* [dcl.meaning]
12019 A declarator-id shall not be qualified except
12020 for ...
12022 None of the cases are permitted in block
12023 scope. */
12024 if (qualifying_scope == global_namespace)
12025 error ("invalid use of qualified-name %<::%D%>",
12026 decl);
12027 else if (TYPE_P (qualifying_scope))
12028 error ("invalid use of qualified-name %<%T::%D%>",
12029 qualifying_scope, decl);
12030 else
12031 error ("invalid use of qualified-name %<%D::%D%>",
12032 qualifying_scope, decl);
12033 return error_mark_node;
12035 else if (TYPE_P (qualifying_scope))
12037 ctype = qualifying_scope;
12038 if (!MAYBE_CLASS_TYPE_P (ctype))
12040 error_at (id_declarator->id_loc,
12041 "%q#T is not a class or namespace", ctype);
12042 ctype = NULL_TREE;
12044 else if (innermost_code != cdk_function
12045 && current_class_type
12046 && !uniquely_derived_from_p (ctype,
12047 current_class_type))
12049 error_at (id_declarator->id_loc,
12050 "invalid use of qualified-name %<%T::%D%>",
12051 qualifying_scope, decl);
12052 return error_mark_node;
12055 else if (TREE_CODE (qualifying_scope) == NAMESPACE_DECL)
12056 in_namespace = qualifying_scope;
12058 switch (TREE_CODE (decl))
12060 case BIT_NOT_EXPR:
12062 if (innermost_code != cdk_function)
12064 error_at (EXPR_LOCATION (decl),
12065 "declaration of %qE as non-function", decl);
12066 return error_mark_node;
12068 else if (!qualifying_scope
12069 && !(current_class_type && at_class_scope_p ()))
12071 error_at (EXPR_LOCATION (decl),
12072 "declaration of %qE as non-member", decl);
12073 return error_mark_node;
12076 tree type = TREE_OPERAND (decl, 0);
12077 if (TYPE_P (type))
12078 type = constructor_name (type);
12079 name = identifier_to_locale (IDENTIFIER_POINTER (type));
12080 dname = decl;
12082 break;
12084 case TEMPLATE_ID_EXPR:
12086 tree fns = TREE_OPERAND (decl, 0);
12088 dname = fns;
12089 if (!identifier_p (dname))
12090 dname = OVL_NAME (dname);
12092 /* Fall through. */
12094 case IDENTIFIER_NODE:
12095 if (identifier_p (decl))
12096 dname = decl;
12098 if (IDENTIFIER_KEYWORD_P (dname))
12100 error ("declarator-id missing; using reserved word %qD",
12101 dname);
12102 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
12104 else if (!IDENTIFIER_CONV_OP_P (dname))
12105 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
12106 else
12108 gcc_assert (flags == NO_SPECIAL);
12109 flags = TYPENAME_FLAG;
12110 sfk = sfk_conversion;
12111 tree glob = get_global_binding (dname);
12112 if (glob && TREE_CODE (glob) == TYPE_DECL)
12113 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
12114 else
12115 name = "<invalid operator>";
12117 break;
12119 default:
12120 gcc_unreachable ();
12122 break;
12125 case cdk_array:
12126 case cdk_pointer:
12127 case cdk_reference:
12128 case cdk_ptrmem:
12129 break;
12131 case cdk_decomp:
12132 name = "structured binding";
12133 break;
12135 case cdk_error:
12136 return error_mark_node;
12138 default:
12139 gcc_unreachable ();
12141 if (id_declarator->kind == cdk_id)
12142 break;
12145 /* [dcl.fct.edf]
12147 The declarator in a function-definition shall have the form
12148 D1 ( parameter-declaration-clause) ... */
12149 if (funcdef_flag && innermost_code != cdk_function)
12151 error_at (id_loc, "function definition does not declare parameters");
12152 return error_mark_node;
12155 if (flags == TYPENAME_FLAG
12156 && innermost_code != cdk_function
12157 && ! (ctype && !declspecs->any_specifiers_p))
12159 error_at (id_loc, "declaration of %qD as non-function", dname);
12160 return error_mark_node;
12163 if (dname && identifier_p (dname))
12165 if (UDLIT_OPER_P (dname)
12166 && innermost_code != cdk_function)
12168 error_at (id_loc, "declaration of %qD as non-function", dname);
12169 return error_mark_node;
12172 if (IDENTIFIER_ANY_OP_P (dname))
12174 if (typedef_p)
12176 error_at (id_loc, "declaration of %qD as %<typedef%>", dname);
12177 return error_mark_node;
12179 else if (decl_context == PARM || decl_context == CATCHPARM)
12181 error_at (id_loc, "declaration of %qD as parameter", dname);
12182 return error_mark_node;
12187 /* Anything declared one level down from the top level
12188 must be one of the parameters of a function
12189 (because the body is at least two levels down). */
12191 /* This heuristic cannot be applied to C++ nodes! Fixed, however,
12192 by not allowing C++ class definitions to specify their parameters
12193 with xdecls (must be spec.d in the parmlist).
12195 Since we now wait to push a class scope until we are sure that
12196 we are in a legitimate method context, we must set oldcname
12197 explicitly (since current_class_name is not yet alive).
12199 We also want to avoid calling this a PARM if it is in a namespace. */
12201 if (decl_context == NORMAL && !toplevel_bindings_p ())
12203 cp_binding_level *b = current_binding_level;
12204 current_binding_level = b->level_chain;
12205 if (current_binding_level != 0 && toplevel_bindings_p ())
12206 decl_context = PARM;
12207 current_binding_level = b;
12210 if (name == NULL)
12211 name = decl_context == PARM ? "parameter" : "type name";
12213 if (consteval_p && constexpr_p)
12215 error_at (declspecs->locations[ds_consteval],
12216 "both %qs and %qs specified", "constexpr", "consteval");
12217 return error_mark_node;
12220 if (concept_p && typedef_p)
12222 error_at (declspecs->locations[ds_concept],
12223 "%qs cannot appear in a typedef declaration", "concept");
12224 return error_mark_node;
12227 if (constexpr_p && typedef_p)
12229 error_at (declspecs->locations[ds_constexpr],
12230 "%qs cannot appear in a typedef declaration", "constexpr");
12231 return error_mark_node;
12234 if (consteval_p && typedef_p)
12236 error_at (declspecs->locations[ds_consteval],
12237 "%qs cannot appear in a typedef declaration", "consteval");
12238 return error_mark_node;
12241 if (constinit_p && typedef_p)
12243 error_at (declspecs->locations[ds_constinit],
12244 "%qs cannot appear in a typedef declaration", "constinit");
12245 return error_mark_node;
12248 /* [dcl.spec]/2 "At most one of the constexpr, consteval, and constinit
12249 keywords shall appear in a decl-specifier-seq." */
12250 if (constinit_p && constexpr_p)
12252 gcc_rich_location richloc (declspecs->locations[ds_constinit]);
12253 richloc.add_range (declspecs->locations[ds_constexpr]);
12254 error_at (&richloc,
12255 "can use at most one of the %<constinit%> and %<constexpr%> "
12256 "specifiers");
12257 return error_mark_node;
12260 /* If there were multiple types specified in the decl-specifier-seq,
12261 issue an error message. */
12262 if (declspecs->multiple_types_p)
12264 error_at (typespec_loc,
12265 "two or more data types in declaration of %qs", name);
12266 return error_mark_node;
12269 if (declspecs->conflicting_specifiers_p)
12270 return error_mark_node;
12272 /* Extract the basic type from the decl-specifier-seq. */
12273 type = declspecs->type;
12274 if (type == error_mark_node)
12276 type = NULL_TREE;
12277 type_was_error_mark_node = true;
12280 /* Ignore erroneous attributes. */
12281 if (attrlist && *attrlist == error_mark_node)
12282 *attrlist = NULL_TREE;
12284 /* An object declared as __attribute__((unavailable)) suppresses
12285 any reports of being declared with unavailable or deprecated
12286 items. An object declared as __attribute__((deprecated))
12287 suppresses warnings of uses of other deprecated items. */
12288 auto ds = make_temp_override (deprecated_state);
12289 if (attrlist && lookup_attribute ("unavailable", *attrlist))
12290 deprecated_state = UNAVAILABLE_DEPRECATED_SUPPRESS;
12291 else if (attrlist && lookup_attribute ("deprecated", *attrlist))
12292 deprecated_state = DEPRECATED_SUPPRESS;
12294 cp_handle_deprecated_or_unavailable (type);
12295 if (type && TREE_CODE (type) == TYPE_DECL)
12297 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (type));
12298 typedef_decl = type;
12299 type = TREE_TYPE (typedef_decl);
12300 if (DECL_ARTIFICIAL (typedef_decl))
12301 cp_handle_deprecated_or_unavailable (type);
12303 /* No type at all: default to `int', and set DEFAULTED_INT
12304 because it was not a user-defined typedef. */
12305 if (type == NULL_TREE)
12307 if (signed_p || unsigned_p || long_p || short_p)
12309 /* These imply 'int'. */
12310 type = integer_type_node;
12311 defaulted_int = 1;
12313 /* If we just have "complex", it is equivalent to "complex double". */
12314 else if (!longlong && !explicit_intN
12315 && decl_spec_seq_has_spec_p (declspecs, ds_complex))
12317 type = double_type_node;
12318 pedwarn (declspecs->locations[ds_complex], OPT_Wpedantic,
12319 "ISO C++ does not support plain %<complex%> meaning "
12320 "%<double complex%>");
12323 /* Gather flags. */
12324 explicit_int = declspecs->explicit_int_p;
12325 explicit_char = declspecs->explicit_char_p;
12327 #if 0
12328 /* See the code below that used this. */
12329 if (typedef_decl)
12330 decl_attr = DECL_ATTRIBUTES (typedef_decl);
12331 #endif
12332 typedef_type = type;
12334 if (sfk == sfk_conversion || sfk == sfk_deduction_guide)
12335 ctor_return_type = TREE_TYPE (dname);
12336 else
12337 ctor_return_type = ctype;
12339 if (sfk != sfk_none)
12341 type = check_special_function_return_type (sfk, type,
12342 ctor_return_type,
12343 type_quals,
12344 declspecs->locations);
12345 type_quals = TYPE_UNQUALIFIED;
12347 else if (type == NULL_TREE)
12349 int is_main;
12351 explicit_int = -1;
12353 /* We handle `main' specially here, because 'main () { }' is so
12354 common. With no options, it is allowed. With -Wreturn-type,
12355 it is a warning. It is only an error with -pedantic-errors. */
12356 is_main = (funcdef_flag
12357 && dname && identifier_p (dname)
12358 && MAIN_NAME_P (dname)
12359 && ctype == NULL_TREE
12360 && in_namespace == NULL_TREE
12361 && current_namespace == global_namespace);
12363 if (type_was_error_mark_node)
12364 /* We've already issued an error, don't complain more. */;
12365 else if (in_system_header_at (id_loc) || flag_ms_extensions)
12366 /* Allow it, sigh. */;
12367 else if (! is_main)
12368 permerror (id_loc, "ISO C++ forbids declaration of %qs with no type",
12369 name);
12370 else if (pedantic)
12371 pedwarn (id_loc, OPT_Wpedantic,
12372 "ISO C++ forbids declaration of %qs with no type", name);
12373 else
12374 warning_at (id_loc, OPT_Wreturn_type,
12375 "ISO C++ forbids declaration of %qs with no type", name);
12377 if (type_was_error_mark_node && template_parm_flag)
12378 /* FIXME we should be able to propagate the error_mark_node as is
12379 for other contexts too. */
12380 type = error_mark_node;
12381 else
12382 type = integer_type_node;
12385 ctype = NULL_TREE;
12387 if (explicit_intN)
12389 if (! int_n_enabled_p[declspecs->int_n_idx])
12391 error_at (declspecs->locations[ds_type_spec],
12392 "%<__int%d%> is not supported by this target",
12393 int_n_data[declspecs->int_n_idx].bitsize);
12394 explicit_intN = false;
12396 /* Don't pedwarn if the alternate "__intN__" form has been used instead
12397 of "__intN". */
12398 else if (!int_n_alt && pedantic)
12399 pedwarn (declspecs->locations[ds_type_spec], OPT_Wpedantic,
12400 "ISO C++ does not support %<__int%d%> for %qs",
12401 int_n_data[declspecs->int_n_idx].bitsize, name);
12404 /* Now process the modifiers that were specified
12405 and check for invalid combinations. */
12407 /* Long double is a special combination. */
12408 if (long_p && !longlong && TYPE_MAIN_VARIANT (type) == double_type_node)
12410 long_p = false;
12411 type = cp_build_qualified_type (long_double_type_node,
12412 cp_type_quals (type));
12415 /* Check all other uses of type modifiers. */
12417 if (unsigned_p || signed_p || long_p || short_p)
12419 location_t loc;
12420 const char *key;
12421 if (unsigned_p)
12423 key = "unsigned";
12424 loc = declspecs->locations[ds_unsigned];
12426 else if (signed_p)
12428 key = "signed";
12429 loc = declspecs->locations[ds_signed];
12431 else if (longlong)
12433 key = "long long";
12434 loc = declspecs->locations[ds_long_long];
12436 else if (long_p)
12438 key = "long";
12439 loc = declspecs->locations[ds_long];
12441 else /* if (short_p) */
12443 key = "short";
12444 loc = declspecs->locations[ds_short];
12447 int ok = 0;
12449 if (signed_p && unsigned_p)
12451 gcc_rich_location richloc (declspecs->locations[ds_signed]);
12452 richloc.add_range (declspecs->locations[ds_unsigned]);
12453 error_at (&richloc,
12454 "%<signed%> and %<unsigned%> specified together");
12456 else if (long_p && short_p)
12458 gcc_rich_location richloc (declspecs->locations[ds_long]);
12459 richloc.add_range (declspecs->locations[ds_short]);
12460 error_at (&richloc, "%<long%> and %<short%> specified together");
12462 else if (TREE_CODE (type) != INTEGER_TYPE
12463 || type == char8_type_node
12464 || type == char16_type_node
12465 || type == char32_type_node
12466 || ((long_p || short_p)
12467 && (explicit_char || explicit_intN)))
12468 error_at (loc, "%qs specified with %qT", key, type);
12469 else if (!explicit_int && !defaulted_int
12470 && !explicit_char && !explicit_intN)
12472 if (typedef_decl)
12474 pedwarn (loc, OPT_Wpedantic,
12475 "%qs specified with typedef-name %qD",
12476 key, typedef_decl);
12477 ok = !flag_pedantic_errors;
12478 /* PR108099: __int128_t comes from c_common_nodes_and_builtins,
12479 and is not built as a typedef. */
12480 if (is_typedef_decl (typedef_decl))
12481 type = DECL_ORIGINAL_TYPE (typedef_decl);
12483 else if (declspecs->decltype_p)
12484 error_at (loc, "%qs specified with %<decltype%>", key);
12485 else
12486 error_at (loc, "%qs specified with %<typeof%>", key);
12488 else
12489 ok = 1;
12491 /* Discard the type modifiers if they are invalid. */
12492 if (! ok)
12494 unsigned_p = false;
12495 signed_p = false;
12496 long_p = false;
12497 short_p = false;
12498 longlong = 0;
12502 /* Decide whether an integer type is signed or not.
12503 Optionally treat bitfields as signed by default. */
12504 if (unsigned_p
12505 /* [class.bit]
12507 It is implementation-defined whether a plain (neither
12508 explicitly signed or unsigned) char, short, int, or long
12509 bit-field is signed or unsigned.
12511 Naturally, we extend this to long long as well. Note that
12512 this does not include wchar_t. */
12513 || (bitfield && !flag_signed_bitfields
12514 && !signed_p
12515 /* A typedef for plain `int' without `signed' can be
12516 controlled just like plain `int', but a typedef for
12517 `signed int' cannot be so controlled. */
12518 && !(typedef_decl
12519 && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl))
12520 && TREE_CODE (type) == INTEGER_TYPE
12521 && !same_type_p (TYPE_MAIN_VARIANT (type), wchar_type_node)))
12523 if (explicit_intN)
12524 type = int_n_trees[declspecs->int_n_idx].unsigned_type;
12525 else if (longlong)
12526 type = long_long_unsigned_type_node;
12527 else if (long_p)
12528 type = long_unsigned_type_node;
12529 else if (short_p)
12530 type = short_unsigned_type_node;
12531 else if (type == char_type_node)
12532 type = unsigned_char_type_node;
12533 else if (typedef_decl)
12534 type = c_common_unsigned_type (type);
12535 else
12536 type = unsigned_type_node;
12538 else if (signed_p && type == char_type_node)
12539 type = signed_char_type_node;
12540 else if (explicit_intN)
12541 type = int_n_trees[declspecs->int_n_idx].signed_type;
12542 else if (longlong)
12543 type = long_long_integer_type_node;
12544 else if (long_p)
12545 type = long_integer_type_node;
12546 else if (short_p)
12547 type = short_integer_type_node;
12548 else if (signed_p && typedef_decl)
12549 type = c_common_signed_type (type);
12551 if (decl_spec_seq_has_spec_p (declspecs, ds_complex))
12553 if (TREE_CODE (type) != INTEGER_TYPE && TREE_CODE (type) != REAL_TYPE)
12554 error_at (declspecs->locations[ds_complex],
12555 "complex invalid for %qs", name);
12556 /* If a modifier is specified, the resulting complex is the complex
12557 form of TYPE. E.g, "complex short" is "complex short int". */
12558 else if (type == integer_type_node)
12559 type = complex_integer_type_node;
12560 else if (type == float_type_node)
12561 type = complex_float_type_node;
12562 else if (type == double_type_node)
12563 type = complex_double_type_node;
12564 else if (type == long_double_type_node)
12565 type = complex_long_double_type_node;
12566 else
12567 type = build_complex_type (type);
12570 /* If we're using the injected-class-name to form a compound type or a
12571 declaration, replace it with the underlying class so we don't get
12572 redundant typedefs in the debug output. But if we are returning the
12573 type unchanged, leave it alone so that it's available to
12574 maybe_get_template_decl_from_type_decl. */
12575 if (CLASS_TYPE_P (type)
12576 && DECL_SELF_REFERENCE_P (TYPE_NAME (type))
12577 && type == TREE_TYPE (TYPE_NAME (type))
12578 && (declarator || type_quals))
12579 type = DECL_ORIGINAL_TYPE (TYPE_NAME (type));
12581 type_quals |= cp_type_quals (type);
12582 type = cp_build_qualified_type
12583 (type, type_quals, ((((typedef_decl && !DECL_ARTIFICIAL (typedef_decl))
12584 || declspecs->decltype_p)
12585 ? tf_ignore_bad_quals : 0) | tf_warning_or_error));
12586 /* We might have ignored or rejected some of the qualifiers. */
12587 type_quals = cp_type_quals (type);
12589 if (cxx_dialect >= cxx17 && type && is_auto (type)
12590 && innermost_code != cdk_function
12591 /* Placeholder in parm gets a better error below. */
12592 && !(decl_context == PARM || decl_context == CATCHPARM)
12593 && id_declarator && declarator != id_declarator)
12594 if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (type))
12596 auto_diagnostic_group g;
12597 gcc_rich_location richloc (typespec_loc);
12598 richloc.add_fixit_insert_after ("<>");
12599 error_at (&richloc, "missing template argument list after %qE; "
12600 "for deduction, template placeholder must be followed "
12601 "by a simple declarator-id", tmpl);
12602 inform (DECL_SOURCE_LOCATION (tmpl), "%qD declared here", tmpl);
12603 type = error_mark_node;
12606 staticp = 0;
12607 inlinep = decl_spec_seq_has_spec_p (declspecs, ds_inline);
12608 virtualp = decl_spec_seq_has_spec_p (declspecs, ds_virtual);
12609 explicitp = decl_spec_seq_has_spec_p (declspecs, ds_explicit);
12611 storage_class = declspecs->storage_class;
12612 if (storage_class == sc_static)
12613 staticp = 1 + (decl_context == FIELD);
12614 else if (decl_context == FIELD && sfk == sfk_deduction_guide)
12615 /* Treat class-scope deduction guides as static member functions
12616 so that they get a FUNCTION_TYPE instead of a METHOD_TYPE. */
12617 staticp = 2;
12619 if (virtualp)
12621 if (staticp == 2)
12623 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
12624 richloc.add_range (declspecs->locations[ds_storage_class]);
12625 error_at (&richloc, "member %qD cannot be declared both %<virtual%> "
12626 "and %<static%>", dname);
12627 storage_class = sc_none;
12628 staticp = 0;
12630 if (constexpr_p && pedantic && cxx_dialect < cxx20)
12632 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
12633 richloc.add_range (declspecs->locations[ds_constexpr]);
12634 pedwarn (&richloc, OPT_Wc__20_extensions, "member %qD can be "
12635 "declared both %<virtual%> and %<constexpr%> only in "
12636 "%<-std=c++20%> or %<-std=gnu++20%>", dname);
12639 friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
12641 /* Issue errors about use of storage classes for parameters. */
12642 if (decl_context == PARM)
12644 if (typedef_p)
12646 error_at (declspecs->locations[ds_typedef],
12647 "typedef declaration invalid in parameter declaration");
12648 return error_mark_node;
12650 else if (template_parm_flag && storage_class != sc_none)
12652 error_at (min_location (declspecs->locations[ds_thread],
12653 declspecs->locations[ds_storage_class]),
12654 "storage class specified for template parameter %qs",
12655 name);
12656 return error_mark_node;
12658 else if (storage_class == sc_static
12659 || storage_class == sc_extern
12660 || thread_p)
12662 error_at (min_location (declspecs->locations[ds_thread],
12663 declspecs->locations[ds_storage_class]),
12664 "storage class specified for parameter %qs", name);
12665 return error_mark_node;
12668 /* Function parameters cannot be concept. */
12669 if (concept_p)
12671 error_at (declspecs->locations[ds_concept],
12672 "a parameter cannot be declared %qs", "concept");
12673 concept_p = 0;
12674 constexpr_p = 0;
12676 /* Function parameters cannot be constexpr. If we saw one, moan
12677 and pretend it wasn't there. */
12678 else if (constexpr_p)
12680 error_at (declspecs->locations[ds_constexpr],
12681 "a parameter cannot be declared %qs", "constexpr");
12682 constexpr_p = 0;
12684 if (constinit_p)
12686 error_at (declspecs->locations[ds_constinit],
12687 "a parameter cannot be declared %qs", "constinit");
12688 constinit_p = 0;
12690 if (consteval_p)
12692 error_at (declspecs->locations[ds_consteval],
12693 "a parameter cannot be declared %qs", "consteval");
12694 consteval_p = 0;
12698 /* Give error if `virtual' is used outside of class declaration. */
12699 if (virtualp
12700 && (current_class_name == NULL_TREE || decl_context != FIELD))
12702 error_at (declspecs->locations[ds_virtual],
12703 "%<virtual%> outside class declaration");
12704 virtualp = 0;
12707 if (innermost_code == cdk_decomp)
12709 location_t loc = (declarator->kind == cdk_reference
12710 ? declarator->declarator->id_loc : declarator->id_loc);
12711 if (inlinep)
12712 error_at (declspecs->locations[ds_inline],
12713 "structured binding declaration cannot be %qs", "inline");
12714 if (typedef_p)
12715 error_at (declspecs->locations[ds_typedef],
12716 "structured binding declaration cannot be %qs", "typedef");
12717 if (constexpr_p && !concept_p)
12718 error_at (declspecs->locations[ds_constexpr], "structured "
12719 "binding declaration cannot be %qs", "constexpr");
12720 if (consteval_p)
12721 error_at (declspecs->locations[ds_consteval], "structured "
12722 "binding declaration cannot be %qs", "consteval");
12723 if (thread_p && cxx_dialect < cxx20)
12724 pedwarn (declspecs->locations[ds_thread], OPT_Wc__20_extensions,
12725 "structured binding declaration can be %qs only in "
12726 "%<-std=c++20%> or %<-std=gnu++20%>",
12727 declspecs->gnu_thread_keyword_p
12728 ? "__thread" : "thread_local");
12729 if (concept_p)
12730 error_at (declspecs->locations[ds_concept],
12731 "structured binding declaration cannot be %qs", "concept");
12732 /* [dcl.struct.bind] "A cv that includes volatile is deprecated." */
12733 if (type_quals & TYPE_QUAL_VOLATILE)
12734 warning_at (declspecs->locations[ds_volatile], OPT_Wvolatile,
12735 "%<volatile%>-qualified structured binding is deprecated");
12736 switch (storage_class)
12738 case sc_none:
12739 break;
12740 case sc_register:
12741 error_at (loc, "structured binding declaration cannot be %qs",
12742 "register");
12743 break;
12744 case sc_static:
12745 if (cxx_dialect < cxx20)
12746 pedwarn (loc, OPT_Wc__20_extensions,
12747 "structured binding declaration can be %qs only in "
12748 "%<-std=c++20%> or %<-std=gnu++20%>", "static");
12749 break;
12750 case sc_extern:
12751 error_at (loc, "structured binding declaration cannot be %qs",
12752 "extern");
12753 break;
12754 case sc_mutable:
12755 error_at (loc, "structured binding declaration cannot be %qs",
12756 "mutable");
12757 break;
12758 case sc_auto:
12759 error_at (loc, "structured binding declaration cannot be "
12760 "C++98 %<auto%>");
12761 break;
12762 default:
12763 gcc_unreachable ();
12765 if (TREE_CODE (type) != TEMPLATE_TYPE_PARM
12766 || TYPE_IDENTIFIER (type) != auto_identifier)
12768 if (type != error_mark_node)
12770 auto_diagnostic_group d;
12771 error_at (loc, "structured binding declaration cannot have "
12772 "type %qT", type);
12773 inform (loc,
12774 "type must be cv-qualified %<auto%> or reference to "
12775 "cv-qualified %<auto%>");
12777 type = build_qualified_type (make_auto (), type_quals);
12778 declspecs->type = type;
12780 else if (PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type))
12781 pedwarn (loc, OPT_Wpedantic,
12782 "structured binding declaration cannot have constrained "
12783 "%<auto%> type %qT", type);
12784 inlinep = 0;
12785 typedef_p = 0;
12786 constexpr_p = 0;
12787 consteval_p = 0;
12788 concept_p = 0;
12789 if (storage_class != sc_static)
12791 storage_class = sc_none;
12792 declspecs->storage_class = sc_none;
12796 /* Static anonymous unions are dealt with here. */
12797 if (staticp && decl_context == TYPENAME
12798 && declspecs->type
12799 && ANON_AGGR_TYPE_P (declspecs->type))
12800 decl_context = FIELD;
12802 /* Warn about storage classes that are invalid for certain
12803 kinds of declarations (parameters, typenames, etc.). */
12804 if (thread_p
12805 && ((storage_class
12806 && storage_class != sc_extern
12807 && storage_class != sc_static)
12808 || typedef_p))
12810 location_t loc
12811 = min_location (declspecs->locations[ds_thread],
12812 declspecs->locations[ds_storage_class]);
12813 error_at (loc, "multiple storage classes in declaration of %qs", name);
12814 thread_p = false;
12816 if (decl_context != NORMAL
12817 && ((storage_class != sc_none
12818 && storage_class != sc_mutable)
12819 || thread_p))
12821 if ((decl_context == PARM || decl_context == CATCHPARM)
12822 && (storage_class == sc_register
12823 || storage_class == sc_auto))
12825 else if (typedef_p)
12827 else if (decl_context == FIELD
12828 /* C++ allows static class elements. */
12829 && storage_class == sc_static)
12830 /* C++ also allows inlines and signed and unsigned elements,
12831 but in those cases we don't come in here. */
12833 else
12835 location_t loc
12836 = min_location (declspecs->locations[ds_thread],
12837 declspecs->locations[ds_storage_class]);
12838 if (decl_context == FIELD)
12839 error_at (loc, "storage class specified for %qs", name);
12840 else if (decl_context == PARM || decl_context == CATCHPARM)
12841 error_at (loc, "storage class specified for parameter %qs", name);
12842 else
12843 error_at (loc, "storage class specified for typename");
12844 if (storage_class == sc_register
12845 || storage_class == sc_auto
12846 || storage_class == sc_extern
12847 || thread_p)
12848 storage_class = sc_none;
12851 else if (storage_class == sc_extern && funcdef_flag
12852 && ! toplevel_bindings_p ())
12853 error ("nested function %qs declared %<extern%>", name);
12854 else if (toplevel_bindings_p ())
12856 if (storage_class == sc_auto)
12857 error_at (declspecs->locations[ds_storage_class],
12858 "top-level declaration of %qs specifies %<auto%>", name);
12860 else if (thread_p
12861 && storage_class != sc_extern
12862 && storage_class != sc_static)
12864 if (declspecs->gnu_thread_keyword_p)
12865 pedwarn (declspecs->locations[ds_thread],
12866 0, "function-scope %qs implicitly auto and "
12867 "declared %<__thread%>", name);
12869 /* When thread_local is applied to a variable of block scope the
12870 storage-class-specifier static is implied if it does not appear
12871 explicitly. */
12872 storage_class = declspecs->storage_class = sc_static;
12873 staticp = 1;
12876 if (storage_class && friendp)
12878 error_at (min_location (declspecs->locations[ds_thread],
12879 declspecs->locations[ds_storage_class]),
12880 "storage class specifiers invalid in friend function "
12881 "declarations");
12882 storage_class = sc_none;
12883 staticp = 0;
12886 if (!id_declarator)
12887 unqualified_id = NULL_TREE;
12888 else
12890 unqualified_id = id_declarator->u.id.unqualified_name;
12891 switch (TREE_CODE (unqualified_id))
12893 case BIT_NOT_EXPR:
12894 unqualified_id = TREE_OPERAND (unqualified_id, 0);
12895 if (TYPE_P (unqualified_id))
12896 unqualified_id = constructor_name (unqualified_id);
12897 break;
12899 case IDENTIFIER_NODE:
12900 case TEMPLATE_ID_EXPR:
12901 break;
12903 default:
12904 gcc_unreachable ();
12908 if (declspecs->std_attributes
12909 && !diagnose_misapplied_contracts (declspecs->std_attributes))
12911 location_t attr_loc = declspecs->locations[ds_std_attribute];
12912 if (warning_at (attr_loc, OPT_Wattributes, "attribute ignored"))
12913 inform (attr_loc, "an attribute that appertains to a type-specifier "
12914 "is ignored");
12917 if (attrlist)
12918 diagnose_misapplied_contracts (*attrlist);
12920 /* Determine the type of the entity declared by recurring on the
12921 declarator. */
12922 for (; declarator; declarator = declarator->declarator)
12924 const cp_declarator *inner_declarator;
12925 tree attrs;
12927 if (type == error_mark_node)
12928 return error_mark_node;
12930 attrs = declarator->attributes;
12931 if (attrs)
12933 int attr_flags;
12935 attr_flags = 0;
12936 if (declarator->kind == cdk_id)
12937 attr_flags |= (int) ATTR_FLAG_DECL_NEXT;
12938 if (declarator->kind == cdk_function)
12939 attr_flags |= (int) ATTR_FLAG_FUNCTION_NEXT;
12940 if (declarator->kind == cdk_array)
12941 attr_flags |= (int) ATTR_FLAG_ARRAY_NEXT;
12942 tree late_attrs = NULL_TREE;
12943 if (decl_context != PARM && decl_context != TYPENAME)
12944 /* Assume that any attributes that get applied late to
12945 templates will DTRT when applied to the declaration
12946 as a whole. */
12947 late_attrs = splice_template_attributes (&attrs, type);
12948 returned_attrs = decl_attributes (&type,
12949 attr_chainon (returned_attrs,
12950 attrs),
12951 attr_flags);
12952 returned_attrs = attr_chainon (late_attrs, returned_attrs);
12955 inner_declarator = declarator->declarator;
12957 /* Check that contracts aren't misapplied. */
12958 if (tree contract_attr = find_contract (declarator->std_attributes))
12959 if (declarator->kind != cdk_function
12960 || innermost_code != cdk_function)
12961 diagnose_misapplied_contracts (contract_attr);
12963 /* We don't want to warn in parameter context because we don't
12964 yet know if the parse will succeed, and this might turn out
12965 to be a constructor call. */
12966 if (decl_context != PARM
12967 && decl_context != TYPENAME
12968 && !typedef_p
12969 && declarator->parenthesized != UNKNOWN_LOCATION
12970 /* If the type is class-like and the inner name used a
12971 global namespace qualifier, we need the parens.
12972 Unfortunately all we can tell is whether a qualified name
12973 was used or not. */
12974 && !(inner_declarator
12975 && inner_declarator->kind == cdk_id
12976 && inner_declarator->u.id.qualifying_scope
12977 && (MAYBE_CLASS_TYPE_P (type)
12978 || TREE_CODE (type) == ENUMERAL_TYPE)))
12980 if (warning_at (declarator->parenthesized, OPT_Wparentheses,
12981 "unnecessary parentheses in declaration of %qs",
12982 name))
12984 gcc_rich_location iloc (declarator->parenthesized);
12985 iloc.add_fixit_remove (get_start (declarator->parenthesized));
12986 iloc.add_fixit_remove (get_finish (declarator->parenthesized));
12987 inform (&iloc, "remove parentheses");
12990 if (declarator->kind == cdk_id || declarator->kind == cdk_decomp)
12991 break;
12993 switch (declarator->kind)
12995 case cdk_array:
12996 type = create_array_type_for_decl (dname, type,
12997 declarator->u.array.bounds,
12998 declarator->id_loc);
12999 if (!valid_array_size_p (dname
13000 ? declarator->id_loc : input_location,
13001 type, dname))
13002 type = error_mark_node;
13004 if (declarator->std_attributes)
13005 /* [dcl.array]/1:
13007 The optional attribute-specifier-seq appertains to the
13008 array. */
13009 returned_attrs = attr_chainon (returned_attrs,
13010 declarator->std_attributes);
13011 break;
13013 case cdk_function:
13015 tree arg_types;
13016 int funcdecl_p;
13018 /* Declaring a function type. */
13020 /* Pick up type qualifiers which should be applied to `this'. */
13021 memfn_quals = declarator->u.function.qualifiers;
13022 /* Pick up virt-specifiers. */
13023 virt_specifiers = declarator->u.function.virt_specifiers;
13024 /* And ref-qualifier, too */
13025 rqual = declarator->u.function.ref_qualifier;
13026 /* And tx-qualifier. */
13027 tree tx_qual = declarator->u.function.tx_qualifier;
13028 /* Pick up the exception specifications. */
13029 raises = declarator->u.function.exception_specification;
13030 /* If the exception-specification is ill-formed, let's pretend
13031 there wasn't one. */
13032 if (raises == error_mark_node)
13033 raises = NULL_TREE;
13035 if (reqs)
13036 error_at (location_of (reqs), "requires-clause on return type");
13037 reqs = declarator->u.function.requires_clause;
13039 /* Say it's a definition only for the CALL_EXPR
13040 closest to the identifier. */
13041 funcdecl_p = inner_declarator && inner_declarator->kind == cdk_id;
13043 /* Handle a late-specified return type. */
13044 tree late_return_type = declarator->u.function.late_return_type;
13045 if (tree auto_node = type_uses_auto (type))
13047 if (!late_return_type)
13049 if (!funcdecl_p)
13050 /* auto (*fp)() = f; is OK. */;
13051 else if (current_class_type
13052 && LAMBDA_TYPE_P (current_class_type))
13053 /* OK for C++11 lambdas. */;
13054 else if (cxx_dialect < cxx14)
13056 error_at (typespec_loc, "%qs function uses "
13057 "%<auto%> type specifier without "
13058 "trailing return type", name);
13059 inform (typespec_loc,
13060 "deduced return type only available "
13061 "with %<-std=c++14%> or %<-std=gnu++14%>");
13063 else if (virtualp)
13065 error_at (typespec_loc, "virtual function "
13066 "cannot have deduced return type");
13067 virtualp = false;
13070 else if (!is_auto (type) && sfk != sfk_conversion)
13072 error_at (typespec_loc, "%qs function with trailing "
13073 "return type has %qT as its type rather "
13074 "than plain %<auto%>", name, type);
13075 return error_mark_node;
13077 else if (is_auto (type) && AUTO_IS_DECLTYPE (type))
13079 if (funcdecl_p)
13080 error_at (typespec_loc,
13081 "%qs function with trailing return type "
13082 "has %<decltype(auto)%> as its type "
13083 "rather than plain %<auto%>", name);
13084 else
13085 error_at (typespec_loc,
13086 "invalid use of %<decltype(auto)%>");
13087 return error_mark_node;
13089 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node);
13090 if (!tmpl)
13091 if (tree late_auto = type_uses_auto (late_return_type))
13092 tmpl = CLASS_PLACEHOLDER_TEMPLATE (late_auto);
13093 if (tmpl)
13095 if (!funcdecl_p || !dguide_name_p (unqualified_id))
13097 auto_diagnostic_group g;
13098 error_at (typespec_loc, "deduced class "
13099 "type %qD in function return type",
13100 DECL_NAME (tmpl));
13101 inform (DECL_SOURCE_LOCATION (tmpl),
13102 "%qD declared here", tmpl);
13103 return error_mark_node;
13105 else if (!late_return_type)
13107 error_at (declarator->id_loc, "deduction guide "
13108 "for %qT must have trailing return "
13109 "type", TREE_TYPE (tmpl));
13110 inform (DECL_SOURCE_LOCATION (tmpl),
13111 "%qD declared here", tmpl);
13112 return error_mark_node;
13114 else if (CLASS_TYPE_P (late_return_type)
13115 && CLASSTYPE_TEMPLATE_INFO (late_return_type)
13116 && (CLASSTYPE_TI_TEMPLATE (late_return_type)
13117 == tmpl))
13118 /* OK */;
13119 else
13120 error ("trailing return type %qT of deduction guide "
13121 "is not a specialization of %qT",
13122 late_return_type, TREE_TYPE (tmpl));
13125 else if (late_return_type
13126 && sfk != sfk_conversion)
13128 if (late_return_type == error_mark_node)
13129 return error_mark_node;
13130 if (cxx_dialect < cxx11)
13131 /* Not using maybe_warn_cpp0x because this should
13132 always be an error. */
13133 error_at (typespec_loc,
13134 "trailing return type only available "
13135 "with %<-std=c++11%> or %<-std=gnu++11%>");
13136 else
13137 error_at (typespec_loc, "%qs function with trailing "
13138 "return type not declared with %<auto%> "
13139 "type specifier", name);
13140 return error_mark_node;
13142 if (late_return_type && sfk == sfk_conversion)
13144 error ("a conversion function cannot have a trailing return type");
13145 return error_mark_node;
13147 type = splice_late_return_type (type, late_return_type);
13148 if (type == error_mark_node)
13149 return error_mark_node;
13151 if (late_return_type)
13153 late_return_type_p = true;
13154 type_quals = cp_type_quals (type);
13157 if (type_quals != TYPE_UNQUALIFIED)
13159 /* It's wrong, for instance, to issue a -Wignored-qualifiers
13160 warning for
13161 static_assert(!is_same_v<void(*)(), const void(*)()>);
13162 because there the qualifier matters. */
13163 if (funcdecl_p && (SCALAR_TYPE_P (type) || VOID_TYPE_P (type)))
13164 warning_at (typespec_loc, OPT_Wignored_qualifiers, "type "
13165 "qualifiers ignored on function return type");
13166 /* [dcl.fct] "A volatile-qualified return type is
13167 deprecated." */
13168 if (type_quals & TYPE_QUAL_VOLATILE)
13169 warning_at (typespec_loc, OPT_Wvolatile,
13170 "%<volatile%>-qualified return type is "
13171 "deprecated");
13173 /* We now know that the TYPE_QUALS don't apply to the
13174 decl, but to its return type. */
13175 type_quals = TYPE_UNQUALIFIED;
13178 /* Error about some types functions can't return. */
13180 if (TREE_CODE (type) == FUNCTION_TYPE)
13182 error_at (typespec_loc, "%qs declared as function returning "
13183 "a function", name);
13184 return error_mark_node;
13186 if (TREE_CODE (type) == ARRAY_TYPE)
13188 error_at (typespec_loc, "%qs declared as function returning "
13189 "an array", name);
13190 return error_mark_node;
13192 if (constinit_p && funcdecl_p)
13194 error_at (declspecs->locations[ds_constinit],
13195 "%<constinit%> on function return type is not "
13196 "allowed");
13197 return error_mark_node;
13200 if (check_decltype_auto (typespec_loc, type))
13201 return error_mark_node;
13203 if (ctype == NULL_TREE
13204 && decl_context == FIELD
13205 && funcdecl_p
13206 && friendp == 0)
13207 ctype = current_class_type;
13209 if (ctype && (sfk == sfk_constructor
13210 || sfk == sfk_destructor))
13212 /* We are within a class's scope. If our declarator name
13213 is the same as the class name, and we are defining
13214 a function, then it is a constructor/destructor, and
13215 therefore returns a void type. */
13217 /* ISO C++ 12.4/2. A destructor may not be declared
13218 const or volatile. A destructor may not be static.
13219 A destructor may not be declared with ref-qualifier.
13221 ISO C++ 12.1. A constructor may not be declared
13222 const or volatile. A constructor may not be
13223 virtual. A constructor may not be static.
13224 A constructor may not be declared with ref-qualifier. */
13225 if (staticp == 2)
13226 error_at (declspecs->locations[ds_storage_class],
13227 (flags == DTOR_FLAG)
13228 ? G_("destructor cannot be static member "
13229 "function")
13230 : G_("constructor cannot be static member "
13231 "function"));
13232 if (memfn_quals)
13234 error ((flags == DTOR_FLAG)
13235 ? G_("destructors may not be cv-qualified")
13236 : G_("constructors may not be cv-qualified"));
13237 memfn_quals = TYPE_UNQUALIFIED;
13240 if (rqual)
13242 maybe_warn_cpp0x (CPP0X_REF_QUALIFIER);
13243 error ((flags == DTOR_FLAG)
13244 ? G_("destructors may not be ref-qualified")
13245 : G_("constructors may not be ref-qualified"));
13246 rqual = REF_QUAL_NONE;
13249 if (decl_context == FIELD
13250 && !member_function_or_else (ctype,
13251 current_class_type,
13252 flags))
13253 return error_mark_node;
13255 if (flags != DTOR_FLAG)
13257 /* It's a constructor. */
13258 if (explicitp == 1)
13259 explicitp = 2;
13260 if (virtualp)
13262 permerror (declspecs->locations[ds_virtual],
13263 "constructors cannot be declared %<virtual%>");
13264 virtualp = 0;
13266 if (decl_context == FIELD
13267 && sfk != sfk_constructor)
13268 return error_mark_node;
13270 if (decl_context == FIELD)
13271 staticp = 0;
13273 else if (friendp)
13275 if (virtualp)
13277 /* Cannot be both friend and virtual. */
13278 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
13279 richloc.add_range (declspecs->locations[ds_friend]);
13280 error_at (&richloc, "virtual functions cannot be friends");
13281 friendp = 0;
13283 if (decl_context == NORMAL)
13284 error_at (declarator->id_loc,
13285 "friend declaration not in class definition");
13286 if (current_function_decl && funcdef_flag)
13288 error_at (declarator->id_loc,
13289 "cannot define friend function %qs in a local "
13290 "class definition", name);
13291 friendp = 0;
13293 /* [class.friend]/6: A function can be defined in a friend
13294 declaration if the function name is unqualified. */
13295 if (funcdef_flag && in_namespace)
13297 if (in_namespace == global_namespace)
13298 error_at (declarator->id_loc,
13299 "friend function definition %qs cannot have "
13300 "a name qualified with %<::%>", name);
13301 else
13302 error_at (declarator->id_loc,
13303 "friend function definition %qs cannot have "
13304 "a name qualified with %<%D::%>", name,
13305 in_namespace);
13308 else if (ctype && sfk == sfk_conversion)
13310 if (explicitp == 1)
13312 maybe_warn_cpp0x (CPP0X_EXPLICIT_CONVERSION);
13313 explicitp = 2;
13316 else if (sfk == sfk_deduction_guide)
13318 if (explicitp == 1)
13319 explicitp = 2;
13322 tree pushed_scope = NULL_TREE;
13323 if (funcdecl_p
13324 && decl_context != FIELD
13325 && inner_declarator->u.id.qualifying_scope
13326 && CLASS_TYPE_P (inner_declarator->u.id.qualifying_scope))
13327 pushed_scope
13328 = push_scope (inner_declarator->u.id.qualifying_scope);
13330 arg_types = grokparms (declarator->u.function.parameters, &parms);
13332 if (pushed_scope)
13333 pop_scope (pushed_scope);
13335 if (inner_declarator
13336 && inner_declarator->kind == cdk_id
13337 && inner_declarator->u.id.sfk == sfk_destructor
13338 && arg_types != void_list_node)
13340 error_at (declarator->id_loc,
13341 "destructors may not have parameters");
13342 arg_types = void_list_node;
13343 parms = NULL_TREE;
13346 type = build_function_type (type, arg_types);
13348 tree attrs = declarator->std_attributes;
13349 if (tx_qual)
13351 tree att = build_tree_list (tx_qual, NULL_TREE);
13352 /* transaction_safe applies to the type, but
13353 transaction_safe_dynamic applies to the function. */
13354 if (is_attribute_p ("transaction_safe", tx_qual))
13355 attrs = attr_chainon (attrs, att);
13356 else
13357 returned_attrs = attr_chainon (returned_attrs, att);
13360 /* Actually apply the contract attributes to the declaration. */
13361 for (tree *p = &attrs; *p;)
13363 tree l = *p;
13364 if (cxx_contract_attribute_p (l))
13366 *p = TREE_CHAIN (l);
13367 /* Intentionally reverse order of contracts so they're
13368 reversed back into their lexical order. */
13369 TREE_CHAIN (l) = NULL_TREE;
13370 returned_attrs = chainon (l, returned_attrs);
13372 else
13373 p = &TREE_CHAIN (l);
13376 if (attrs)
13377 /* [dcl.fct]/2:
13379 The optional attribute-specifier-seq appertains to
13380 the function type. */
13381 cplus_decl_attributes (&type, attrs, 0);
13383 if (raises)
13384 type = build_exception_variant (type, raises);
13386 break;
13388 case cdk_pointer:
13389 case cdk_reference:
13390 case cdk_ptrmem:
13391 /* Filter out pointers-to-references and references-to-references.
13392 We can get these if a TYPE_DECL is used. */
13394 if (TYPE_REF_P (type))
13396 if (declarator->kind != cdk_reference)
13398 error ("cannot declare pointer to %q#T", type);
13399 type = TREE_TYPE (type);
13402 /* In C++0x, we allow reference to reference declarations
13403 that occur indirectly through typedefs [7.1.3/8 dcl.typedef]
13404 and template type arguments [14.3.1/4 temp.arg.type]. The
13405 check for direct reference to reference declarations, which
13406 are still forbidden, occurs below. Reasoning behind the change
13407 can be found in DR106, DR540, and the rvalue reference
13408 proposals. */
13409 else if (cxx_dialect == cxx98)
13411 error ("cannot declare reference to %q#T", type);
13412 type = TREE_TYPE (type);
13415 else if (VOID_TYPE_P (type))
13417 if (declarator->kind == cdk_reference)
13418 error ("cannot declare reference to %q#T", type);
13419 else if (declarator->kind == cdk_ptrmem)
13420 error ("cannot declare pointer to %q#T member", type);
13423 /* We now know that the TYPE_QUALS don't apply to the decl,
13424 but to the target of the pointer. */
13425 type_quals = TYPE_UNQUALIFIED;
13427 /* This code used to handle METHOD_TYPE, but I don't think it's
13428 possible to get it here anymore. */
13429 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
13430 if (declarator->kind == cdk_ptrmem
13431 && TREE_CODE (type) == FUNCTION_TYPE)
13433 memfn_quals |= type_memfn_quals (type);
13434 type = build_memfn_type (type,
13435 declarator->u.pointer.class_type,
13436 memfn_quals,
13437 rqual);
13438 if (type == error_mark_node)
13439 return error_mark_node;
13441 rqual = REF_QUAL_NONE;
13442 memfn_quals = TYPE_UNQUALIFIED;
13445 if (TREE_CODE (type) == FUNCTION_TYPE
13446 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
13447 || type_memfn_rqual (type) != REF_QUAL_NONE))
13448 error (declarator->kind == cdk_reference
13449 ? G_("cannot declare reference to qualified function type %qT")
13450 : G_("cannot declare pointer to qualified function type %qT"),
13451 type);
13453 /* When the pointed-to type involves components of variable size,
13454 care must be taken to ensure that the size evaluation code is
13455 emitted early enough to dominate all the possible later uses
13456 and late enough for the variables on which it depends to have
13457 been assigned.
13459 This is expected to happen automatically when the pointed-to
13460 type has a name/declaration of it's own, but special attention
13461 is required if the type is anonymous.
13463 We handle the NORMAL and FIELD contexts here by inserting a
13464 dummy statement that just evaluates the size at a safe point
13465 and ensures it is not deferred until e.g. within a deeper
13466 conditional context (c++/43555).
13468 We expect nothing to be needed here for PARM or TYPENAME.
13469 Evaluating the size at this point for TYPENAME would
13470 actually be incorrect, as we might be in the middle of an
13471 expression with side effects on the pointed-to type size
13472 "arguments" prior to the pointer declaration point and the
13473 size evaluation could end up prior to the side effects. */
13475 if (!TYPE_NAME (type)
13476 && (decl_context == NORMAL || decl_context == FIELD)
13477 && at_function_scope_p ()
13478 && variably_modified_type_p (type, NULL_TREE))
13480 TYPE_NAME (type) = build_decl (UNKNOWN_LOCATION, TYPE_DECL,
13481 NULL_TREE, type);
13482 add_decl_expr (TYPE_NAME (type));
13485 if (declarator->kind == cdk_reference)
13487 /* In C++0x, the type we are creating a reference to might be
13488 a typedef which is itself a reference type. In that case,
13489 we follow the reference collapsing rules in
13490 [7.1.3/8 dcl.typedef] to create the final reference type:
13492 "If a typedef TD names a type that is a reference to a type
13493 T, an attempt to create the type 'lvalue reference to cv TD'
13494 creates the type 'lvalue reference to T,' while an attempt
13495 to create the type "rvalue reference to cv TD' creates the
13496 type TD."
13498 if (VOID_TYPE_P (type))
13499 /* We already gave an error. */;
13500 else if (TYPE_REF_P (type))
13502 if (declarator->u.reference.rvalue_ref)
13503 /* Leave type alone. */;
13504 else
13505 type = cp_build_reference_type (TREE_TYPE (type), false);
13507 else
13508 type = cp_build_reference_type
13509 (type, declarator->u.reference.rvalue_ref);
13511 /* In C++0x, we need this check for direct reference to
13512 reference declarations, which are forbidden by
13513 [8.3.2/5 dcl.ref]. Reference to reference declarations
13514 are only allowed indirectly through typedefs and template
13515 type arguments. Example:
13517 void foo(int & &); // invalid ref-to-ref decl
13519 typedef int & int_ref;
13520 void foo(int_ref &); // valid ref-to-ref decl
13522 if (inner_declarator && inner_declarator->kind == cdk_reference)
13523 error ("cannot declare reference to %q#T, which is not "
13524 "a typedef or a template type argument", type);
13526 else if (TREE_CODE (type) == METHOD_TYPE)
13527 type = build_ptrmemfunc_type (build_pointer_type (type));
13528 else if (declarator->kind == cdk_ptrmem)
13530 gcc_assert (TREE_CODE (declarator->u.pointer.class_type)
13531 != NAMESPACE_DECL);
13532 if (declarator->u.pointer.class_type == error_mark_node)
13533 /* We will already have complained. */
13534 type = error_mark_node;
13535 else
13536 type = build_ptrmem_type (declarator->u.pointer.class_type,
13537 type);
13539 else
13540 type = build_pointer_type (type);
13542 /* Process a list of type modifier keywords (such as
13543 const or volatile) that were given inside the `*' or `&'. */
13545 if (declarator->u.pointer.qualifiers)
13547 type
13548 = cp_build_qualified_type (type,
13549 declarator->u.pointer.qualifiers);
13550 type_quals = cp_type_quals (type);
13553 /* Apply C++11 attributes to the pointer, and not to the
13554 type pointed to. This is unlike what is done for GNU
13555 attributes above. It is to comply with [dcl.ptr]/1:
13557 [the optional attribute-specifier-seq (7.6.1) appertains
13558 to the pointer and not to the object pointed to]. */
13559 if (declarator->std_attributes)
13560 decl_attributes (&type, declarator->std_attributes,
13563 ctype = NULL_TREE;
13564 break;
13566 case cdk_error:
13567 break;
13569 default:
13570 gcc_unreachable ();
13574 id_loc = declarator ? declarator->id_loc : input_location;
13576 if (innermost_code != cdk_function
13577 /* Don't check this if it can be the artifical decltype(auto)
13578 we created when building a constraint in a compound-requirement:
13579 that the type-constraint is plain is going to be checked in
13580 cp_parser_compound_requirement. */
13581 && decl_context != TYPENAME
13582 && check_decltype_auto (id_loc, type))
13583 return error_mark_node;
13585 /* A `constexpr' specifier used in an object declaration declares
13586 the object as `const'. */
13587 if (constexpr_p && innermost_code != cdk_function)
13589 /* DR1688 says that a `constexpr' specifier in combination with
13590 `volatile' is valid. */
13592 if (!TYPE_REF_P (type))
13594 type_quals |= TYPE_QUAL_CONST;
13595 type = cp_build_qualified_type (type, type_quals);
13599 if (unqualified_id && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR
13600 && !FUNC_OR_METHOD_TYPE_P (type)
13601 && !variable_template_p (TREE_OPERAND (unqualified_id, 0)))
13603 error ("template-id %qD used as a declarator",
13604 unqualified_id);
13605 unqualified_id = dname;
13608 /* If TYPE is a FUNCTION_TYPE, but the function name was explicitly
13609 qualified with a class-name, turn it into a METHOD_TYPE, unless
13610 we know that the function is static. We take advantage of this
13611 opportunity to do other processing that pertains to entities
13612 explicitly declared to be class members. Note that if DECLARATOR
13613 is non-NULL, we know it is a cdk_id declarator; otherwise, we
13614 would not have exited the loop above. */
13615 if (declarator
13616 && declarator->kind == cdk_id
13617 && declarator->u.id.qualifying_scope
13618 && MAYBE_CLASS_TYPE_P (declarator->u.id.qualifying_scope))
13620 ctype = declarator->u.id.qualifying_scope;
13621 ctype = TYPE_MAIN_VARIANT (ctype);
13622 template_count = num_template_headers_for_class (ctype);
13624 if (ctype == current_class_type)
13626 if (friendp)
13628 permerror (declspecs->locations[ds_friend],
13629 "member functions are implicitly "
13630 "friends of their class");
13631 friendp = 0;
13633 else
13634 permerror (id_loc, "extra qualification %<%T::%> on member %qs",
13635 ctype, name);
13637 else if (/* If the qualifying type is already complete, then we
13638 can skip the following checks. */
13639 !COMPLETE_TYPE_P (ctype)
13640 && (/* If the function is being defined, then
13641 qualifying type must certainly be complete. */
13642 funcdef_flag
13643 /* A friend declaration of "T::f" is OK, even if
13644 "T" is a template parameter. But, if this
13645 function is not a friend, the qualifying type
13646 must be a class. */
13647 || (!friendp && !CLASS_TYPE_P (ctype))
13648 /* For a declaration, the type need not be
13649 complete, if either it is dependent (since there
13650 is no meaningful definition of complete in that
13651 case) or the qualifying class is currently being
13652 defined. */
13653 || !(dependent_type_p (ctype)
13654 || currently_open_class (ctype)))
13655 /* Check that the qualifying type is complete. */
13656 && !complete_type_or_else (ctype, NULL_TREE))
13657 return error_mark_node;
13658 else if (TREE_CODE (type) == FUNCTION_TYPE)
13660 if (current_class_type
13661 && (!friendp || funcdef_flag || initialized))
13663 error_at (id_loc, funcdef_flag || initialized
13664 ? G_("cannot define member function %<%T::%s%> "
13665 "within %qT")
13666 : G_("cannot declare member function %<%T::%s%> "
13667 "within %qT"),
13668 ctype, name, current_class_type);
13669 return error_mark_node;
13672 else if (typedef_p && current_class_type)
13674 error_at (id_loc, "cannot declare member %<%T::%s%> within %qT",
13675 ctype, name, current_class_type);
13676 return error_mark_node;
13680 if (ctype == NULL_TREE && decl_context == FIELD && friendp == 0)
13681 ctype = current_class_type;
13683 /* Now TYPE has the actual type. */
13685 if (returned_attrs)
13687 if (attrlist)
13688 *attrlist = attr_chainon (returned_attrs, *attrlist);
13689 else
13690 attrlist = &returned_attrs;
13693 if (declarator
13694 && declarator->kind == cdk_id
13695 && declarator->std_attributes
13696 && attrlist != NULL)
13698 /* [dcl.meaning]/1: The optional attribute-specifier-seq following
13699 a declarator-id appertains to the entity that is declared. */
13700 if (declarator->std_attributes != error_mark_node)
13701 *attrlist = attr_chainon (declarator->std_attributes, *attrlist);
13702 else
13703 /* We should have already diagnosed the issue (c++/78344). */
13704 gcc_assert (seen_error ());
13707 /* Handle parameter packs. */
13708 if (parameter_pack_p)
13710 if (decl_context == PARM)
13711 /* Turn the type into a pack expansion.*/
13712 type = make_pack_expansion (type);
13713 else
13714 error ("non-parameter %qs cannot be a parameter pack", name);
13717 if ((decl_context == FIELD || decl_context == PARM)
13718 && !processing_template_decl
13719 && variably_modified_type_p (type, NULL_TREE))
13721 if (decl_context == FIELD)
13722 error_at (id_loc,
13723 "data member may not have variably modified type %qT", type);
13724 else
13725 error_at (id_loc,
13726 "parameter may not have variably modified type %qT", type);
13727 type = error_mark_node;
13730 if (explicitp == 1 || (explicitp && friendp))
13732 /* [dcl.fct.spec] (C++11) The explicit specifier shall be used only
13733 in the declaration of a constructor or conversion function within
13734 a class definition. */
13735 if (!current_class_type)
13736 error_at (declspecs->locations[ds_explicit],
13737 "%<explicit%> outside class declaration");
13738 else if (friendp)
13739 error_at (declspecs->locations[ds_explicit],
13740 "%<explicit%> in friend declaration");
13741 else
13742 error_at (declspecs->locations[ds_explicit],
13743 "only declarations of constructors and conversion operators "
13744 "can be %<explicit%>");
13745 explicitp = 0;
13748 if (storage_class == sc_mutable)
13750 location_t sloc = declspecs->locations[ds_storage_class];
13751 if (decl_context != FIELD || friendp)
13753 error_at (sloc, "non-member %qs cannot be declared %<mutable%>",
13754 name);
13755 storage_class = sc_none;
13757 else if (decl_context == TYPENAME || typedef_p)
13759 error_at (sloc,
13760 "non-object member %qs cannot be declared %<mutable%>",
13761 name);
13762 storage_class = sc_none;
13764 else if (FUNC_OR_METHOD_TYPE_P (type))
13766 error_at (sloc, "function %qs cannot be declared %<mutable%>",
13767 name);
13768 storage_class = sc_none;
13770 else if (staticp)
13772 error_at (sloc, "%<static%> %qs cannot be declared %<mutable%>",
13773 name);
13774 storage_class = sc_none;
13776 else if (type_quals & TYPE_QUAL_CONST)
13778 error_at (sloc, "%<const%> %qs cannot be declared %<mutable%>",
13779 name);
13780 storage_class = sc_none;
13782 else if (TYPE_REF_P (type))
13784 permerror (sloc, "reference %qs cannot be declared %<mutable%>",
13785 name);
13786 storage_class = sc_none;
13790 /* If this is declaring a typedef name, return a TYPE_DECL. */
13791 if (typedef_p && decl_context != TYPENAME)
13793 bool alias_p = decl_spec_seq_has_spec_p (declspecs, ds_alias);
13794 tree decl;
13796 if (funcdef_flag)
13798 if (decl_context == NORMAL)
13799 error_at (id_loc,
13800 "typedef may not be a function definition");
13801 else
13802 error_at (id_loc,
13803 "typedef may not be a member function definition");
13804 return error_mark_node;
13807 /* This declaration:
13809 typedef void f(int) const;
13811 declares a function type which is not a member of any
13812 particular class, but which is cv-qualified; for
13813 example "f S::*" declares a pointer to a const-qualified
13814 member function of S. We record the cv-qualification in the
13815 function type. */
13816 if ((rqual || memfn_quals) && TREE_CODE (type) == FUNCTION_TYPE)
13818 type = apply_memfn_quals (type, memfn_quals, rqual);
13820 /* We have now dealt with these qualifiers. */
13821 memfn_quals = TYPE_UNQUALIFIED;
13822 rqual = REF_QUAL_NONE;
13825 if (type_uses_auto (type))
13827 if (alias_p)
13828 error_at (declspecs->locations[ds_type_spec],
13829 "%<auto%> not allowed in alias declaration");
13830 else
13831 error_at (declspecs->locations[ds_type_spec],
13832 "typedef declared %<auto%>");
13833 type = error_mark_node;
13836 if (reqs)
13837 error_at (location_of (reqs), "requires-clause on typedef");
13839 if (id_declarator && declarator->u.id.qualifying_scope)
13841 error_at (id_loc, "typedef name may not be a nested-name-specifier");
13842 type = error_mark_node;
13845 if (decl_context == FIELD)
13846 decl = build_lang_decl_loc (id_loc, TYPE_DECL, unqualified_id, type);
13847 else
13848 decl = build_decl (id_loc, TYPE_DECL, unqualified_id, type);
13850 if (decl_context != FIELD)
13852 if (!current_function_decl)
13853 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
13854 else if (DECL_MAYBE_IN_CHARGE_CDTOR_P (current_function_decl))
13855 /* The TYPE_DECL is "abstract" because there will be
13856 clones of this constructor/destructor, and there will
13857 be copies of this TYPE_DECL generated in those
13858 clones. The decloning optimization (for space) may
13859 revert this subsequently if it determines that
13860 the clones should share a common implementation. */
13861 DECL_ABSTRACT_P (decl) = true;
13863 set_originating_module (decl);
13865 else if (current_class_type
13866 && constructor_name_p (unqualified_id, current_class_type))
13867 permerror (id_loc, "ISO C++ forbids nested type %qD with same name "
13868 "as enclosing class",
13869 unqualified_id);
13871 /* If the user declares "typedef struct {...} foo" then the
13872 struct will have an anonymous name. Fill that name in now.
13873 Nothing can refer to it, so nothing needs know about the name
13874 change. */
13875 if (type != error_mark_node
13876 && unqualified_id
13877 && TYPE_NAME (type)
13878 && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL
13879 && TYPE_UNNAMED_P (type)
13880 && declspecs->type_definition_p
13881 && attributes_naming_typedef_ok (*attrlist)
13882 && cp_type_quals (type) == TYPE_UNQUALIFIED)
13883 name_unnamed_type (type, decl);
13885 if (signed_p
13886 || (typedef_decl && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl)))
13887 C_TYPEDEF_EXPLICITLY_SIGNED (decl) = 1;
13889 bad_specifiers (decl, BSP_TYPE, virtualp,
13890 memfn_quals != TYPE_UNQUALIFIED,
13891 inlinep, friendp, raises != NULL_TREE,
13892 declspecs->locations);
13894 if (alias_p)
13895 /* Acknowledge that this was written:
13896 `using analias = atype;'. */
13897 TYPE_DECL_ALIAS_P (decl) = 1;
13899 return decl;
13902 /* Detect the case of an array type of unspecified size
13903 which came, as such, direct from a typedef name.
13904 We must copy the type, so that the array's domain can be
13905 individually set by the object's initializer. */
13907 if (type && typedef_type
13908 && TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type)
13909 && TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (typedef_type))
13910 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
13912 /* Detect where we're using a typedef of function type to declare a
13913 function. PARMS will not be set, so we must create it now. */
13915 if (type == typedef_type && TREE_CODE (type) == FUNCTION_TYPE)
13917 tree decls = NULL_TREE;
13918 tree args;
13920 for (args = TYPE_ARG_TYPES (type);
13921 args && args != void_list_node;
13922 args = TREE_CHAIN (args))
13924 tree decl = cp_build_parm_decl (NULL_TREE, NULL_TREE,
13925 TREE_VALUE (args));
13927 DECL_CHAIN (decl) = decls;
13928 decls = decl;
13931 parms = nreverse (decls);
13933 if (decl_context != TYPENAME)
13935 /* The qualifiers on the function type become the qualifiers on
13936 the non-static member function. */
13937 memfn_quals |= type_memfn_quals (type);
13938 rqual = type_memfn_rqual (type);
13939 type_quals = TYPE_UNQUALIFIED;
13940 raises = TYPE_RAISES_EXCEPTIONS (type);
13944 /* If this is a type name (such as, in a cast or sizeof),
13945 compute the type and return it now. */
13947 if (decl_context == TYPENAME)
13949 /* Note that here we don't care about type_quals. */
13951 /* Special case: "friend class foo" looks like a TYPENAME context. */
13952 if (friendp)
13954 if (inlinep)
13956 error ("%<inline%> specified for friend class declaration");
13957 inlinep = 0;
13960 if (!current_aggr)
13962 /* Don't allow friend declaration without a class-key. */
13963 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
13964 permerror (input_location, "template parameters cannot be friends");
13965 else if (TREE_CODE (type) == TYPENAME_TYPE)
13966 permerror (input_location, "friend declaration requires class-key, "
13967 "i.e. %<friend class %T::%D%>",
13968 TYPE_CONTEXT (type), TYPENAME_TYPE_FULLNAME (type));
13969 else
13970 permerror (input_location, "friend declaration requires class-key, "
13971 "i.e. %<friend %#T%>",
13972 type);
13975 /* Only try to do this stuff if we didn't already give up. */
13976 if (type != integer_type_node)
13978 /* A friendly class? */
13979 if (current_class_type)
13980 make_friend_class (current_class_type, TYPE_MAIN_VARIANT (type),
13981 /*complain=*/true);
13982 else
13983 error ("trying to make class %qT a friend of global scope",
13984 type);
13986 type = void_type_node;
13989 else if (memfn_quals || rqual)
13991 if (ctype == NULL_TREE
13992 && TREE_CODE (type) == METHOD_TYPE)
13993 ctype = TYPE_METHOD_BASETYPE (type);
13995 if (ctype)
13996 type = build_memfn_type (type, ctype, memfn_quals, rqual);
13997 /* Core issue #547: need to allow this in template type args.
13998 Allow it in general in C++11 for alias-declarations. */
13999 else if ((template_type_arg || cxx_dialect >= cxx11)
14000 && TREE_CODE (type) == FUNCTION_TYPE)
14001 type = apply_memfn_quals (type, memfn_quals, rqual);
14002 else
14003 error ("invalid qualifiers on non-member function type");
14006 if (reqs)
14007 error_at (location_of (reqs), "requires-clause on type-id");
14009 return type;
14011 else if (unqualified_id == NULL_TREE && decl_context != PARM
14012 && decl_context != CATCHPARM
14013 && TREE_CODE (type) != UNION_TYPE
14014 && ! bitfield
14015 && innermost_code != cdk_decomp)
14017 error ("abstract declarator %qT used as declaration", type);
14018 return error_mark_node;
14021 if (!FUNC_OR_METHOD_TYPE_P (type))
14023 /* Only functions may be declared using an operator-function-id. */
14024 if (dname && IDENTIFIER_ANY_OP_P (dname))
14026 error_at (id_loc, "declaration of %qD as non-function", dname);
14027 return error_mark_node;
14030 if (reqs)
14031 error_at (location_of (reqs),
14032 "requires-clause on declaration of non-function type %qT",
14033 type);
14036 /* We don't check parameter types here because we can emit a better
14037 error message later. */
14038 if (decl_context != PARM)
14040 type = check_var_type (unqualified_id, type, id_loc);
14041 if (type == error_mark_node)
14042 return error_mark_node;
14045 /* Now create the decl, which may be a VAR_DECL, a PARM_DECL
14046 or a FUNCTION_DECL, depending on DECL_CONTEXT and TYPE. */
14048 if (decl_context == PARM || decl_context == CATCHPARM)
14050 if (ctype || in_namespace)
14051 error ("cannot use %<::%> in parameter declaration");
14053 tree auto_node = type_uses_auto (type);
14054 if (auto_node && !(cxx_dialect >= cxx17 && template_parm_flag))
14056 if (cxx_dialect >= cxx14)
14058 if (decl_context == PARM && AUTO_IS_DECLTYPE (auto_node))
14059 error_at (typespec_loc,
14060 "cannot declare a parameter with %<decltype(auto)%>");
14061 else if (tree c = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14063 auto_diagnostic_group g;
14064 gcc_rich_location richloc (typespec_loc);
14065 richloc.add_fixit_insert_after ("<>");
14066 error_at (&richloc,
14067 "missing template argument list after %qE; template "
14068 "placeholder not permitted in parameter", c);
14069 if (decl_context == PARM && cxx_dialect >= cxx20)
14070 inform (typespec_loc, "or use %<auto%> for an "
14071 "abbreviated function template");
14072 inform (DECL_SOURCE_LOCATION (c), "%qD declared here", c);
14074 else
14075 error_at (typespec_loc,
14076 "%<auto%> parameter not permitted in this context");
14078 else
14079 error_at (typespec_loc, "parameter declared %<auto%>");
14080 type = error_mark_node;
14083 /* A parameter declared as an array of T is really a pointer to T.
14084 One declared as a function is really a pointer to a function.
14085 One declared as a member is really a pointer to member. */
14087 if (TREE_CODE (type) == ARRAY_TYPE)
14089 /* Transfer const-ness of array into that of type pointed to. */
14090 type = build_pointer_type (TREE_TYPE (type));
14091 type_quals = TYPE_UNQUALIFIED;
14092 array_parameter_p = true;
14094 else if (TREE_CODE (type) == FUNCTION_TYPE)
14095 type = build_pointer_type (type);
14098 if (ctype && TREE_CODE (type) == FUNCTION_TYPE && staticp < 2
14099 && !(unqualified_id
14100 && identifier_p (unqualified_id)
14101 && IDENTIFIER_NEWDEL_OP_P (unqualified_id)))
14103 cp_cv_quals real_quals = memfn_quals;
14104 if (cxx_dialect < cxx14 && constexpr_p
14105 && sfk != sfk_constructor && sfk != sfk_destructor)
14106 real_quals |= TYPE_QUAL_CONST;
14107 type = build_memfn_type (type, ctype, real_quals, rqual);
14111 tree decl = NULL_TREE;
14113 if (decl_context == PARM)
14115 decl = cp_build_parm_decl (NULL_TREE, unqualified_id, type);
14116 DECL_ARRAY_PARAMETER_P (decl) = array_parameter_p;
14118 bad_specifiers (decl, BSP_PARM, virtualp,
14119 memfn_quals != TYPE_UNQUALIFIED,
14120 inlinep, friendp, raises != NULL_TREE,
14121 declspecs->locations);
14123 else if (decl_context == FIELD)
14125 if (!staticp && !friendp && !FUNC_OR_METHOD_TYPE_P (type))
14126 if (tree auto_node = type_uses_auto (type))
14128 location_t tloc = declspecs->locations[ds_type_spec];
14129 if (CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14130 error_at (tloc, "invalid use of template-name %qE without an "
14131 "argument list",
14132 CLASS_PLACEHOLDER_TEMPLATE (auto_node));
14133 else
14134 error_at (tloc, "non-static data member declared with "
14135 "placeholder %qT", auto_node);
14136 type = error_mark_node;
14139 /* The C99 flexible array extension. */
14140 if (!staticp && TREE_CODE (type) == ARRAY_TYPE
14141 && TYPE_DOMAIN (type) == NULL_TREE)
14143 if (ctype
14144 && (TREE_CODE (ctype) == UNION_TYPE
14145 || TREE_CODE (ctype) == QUAL_UNION_TYPE))
14147 error_at (id_loc, "flexible array member in union");
14148 type = error_mark_node;
14150 else
14152 /* Array is a flexible member. */
14153 if (name)
14154 pedwarn (id_loc, OPT_Wpedantic,
14155 "ISO C++ forbids flexible array member %qs", name);
14156 else
14157 pedwarn (input_location, OPT_Wpedantic,
14158 "ISO C++ forbids flexible array members");
14160 /* Flexible array member has a null domain. */
14161 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
14165 if (type == error_mark_node)
14167 /* Happens when declaring arrays of sizes which
14168 are error_mark_node, for example. */
14169 decl = NULL_TREE;
14171 else if (in_namespace && !friendp)
14173 /* Something like struct S { int N::j; }; */
14174 error_at (id_loc, "invalid use of %<::%>");
14175 return error_mark_node;
14177 else if (FUNC_OR_METHOD_TYPE_P (type) && unqualified_id)
14179 int publicp = 0;
14180 tree function_context;
14182 if (friendp == 0)
14184 /* This should never happen in pure C++ (the check
14185 could be an assert). It could happen in
14186 Objective-C++ if someone writes invalid code that
14187 uses a function declaration for an instance
14188 variable or property (instance variables and
14189 properties are parsed as FIELD_DECLs, but they are
14190 part of an Objective-C class, not a C++ class).
14191 That code is invalid and is caught by this
14192 check. */
14193 if (!ctype)
14195 error ("declaration of function %qD in invalid context",
14196 unqualified_id);
14197 return error_mark_node;
14200 /* ``A union may [ ... ] not [ have ] virtual functions.''
14201 ARM 9.5 */
14202 if (virtualp && TREE_CODE (ctype) == UNION_TYPE)
14204 error_at (declspecs->locations[ds_virtual],
14205 "function %qD declared %<virtual%> inside a union",
14206 unqualified_id);
14207 return error_mark_node;
14210 if (virtualp
14211 && identifier_p (unqualified_id)
14212 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14214 error_at (declspecs->locations[ds_virtual],
14215 "%qD cannot be declared %<virtual%>, since it "
14216 "is always static", unqualified_id);
14217 virtualp = 0;
14221 /* Check that the name used for a destructor makes sense. */
14222 if (sfk == sfk_destructor)
14224 tree uqname = id_declarator->u.id.unqualified_name;
14226 if (!ctype)
14228 gcc_assert (friendp);
14229 error_at (id_loc, "expected qualified name in friend "
14230 "declaration for destructor %qD", uqname);
14231 return error_mark_node;
14234 if (!check_dtor_name (ctype, TREE_OPERAND (uqname, 0)))
14236 error_at (id_loc, "declaration of %qD as member of %qT",
14237 uqname, ctype);
14238 return error_mark_node;
14240 if (concept_p)
14242 error_at (declspecs->locations[ds_concept],
14243 "a destructor cannot be %qs", "concept");
14244 return error_mark_node;
14246 if (constexpr_p && cxx_dialect < cxx20)
14248 error_at (declspecs->locations[ds_constexpr],
14249 "%<constexpr%> destructors only available"
14250 " with %<-std=c++20%> or %<-std=gnu++20%>");
14251 return error_mark_node;
14253 if (consteval_p)
14255 error_at (declspecs->locations[ds_consteval],
14256 "a destructor cannot be %qs", "consteval");
14257 return error_mark_node;
14260 else if (sfk == sfk_constructor && friendp && !ctype)
14262 error ("expected qualified name in friend declaration "
14263 "for constructor %qD",
14264 id_declarator->u.id.unqualified_name);
14265 return error_mark_node;
14267 if (sfk == sfk_constructor)
14268 if (concept_p)
14270 error_at (declspecs->locations[ds_concept],
14271 "a constructor cannot be %<concept%>");
14272 return error_mark_node;
14274 if (concept_p)
14276 error_at (declspecs->locations[ds_concept],
14277 "a concept cannot be a member function");
14278 concept_p = false;
14280 else if (consteval_p
14281 && identifier_p (unqualified_id)
14282 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14284 error_at (declspecs->locations[ds_consteval],
14285 "%qD cannot be %qs", unqualified_id, "consteval");
14286 consteval_p = false;
14289 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14291 tree tmpl = TREE_OPERAND (unqualified_id, 0);
14292 if (variable_template_p (tmpl))
14294 error_at (id_loc, "specialization of variable template "
14295 "%qD declared as function", tmpl);
14296 inform (DECL_SOURCE_LOCATION (tmpl),
14297 "variable template declared here");
14298 return error_mark_node;
14302 /* Tell grokfndecl if it needs to set TREE_PUBLIC on the node. */
14303 function_context
14304 = (ctype != NULL_TREE
14305 ? decl_function_context (TYPE_MAIN_DECL (ctype)) : NULL_TREE);
14306 publicp = ((! friendp || ! staticp)
14307 && function_context == NULL_TREE);
14309 decl = grokfndecl (ctype, type,
14310 TREE_CODE (unqualified_id) != TEMPLATE_ID_EXPR
14311 ? unqualified_id : dname,
14312 parms,
14313 unqualified_id,
14314 declspecs,
14315 reqs,
14316 virtualp, flags, memfn_quals, rqual, raises,
14317 friendp ? -1 : 0, friendp, publicp,
14318 inlinep | (2 * constexpr_p) | (4 * concept_p)
14319 | (8 * consteval_p),
14320 initialized == SD_DELETED, sfk,
14321 funcdef_flag, late_return_type_p,
14322 template_count, in_namespace,
14323 attrlist, id_loc);
14324 decl = set_virt_specifiers (decl, virt_specifiers);
14325 if (decl == NULL_TREE)
14326 return error_mark_node;
14327 #if 0
14328 /* This clobbers the attrs stored in `decl' from `attrlist'. */
14329 /* The decl and setting of decl_attr is also turned off. */
14330 decl = build_decl_attribute_variant (decl, decl_attr);
14331 #endif
14333 /* [class.conv.ctor]
14335 A constructor declared without the function-specifier
14336 explicit that can be called with a single parameter
14337 specifies a conversion from the type of its first
14338 parameter to the type of its class. Such a constructor
14339 is called a converting constructor. */
14340 if (explicitp == 2)
14341 DECL_NONCONVERTING_P (decl) = 1;
14343 if (declspecs->explicit_specifier)
14344 store_explicit_specifier (decl, declspecs->explicit_specifier);
14346 else if (!staticp
14347 && ((current_class_type
14348 && same_type_p (type, current_class_type))
14349 || (!dependent_type_p (type)
14350 && !COMPLETE_TYPE_P (complete_type (type))
14351 && (!complete_or_array_type_p (type)
14352 || initialized == SD_UNINITIALIZED))))
14354 if (TREE_CODE (type) != ARRAY_TYPE
14355 || !COMPLETE_TYPE_P (TREE_TYPE (type)))
14357 if (unqualified_id)
14359 error_at (id_loc, "field %qD has incomplete type %qT",
14360 unqualified_id, type);
14361 cxx_incomplete_type_inform (strip_array_types (type));
14363 else
14364 error ("name %qT has incomplete type", type);
14366 type = error_mark_node;
14367 decl = NULL_TREE;
14370 else if (!verify_type_context (input_location,
14371 staticp
14372 ? TCTX_STATIC_STORAGE
14373 : TCTX_FIELD, type))
14375 type = error_mark_node;
14376 decl = NULL_TREE;
14378 else
14380 if (friendp)
14382 if (unqualified_id)
14383 error_at (id_loc,
14384 "%qE is neither function nor member function; "
14385 "cannot be declared friend", unqualified_id);
14386 else
14387 error ("unnamed field is neither function nor member "
14388 "function; cannot be declared friend");
14389 return error_mark_node;
14391 decl = NULL_TREE;
14394 if (friendp)
14396 /* Packages tend to use GNU attributes on friends, so we only
14397 warn for standard attributes. */
14398 if (attrlist
14399 && !funcdef_flag
14400 && cxx11_attribute_p (*attrlist)
14401 && !all_attributes_are_contracts_p (*attrlist))
14403 *attrlist = NULL_TREE;
14404 if (warning_at (id_loc, OPT_Wattributes, "attribute ignored"))
14405 inform (id_loc, "an attribute that appertains to a friend "
14406 "declaration that is not a definition is ignored");
14408 /* Friends are treated specially. */
14409 if (ctype == current_class_type)
14410 ; /* We already issued a permerror. */
14411 else if (decl && DECL_NAME (decl))
14413 set_originating_module (decl, true);
14415 if (initialized)
14416 /* Kludge: We need funcdef_flag to be true in do_friend for
14417 in-class defaulted functions, but that breaks grokfndecl.
14418 So set it here. */
14419 funcdef_flag = true;
14421 cplus_decl_attributes (&decl, *attrlist, 0);
14422 *attrlist = NULL_TREE;
14424 tree scope = ctype ? ctype : in_namespace;
14425 decl = do_friend (scope, unqualified_id, decl,
14426 flags, funcdef_flag);
14427 return decl;
14429 else
14430 return error_mark_node;
14433 /* Structure field. It may not be a function, except for C++. */
14435 if (decl == NULL_TREE)
14437 if (staticp)
14439 /* C++ allows static class members. All other work
14440 for this is done by grokfield. */
14441 decl = build_lang_decl_loc (id_loc, VAR_DECL,
14442 unqualified_id, type);
14443 set_linkage_for_static_data_member (decl);
14444 if (concept_p)
14445 error_at (declspecs->locations[ds_concept],
14446 "static data member %qE declared %qs",
14447 unqualified_id, "concept");
14448 else if (constexpr_p && !initialized)
14450 error_at (DECL_SOURCE_LOCATION (decl),
14451 "%<constexpr%> static data member %qD must "
14452 "have an initializer", decl);
14453 constexpr_p = false;
14455 if (consteval_p)
14456 error_at (declspecs->locations[ds_consteval],
14457 "static data member %qE declared %qs",
14458 unqualified_id, "consteval");
14460 if (inlinep)
14461 mark_inline_variable (decl, declspecs->locations[ds_inline]);
14463 if (!DECL_VAR_DECLARED_INLINE_P (decl)
14464 && !(cxx_dialect >= cxx17 && constexpr_p))
14465 /* Even if there is an in-class initialization, DECL
14466 is considered undefined until an out-of-class
14467 definition is provided, unless this is an inline
14468 variable. */
14469 DECL_EXTERNAL (decl) = 1;
14471 if (thread_p)
14473 CP_DECL_THREAD_LOCAL_P (decl) = true;
14474 if (!processing_template_decl)
14475 set_decl_tls_model (decl, decl_default_tls_model (decl));
14476 if (declspecs->gnu_thread_keyword_p)
14477 SET_DECL_GNU_TLS_P (decl);
14480 /* Set the constraints on the declaration. */
14481 bool memtmpl = (current_template_depth
14482 > template_class_depth (current_class_type));
14483 if (memtmpl)
14485 tree ci = current_template_constraints ();
14486 set_constraints (decl, ci);
14489 else
14491 if (concept_p)
14493 error_at (declspecs->locations[ds_concept],
14494 "non-static data member %qE declared %qs",
14495 unqualified_id, "concept");
14496 concept_p = false;
14497 constexpr_p = false;
14499 else if (constexpr_p)
14501 error_at (declspecs->locations[ds_constexpr],
14502 "non-static data member %qE declared %qs",
14503 unqualified_id, "constexpr");
14504 constexpr_p = false;
14506 if (constinit_p)
14508 error_at (declspecs->locations[ds_constinit],
14509 "non-static data member %qE declared %qs",
14510 unqualified_id, "constinit");
14511 constinit_p = false;
14513 if (consteval_p)
14515 error_at (declspecs->locations[ds_consteval],
14516 "non-static data member %qE declared %qs",
14517 unqualified_id, "consteval");
14518 consteval_p = false;
14520 decl = build_decl (id_loc, FIELD_DECL, unqualified_id, type);
14521 DECL_NONADDRESSABLE_P (decl) = bitfield;
14522 if (bitfield && !unqualified_id)
14523 DECL_PADDING_P (decl) = 1;
14525 if (storage_class == sc_mutable)
14527 DECL_MUTABLE_P (decl) = 1;
14528 storage_class = sc_none;
14531 if (initialized)
14533 /* An attempt is being made to initialize a non-static
14534 member. This is new in C++11. */
14535 maybe_warn_cpp0x (CPP0X_NSDMI, init_loc);
14537 /* If this has been parsed with static storage class, but
14538 errors forced staticp to be cleared, ensure NSDMI is
14539 not present. */
14540 if (declspecs->storage_class == sc_static)
14541 DECL_INITIAL (decl) = error_mark_node;
14545 bad_specifiers (decl, BSP_FIELD, virtualp,
14546 memfn_quals != TYPE_UNQUALIFIED,
14547 staticp ? false : inlinep, friendp,
14548 raises != NULL_TREE,
14549 declspecs->locations);
14552 else if (FUNC_OR_METHOD_TYPE_P (type))
14554 tree original_name;
14555 int publicp = 0;
14557 if (!unqualified_id)
14558 return error_mark_node;
14560 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14561 original_name = dname;
14562 else
14563 original_name = unqualified_id;
14564 // FIXME:gcc_assert (original_name == dname);
14566 if (storage_class == sc_auto)
14567 error_at (declspecs->locations[ds_storage_class],
14568 "storage class %<auto%> invalid for function %qs", name);
14569 else if (storage_class == sc_register)
14570 error_at (declspecs->locations[ds_storage_class],
14571 "storage class %<register%> invalid for function %qs",
14572 name);
14573 else if (thread_p)
14575 if (declspecs->gnu_thread_keyword_p)
14576 error_at (declspecs->locations[ds_thread],
14577 "storage class %<__thread%> invalid for function %qs",
14578 name);
14579 else
14580 error_at (declspecs->locations[ds_thread],
14581 "storage class %<thread_local%> invalid for "
14582 "function %qs", name);
14585 if (virt_specifiers)
14586 error ("virt-specifiers in %qs not allowed outside a class "
14587 "definition", name);
14588 /* Function declaration not at top level.
14589 Storage classes other than `extern' are not allowed
14590 and `extern' makes no difference. */
14591 if (! toplevel_bindings_p ()
14592 && (storage_class == sc_static
14593 || decl_spec_seq_has_spec_p (declspecs, ds_inline))
14594 && pedantic)
14596 if (storage_class == sc_static)
14597 pedwarn (declspecs->locations[ds_storage_class], OPT_Wpedantic,
14598 "%<static%> specifier invalid for function %qs "
14599 "declared out of global scope", name);
14600 else
14601 pedwarn (declspecs->locations[ds_inline], OPT_Wpedantic,
14602 "%<inline%> specifier invalid for function %qs "
14603 "declared out of global scope", name);
14606 if (ctype == NULL_TREE)
14608 if (virtualp)
14610 error ("virtual non-class function %qs", name);
14611 virtualp = 0;
14613 else if (sfk == sfk_constructor
14614 || sfk == sfk_destructor)
14616 error (funcdef_flag
14617 ? G_("%qs defined in a non-class scope")
14618 : G_("%qs declared in a non-class scope"), name);
14619 sfk = sfk_none;
14622 if (consteval_p
14623 && identifier_p (unqualified_id)
14624 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14626 error_at (declspecs->locations[ds_consteval],
14627 "%qD cannot be %qs", unqualified_id, "consteval");
14628 consteval_p = false;
14631 /* Record whether the function is public. */
14632 publicp = (ctype != NULL_TREE
14633 || storage_class != sc_static);
14635 decl = grokfndecl (ctype, type, original_name, parms, unqualified_id,
14636 declspecs,
14637 reqs, virtualp, flags, memfn_quals, rqual, raises,
14638 1, friendp,
14639 publicp,
14640 inlinep | (2 * constexpr_p) | (4 * concept_p)
14641 | (8 * consteval_p),
14642 initialized == SD_DELETED,
14643 sfk,
14644 funcdef_flag,
14645 late_return_type_p,
14646 template_count, in_namespace, attrlist,
14647 id_loc);
14648 if (decl == NULL_TREE)
14649 return error_mark_node;
14651 if (explicitp == 2)
14652 DECL_NONCONVERTING_P (decl) = 1;
14653 if (staticp == 1)
14655 int invalid_static = 0;
14657 /* Don't allow a static member function in a class, and forbid
14658 declaring main to be static. */
14659 if (TREE_CODE (type) == METHOD_TYPE)
14661 permerror (input_location, "cannot declare member function %qD to have "
14662 "static linkage", decl);
14663 invalid_static = 1;
14665 else if (current_function_decl)
14667 /* 7.1.1: There can be no static function declarations within a
14668 block. */
14669 error_at (declspecs->locations[ds_storage_class],
14670 "cannot declare static function inside another function");
14671 invalid_static = 1;
14674 if (invalid_static)
14676 staticp = 0;
14677 storage_class = sc_none;
14680 if (declspecs->explicit_specifier)
14681 store_explicit_specifier (decl, declspecs->explicit_specifier);
14683 else
14685 /* It's a variable. */
14687 /* An uninitialized decl with `extern' is a reference. */
14688 decl = grokvardecl (type, dname, unqualified_id,
14689 declspecs,
14690 initialized,
14691 type_quals,
14692 inlinep,
14693 concept_p,
14694 template_count,
14695 ctype ? ctype : in_namespace,
14696 id_loc);
14697 if (decl == NULL_TREE)
14698 return error_mark_node;
14700 bad_specifiers (decl, BSP_VAR, virtualp,
14701 memfn_quals != TYPE_UNQUALIFIED,
14702 inlinep, friendp, raises != NULL_TREE,
14703 declspecs->locations);
14705 if (ctype)
14707 DECL_CONTEXT (decl) = ctype;
14708 if (staticp == 1)
14710 permerror (declspecs->locations[ds_storage_class],
14711 "%<static%> may not be used when defining "
14712 "(as opposed to declaring) a static data member");
14713 staticp = 0;
14714 storage_class = sc_none;
14716 if (storage_class == sc_register && TREE_STATIC (decl))
14718 error ("static member %qD declared %<register%>", decl);
14719 storage_class = sc_none;
14721 if (storage_class == sc_extern && pedantic)
14723 pedwarn (input_location, OPT_Wpedantic,
14724 "cannot explicitly declare member %q#D to have "
14725 "extern linkage", decl);
14726 storage_class = sc_none;
14729 else if (constexpr_p && DECL_EXTERNAL (decl))
14731 error_at (DECL_SOURCE_LOCATION (decl),
14732 "declaration of %<constexpr%> variable %qD "
14733 "is not a definition", decl);
14734 constexpr_p = false;
14736 if (consteval_p)
14738 error_at (DECL_SOURCE_LOCATION (decl),
14739 "a variable cannot be declared %<consteval%>");
14740 consteval_p = false;
14743 if (inlinep)
14744 mark_inline_variable (decl, declspecs->locations[ds_inline]);
14745 if (innermost_code == cdk_decomp)
14747 gcc_assert (declarator && declarator->kind == cdk_decomp);
14748 DECL_SOURCE_LOCATION (decl) = id_loc;
14749 DECL_ARTIFICIAL (decl) = 1;
14750 fit_decomposition_lang_decl (decl, NULL_TREE);
14754 if (VAR_P (decl) && !initialized)
14755 if (tree auto_node = type_uses_auto (type))
14756 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14758 location_t loc = declspecs->locations[ds_type_spec];
14759 error_at (loc, "declaration of %q#D has no initializer", decl);
14760 TREE_TYPE (decl) = error_mark_node;
14763 if (storage_class == sc_extern && initialized && !funcdef_flag)
14765 if (toplevel_bindings_p ())
14767 /* It's common practice (and completely valid) to have a const
14768 be initialized and declared extern. */
14769 if (!(type_quals & TYPE_QUAL_CONST))
14770 warning_at (DECL_SOURCE_LOCATION (decl), 0,
14771 "%qs initialized and declared %<extern%>", name);
14773 else
14775 error_at (DECL_SOURCE_LOCATION (decl),
14776 "%qs has both %<extern%> and initializer", name);
14777 return error_mark_node;
14781 /* Record `register' declaration for warnings on &
14782 and in case doing stupid register allocation. */
14784 if (storage_class == sc_register)
14786 DECL_REGISTER (decl) = 1;
14787 /* Warn about register storage specifiers on PARM_DECLs. */
14788 if (TREE_CODE (decl) == PARM_DECL)
14790 if (cxx_dialect >= cxx17)
14791 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
14792 "ISO C++17 does not allow %<register%> storage "
14793 "class specifier");
14794 else
14795 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
14796 "%<register%> storage class specifier used");
14799 else if (storage_class == sc_extern)
14800 DECL_THIS_EXTERN (decl) = 1;
14801 else if (storage_class == sc_static)
14802 DECL_THIS_STATIC (decl) = 1;
14804 if (VAR_P (decl))
14806 /* Set constexpr flag on vars (functions got it in grokfndecl). */
14807 if (constexpr_p)
14808 DECL_DECLARED_CONSTEXPR_P (decl) = true;
14809 /* And the constinit flag (which only applies to variables). */
14810 else if (constinit_p)
14811 DECL_DECLARED_CONSTINIT_P (decl) = true;
14813 else if (TREE_CODE (decl) == FUNCTION_DECL)
14815 /* If we saw a return type, record its location. */
14816 location_t loc = declspecs->locations[ds_type_spec];
14817 if (loc == UNKNOWN_LOCATION)
14818 /* Build DECL_RESULT in start_preparsed_function. */;
14819 else if (!DECL_RESULT (decl))
14821 tree restype = TREE_TYPE (TREE_TYPE (decl));
14822 tree resdecl = build_decl (loc, RESULT_DECL, 0, restype);
14823 DECL_ARTIFICIAL (resdecl) = 1;
14824 DECL_IGNORED_P (resdecl) = 1;
14825 DECL_RESULT (decl) = resdecl;
14827 else if (funcdef_flag)
14828 DECL_SOURCE_LOCATION (DECL_RESULT (decl)) = loc;
14831 /* Record constancy and volatility on the DECL itself . There's
14832 no need to do this when processing a template; we'll do this
14833 for the instantiated declaration based on the type of DECL. */
14834 if (!processing_template_decl)
14835 cp_apply_type_quals_to_decl (type_quals, decl);
14837 return decl;
14841 /* Subroutine of start_function. Ensure that each of the parameter
14842 types (as listed in PARMS) is complete, as is required for a
14843 function definition. */
14845 static void
14846 require_complete_types_for_parms (tree parms)
14848 for (; parms; parms = DECL_CHAIN (parms))
14850 if (dependent_type_p (TREE_TYPE (parms)))
14851 continue;
14852 if (!VOID_TYPE_P (TREE_TYPE (parms))
14853 && complete_type_or_else (TREE_TYPE (parms), parms))
14855 relayout_decl (parms);
14856 DECL_ARG_TYPE (parms) = type_passed_as (TREE_TYPE (parms));
14858 abstract_virtuals_error (parms, TREE_TYPE (parms));
14859 maybe_warn_parm_abi (TREE_TYPE (parms),
14860 DECL_SOURCE_LOCATION (parms));
14862 else
14863 /* grokparms or complete_type_or_else will have already issued
14864 an error. */
14865 TREE_TYPE (parms) = error_mark_node;
14869 /* Returns nonzero if T is a local variable. */
14872 local_variable_p (const_tree t)
14874 if ((VAR_P (t)
14875 && (DECL_LOCAL_DECL_P (t)
14876 || !DECL_CONTEXT (t)
14877 || TREE_CODE (DECL_CONTEXT (t)) == FUNCTION_DECL))
14878 || (TREE_CODE (t) == PARM_DECL))
14879 return 1;
14881 return 0;
14884 /* Like local_variable_p, but suitable for use as a tree-walking
14885 function. */
14887 static tree
14888 local_variable_p_walkfn (tree *tp, int *walk_subtrees,
14889 void * /*data*/)
14891 if (unevaluated_p (TREE_CODE (*tp)))
14893 /* DR 2082 permits local variables in unevaluated contexts
14894 within a default argument. */
14895 *walk_subtrees = 0;
14896 return NULL_TREE;
14899 if (local_variable_p (*tp)
14900 && (!DECL_ARTIFICIAL (*tp) || DECL_NAME (*tp) == this_identifier))
14901 return *tp;
14902 else if (TYPE_P (*tp))
14903 *walk_subtrees = 0;
14905 return NULL_TREE;
14908 /* Check that ARG, which is a default-argument expression for a
14909 parameter DECL, is valid. Returns ARG, or ERROR_MARK_NODE, if
14910 something goes wrong. DECL may also be a _TYPE node, rather than a
14911 DECL, if there is no DECL available. */
14913 tree
14914 check_default_argument (tree decl, tree arg, tsubst_flags_t complain)
14916 tree var;
14917 tree decl_type;
14919 if (TREE_CODE (arg) == DEFERRED_PARSE)
14920 /* We get a DEFERRED_PARSE when looking at an in-class declaration
14921 with a default argument. Ignore the argument for now; we'll
14922 deal with it after the class is complete. */
14923 return arg;
14925 if (TYPE_P (decl))
14927 decl_type = decl;
14928 decl = NULL_TREE;
14930 else
14931 decl_type = TREE_TYPE (decl);
14933 if (arg == error_mark_node
14934 || decl == error_mark_node
14935 || TREE_TYPE (arg) == error_mark_node
14936 || decl_type == error_mark_node)
14937 /* Something already went wrong. There's no need to check
14938 further. */
14939 return error_mark_node;
14941 /* [dcl.fct.default]
14943 A default argument expression is implicitly converted to the
14944 parameter type. */
14945 ++cp_unevaluated_operand;
14946 /* Avoid digest_init clobbering the initializer. */
14947 tree carg = BRACE_ENCLOSED_INITIALIZER_P (arg) ? unshare_expr (arg): arg;
14948 perform_implicit_conversion_flags (decl_type, carg, complain,
14949 LOOKUP_IMPLICIT);
14950 --cp_unevaluated_operand;
14952 /* Avoid redundant -Wzero-as-null-pointer-constant warnings at
14953 the call sites. */
14954 if (TYPE_PTR_OR_PTRMEM_P (decl_type)
14955 && null_ptr_cst_p (arg)
14956 /* Don't lose side-effects as in PR90473. */
14957 && !TREE_SIDE_EFFECTS (arg))
14958 return nullptr_node;
14960 /* [dcl.fct.default]
14962 Local variables shall not be used in default argument
14963 expressions.
14965 The keyword `this' shall not be used in a default argument of a
14966 member function. */
14967 var = cp_walk_tree_without_duplicates (&arg, local_variable_p_walkfn, NULL);
14968 if (var)
14970 if (complain & tf_warning_or_error)
14972 if (DECL_NAME (var) == this_identifier)
14973 permerror (input_location, "default argument %qE uses %qD",
14974 arg, var);
14975 else
14976 error ("default argument %qE uses local variable %qD", arg, var);
14978 return error_mark_node;
14981 /* All is well. */
14982 return arg;
14985 /* Returns a deprecated type used within TYPE, or NULL_TREE if none. */
14987 static tree
14988 type_is_deprecated (tree type)
14990 enum tree_code code;
14991 if (TREE_DEPRECATED (type))
14992 return type;
14993 if (TYPE_NAME (type))
14995 if (TREE_DEPRECATED (TYPE_NAME (type)))
14996 return type;
14997 else
14999 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
15000 return NULL_TREE;
15004 /* Do warn about using typedefs to a deprecated class. */
15005 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
15006 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
15008 code = TREE_CODE (type);
15010 if (code == POINTER_TYPE || code == REFERENCE_TYPE
15011 || code == OFFSET_TYPE || code == FUNCTION_TYPE
15012 || code == METHOD_TYPE || code == ARRAY_TYPE)
15013 return type_is_deprecated (TREE_TYPE (type));
15015 if (TYPE_PTRMEMFUNC_P (type))
15016 return type_is_deprecated
15017 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
15019 return NULL_TREE;
15022 /* Returns an unavailable type used within TYPE, or NULL_TREE if none. */
15024 static tree
15025 type_is_unavailable (tree type)
15027 enum tree_code code;
15028 if (TREE_UNAVAILABLE (type))
15029 return type;
15030 if (TYPE_NAME (type))
15032 if (TREE_UNAVAILABLE (TYPE_NAME (type)))
15033 return type;
15034 else
15036 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
15037 return NULL_TREE;
15041 /* Do warn about using typedefs to a deprecated class. */
15042 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
15043 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
15045 code = TREE_CODE (type);
15047 if (code == POINTER_TYPE || code == REFERENCE_TYPE
15048 || code == OFFSET_TYPE || code == FUNCTION_TYPE
15049 || code == METHOD_TYPE || code == ARRAY_TYPE)
15050 return type_is_unavailable (TREE_TYPE (type));
15052 if (TYPE_PTRMEMFUNC_P (type))
15053 return type_is_unavailable
15054 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
15056 return NULL_TREE;
15059 /* Decode the list of parameter types for a function type.
15060 Given the list of things declared inside the parens,
15061 return a list of types.
15063 If this parameter does not end with an ellipsis, we append
15064 void_list_node.
15066 *PARMS is set to the chain of PARM_DECLs created. */
15068 tree
15069 grokparms (tree parmlist, tree *parms)
15071 tree result = NULL_TREE;
15072 tree decls = NULL_TREE;
15073 tree parm;
15074 int any_error = 0;
15076 for (parm = parmlist; parm != NULL_TREE; parm = TREE_CHAIN (parm))
15078 tree type = NULL_TREE;
15079 tree init = TREE_PURPOSE (parm);
15080 tree decl = TREE_VALUE (parm);
15082 if (parm == void_list_node || parm == explicit_void_list_node)
15083 break;
15085 if (! decl || TREE_TYPE (decl) == error_mark_node)
15087 any_error = 1;
15088 continue;
15091 type = TREE_TYPE (decl);
15092 if (VOID_TYPE_P (type))
15094 if (same_type_p (type, void_type_node)
15095 && !init
15096 && !DECL_NAME (decl) && !result
15097 && TREE_CHAIN (parm) == void_list_node)
15098 /* DR 577: A parameter list consisting of a single
15099 unnamed parameter of non-dependent type 'void'. */
15100 break;
15101 else if (cv_qualified_p (type))
15102 error_at (DECL_SOURCE_LOCATION (decl),
15103 "invalid use of cv-qualified type %qT in "
15104 "parameter declaration", type);
15105 else
15106 error_at (DECL_SOURCE_LOCATION (decl),
15107 "invalid use of type %<void%> in parameter "
15108 "declaration");
15109 /* It's not a good idea to actually create parameters of
15110 type `void'; other parts of the compiler assume that a
15111 void type terminates the parameter list. */
15112 type = error_mark_node;
15113 TREE_TYPE (decl) = error_mark_node;
15116 if (type != error_mark_node)
15118 if (deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
15120 tree unavailtype = type_is_unavailable (type);
15121 if (unavailtype)
15122 cp_handle_deprecated_or_unavailable (unavailtype);
15124 if (deprecated_state != DEPRECATED_SUPPRESS
15125 && deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
15127 tree deptype = type_is_deprecated (type);
15128 if (deptype)
15129 cp_handle_deprecated_or_unavailable (deptype);
15132 /* [dcl.fct] "A parameter with volatile-qualified type is
15133 deprecated." */
15134 if (CP_TYPE_VOLATILE_P (type))
15135 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wvolatile,
15136 "%<volatile%>-qualified parameter is "
15137 "deprecated");
15139 /* Top-level qualifiers on the parameters are
15140 ignored for function types. */
15141 type = cp_build_qualified_type (type, 0);
15142 if (TREE_CODE (type) == METHOD_TYPE)
15144 error ("parameter %qD invalidly declared method type", decl);
15145 type = build_pointer_type (type);
15146 TREE_TYPE (decl) = type;
15148 else if (cxx_dialect < cxx17 && INDIRECT_TYPE_P (type))
15150 /* Before C++17 DR 393:
15151 [dcl.fct]/6, parameter types cannot contain pointers
15152 (references) to arrays of unknown bound. */
15153 tree t = TREE_TYPE (type);
15154 int ptr = TYPE_PTR_P (type);
15156 while (1)
15158 if (TYPE_PTR_P (t))
15159 ptr = 1;
15160 else if (TREE_CODE (t) != ARRAY_TYPE)
15161 break;
15162 else if (!TYPE_DOMAIN (t))
15163 break;
15164 t = TREE_TYPE (t);
15166 if (TREE_CODE (t) == ARRAY_TYPE)
15167 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
15169 ? G_("parameter %qD includes pointer to array of "
15170 "unknown bound %qT")
15171 : G_("parameter %qD includes reference to array of "
15172 "unknown bound %qT"),
15173 decl, t);
15176 if (init && !processing_template_decl)
15177 init = check_default_argument (decl, init, tf_warning_or_error);
15180 DECL_CHAIN (decl) = decls;
15181 decls = decl;
15182 result = tree_cons (init, type, result);
15184 decls = nreverse (decls);
15185 result = nreverse (result);
15186 if (parm)
15187 result = chainon (result, void_list_node);
15188 *parms = decls;
15189 if (any_error)
15190 result = NULL_TREE;
15192 if (any_error)
15193 /* We had parm errors, recover by giving the function (...) type. */
15194 result = NULL_TREE;
15196 return result;
15200 /* D is a constructor or overloaded `operator='.
15202 Let T be the class in which D is declared. Then, this function
15203 returns:
15205 -1 if D's is an ill-formed constructor or copy assignment operator
15206 whose first parameter is of type `T'.
15207 0 if D is not a copy constructor or copy assignment
15208 operator.
15209 1 if D is a copy constructor or copy assignment operator whose
15210 first parameter is a reference to non-const qualified T.
15211 2 if D is a copy constructor or copy assignment operator whose
15212 first parameter is a reference to const qualified T.
15214 This function can be used as a predicate. Positive values indicate
15215 a copy constructor and nonzero values indicate a copy assignment
15216 operator. */
15219 copy_fn_p (const_tree d)
15221 tree args;
15222 tree arg_type;
15223 int result = 1;
15225 gcc_assert (DECL_FUNCTION_MEMBER_P (d));
15227 if (TREE_CODE (d) == TEMPLATE_DECL
15228 || (DECL_TEMPLATE_INFO (d)
15229 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
15230 /* Instantiations of template member functions are never copy
15231 functions. Note that member functions of templated classes are
15232 represented as template functions internally, and we must
15233 accept those as copy functions. */
15234 return 0;
15236 if (!DECL_CONSTRUCTOR_P (d)
15237 && DECL_NAME (d) != assign_op_identifier)
15238 return 0;
15240 args = FUNCTION_FIRST_USER_PARMTYPE (d);
15241 if (!args)
15242 return 0;
15244 arg_type = TREE_VALUE (args);
15245 if (arg_type == error_mark_node)
15246 return 0;
15248 if (TYPE_MAIN_VARIANT (arg_type) == DECL_CONTEXT (d))
15250 /* Pass by value copy assignment operator. */
15251 result = -1;
15253 else if (TYPE_REF_P (arg_type)
15254 && !TYPE_REF_IS_RVALUE (arg_type)
15255 && TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)) == DECL_CONTEXT (d))
15257 if (CP_TYPE_CONST_P (TREE_TYPE (arg_type)))
15258 result = 2;
15260 else
15261 return 0;
15263 args = TREE_CHAIN (args);
15265 if (args && args != void_list_node && !TREE_PURPOSE (args))
15266 /* There are more non-optional args. */
15267 return 0;
15269 return result;
15272 /* D is a constructor or overloaded `operator='.
15274 Let T be the class in which D is declared. Then, this function
15275 returns true when D is a move constructor or move assignment
15276 operator, false otherwise. */
15278 bool
15279 move_fn_p (const_tree d)
15281 if (cxx_dialect == cxx98)
15282 /* There are no move constructors if we are in C++98 mode. */
15283 return false;
15285 if (TREE_CODE (d) == TEMPLATE_DECL
15286 || (DECL_TEMPLATE_INFO (d)
15287 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
15288 /* Instantiations of template member functions are never move
15289 functions. Note that member functions of templated classes are
15290 represented as template functions internally, and we must
15291 accept those as move functions. */
15292 return 0;
15294 return move_signature_fn_p (d);
15297 /* D is a constructor or overloaded `operator='.
15299 Then, this function returns true when D has the same signature as a move
15300 constructor or move assignment operator (because either it is such a
15301 ctor/op= or it is a template specialization with the same signature),
15302 false otherwise. */
15304 bool
15305 move_signature_fn_p (const_tree d)
15307 tree args;
15308 tree arg_type;
15309 bool result = false;
15311 if (!DECL_CONSTRUCTOR_P (d)
15312 && DECL_NAME (d) != assign_op_identifier)
15313 return 0;
15315 args = FUNCTION_FIRST_USER_PARMTYPE (d);
15316 if (!args)
15317 return 0;
15319 arg_type = TREE_VALUE (args);
15320 if (arg_type == error_mark_node)
15321 return 0;
15323 if (TYPE_REF_P (arg_type)
15324 && TYPE_REF_IS_RVALUE (arg_type)
15325 && same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)),
15326 DECL_CONTEXT (d)))
15327 result = true;
15329 args = TREE_CHAIN (args);
15331 if (args && args != void_list_node && !TREE_PURPOSE (args))
15332 /* There are more non-optional args. */
15333 return false;
15335 return result;
15338 /* Remember any special properties of member function DECL. */
15340 void
15341 grok_special_member_properties (tree decl)
15343 tree class_type;
15345 if (TREE_CODE (decl) == USING_DECL
15346 || !DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
15347 return;
15349 class_type = DECL_CONTEXT (decl);
15350 if (IDENTIFIER_CTOR_P (DECL_NAME (decl)))
15352 int ctor = copy_fn_p (decl);
15354 if (!DECL_ARTIFICIAL (decl))
15355 TYPE_HAS_USER_CONSTRUCTOR (class_type) = 1;
15357 if (ctor > 0)
15359 /* [class.copy]
15361 A non-template constructor for class X is a copy
15362 constructor if its first parameter is of type X&, const
15363 X&, volatile X& or const volatile X&, and either there
15364 are no other parameters or else all other parameters have
15365 default arguments. */
15366 TYPE_HAS_COPY_CTOR (class_type) = 1;
15367 if (ctor > 1)
15368 TYPE_HAS_CONST_COPY_CTOR (class_type) = 1;
15371 if (sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (decl)))
15372 TYPE_HAS_DEFAULT_CONSTRUCTOR (class_type) = 1;
15374 if (is_list_ctor (decl))
15375 TYPE_HAS_LIST_CTOR (class_type) = 1;
15377 if (maybe_constexpr_fn (decl)
15378 && !ctor && !move_fn_p (decl))
15379 TYPE_HAS_CONSTEXPR_CTOR (class_type) = 1;
15381 else if (DECL_NAME (decl) == assign_op_identifier)
15383 /* [class.copy]
15385 A non-template assignment operator for class X is a copy
15386 assignment operator if its parameter is of type X, X&, const
15387 X&, volatile X& or const volatile X&. */
15389 int assop = copy_fn_p (decl);
15391 if (assop)
15393 TYPE_HAS_COPY_ASSIGN (class_type) = 1;
15394 if (assop != 1)
15395 TYPE_HAS_CONST_COPY_ASSIGN (class_type) = 1;
15398 else if (IDENTIFIER_CONV_OP_P (DECL_NAME (decl)))
15399 TYPE_HAS_CONVERSION (class_type) = true;
15401 /* Destructors are handled in check_methods. */
15404 /* Check a constructor DECL has the correct form. Complains
15405 if the class has a constructor of the form X(X). */
15407 bool
15408 grok_ctor_properties (const_tree ctype, const_tree decl)
15410 int ctor_parm = copy_fn_p (decl);
15412 if (ctor_parm < 0)
15414 /* [class.copy]
15416 A declaration of a constructor for a class X is ill-formed if
15417 its first parameter is of type (optionally cv-qualified) X
15418 and either there are no other parameters or else all other
15419 parameters have default arguments.
15421 We *don't* complain about member template instantiations that
15422 have this form, though; they can occur as we try to decide
15423 what constructor to use during overload resolution. Since
15424 overload resolution will never prefer such a constructor to
15425 the non-template copy constructor (which is either explicitly
15426 or implicitly defined), there's no need to worry about their
15427 existence. Theoretically, they should never even be
15428 instantiated, but that's hard to forestall. */
15429 error_at (DECL_SOURCE_LOCATION (decl),
15430 "invalid constructor; you probably meant %<%T (const %T&)%>",
15431 ctype, ctype);
15432 return false;
15435 return true;
15438 /* DECL is a declaration for an overloaded or conversion operator. If
15439 COMPLAIN is true, errors are issued for invalid declarations. */
15441 bool
15442 grok_op_properties (tree decl, bool complain)
15444 tree argtypes = TYPE_ARG_TYPES (TREE_TYPE (decl));
15445 bool methodp = TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE;
15446 tree name = DECL_NAME (decl);
15447 location_t loc = DECL_SOURCE_LOCATION (decl);
15449 tree class_type = DECL_CONTEXT (decl);
15450 if (class_type && !CLASS_TYPE_P (class_type))
15451 class_type = NULL_TREE;
15453 tree_code operator_code;
15454 unsigned op_flags;
15455 if (IDENTIFIER_CONV_OP_P (name))
15457 /* Conversion operators are TYPE_EXPR for the purposes of this
15458 function. */
15459 operator_code = TYPE_EXPR;
15460 op_flags = OVL_OP_FLAG_UNARY;
15462 else
15464 const ovl_op_info_t *ovl_op = IDENTIFIER_OVL_OP_INFO (name);
15466 operator_code = ovl_op->tree_code;
15467 op_flags = ovl_op->flags;
15468 gcc_checking_assert (operator_code != ERROR_MARK);
15469 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
15472 if (op_flags & OVL_OP_FLAG_ALLOC)
15474 /* operator new and operator delete are quite special. */
15475 if (class_type)
15476 switch (op_flags)
15478 case OVL_OP_FLAG_ALLOC:
15479 TYPE_HAS_NEW_OPERATOR (class_type) = 1;
15480 break;
15482 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE:
15483 TYPE_GETS_DELETE (class_type) |= 1;
15484 break;
15486 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_VEC:
15487 TYPE_HAS_ARRAY_NEW_OPERATOR (class_type) = 1;
15488 break;
15490 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE | OVL_OP_FLAG_VEC:
15491 TYPE_GETS_DELETE (class_type) |= 2;
15492 break;
15494 default:
15495 gcc_unreachable ();
15498 /* [basic.std.dynamic.allocation]/1:
15500 A program is ill-formed if an allocation function is declared
15501 in a namespace scope other than global scope or declared
15502 static in global scope.
15504 The same also holds true for deallocation functions. */
15505 if (DECL_NAMESPACE_SCOPE_P (decl))
15507 if (CP_DECL_CONTEXT (decl) != global_namespace)
15509 error_at (loc, "%qD may not be declared within a namespace",
15510 decl);
15511 return false;
15514 if (!TREE_PUBLIC (decl))
15516 error_at (loc, "%qD may not be declared as static", decl);
15517 return false;
15521 if (op_flags & OVL_OP_FLAG_DELETE)
15523 DECL_SET_IS_OPERATOR_DELETE (decl, true);
15524 coerce_delete_type (decl, loc);
15526 else
15528 DECL_SET_IS_OPERATOR_NEW (decl, true);
15529 TREE_TYPE (decl) = coerce_new_type (TREE_TYPE (decl), loc);
15532 return true;
15535 /* An operator function must either be a non-static member function
15536 or have at least one parameter of a class, a reference to a class,
15537 an enumeration, or a reference to an enumeration. 13.4.0.6 */
15538 if (! methodp || DECL_STATIC_FUNCTION_P (decl))
15540 if (operator_code == TYPE_EXPR
15541 || operator_code == COMPONENT_REF
15542 || operator_code == NOP_EXPR)
15544 error_at (loc, "%qD must be a non-static member function", decl);
15545 return false;
15548 if (operator_code == CALL_EXPR || operator_code == ARRAY_REF)
15550 if (! DECL_STATIC_FUNCTION_P (decl))
15552 error_at (loc, "%qD must be a member function", decl);
15553 return false;
15555 if (cxx_dialect < cxx23
15556 /* For lambdas we diagnose static lambda specifier elsewhere. */
15557 && (operator_code == ARRAY_REF || ! LAMBDA_FUNCTION_P (decl))
15558 /* For instantiations, we have diagnosed this already. */
15559 && ! DECL_USE_TEMPLATE (decl))
15560 pedwarn (loc, OPT_Wc__23_extensions, "%qD may be a static member "
15561 "function only with %<-std=c++23%> or %<-std=gnu++23%>",
15562 decl);
15563 if (operator_code == ARRAY_REF)
15564 /* static operator[] should have exactly one argument
15565 for C++20 and earlier, so that it isn't multidimensional. */
15566 op_flags = OVL_OP_FLAG_UNARY;
15568 else if (DECL_STATIC_FUNCTION_P (decl))
15570 error_at (loc, "%qD must be either a non-static member "
15571 "function or a non-member function", decl);
15572 return false;
15574 else
15575 for (tree arg = argtypes; ; arg = TREE_CHAIN (arg))
15577 if (!arg || arg == void_list_node)
15579 if (complain)
15580 error_at (loc, "%qD must have an argument of class or "
15581 "enumerated type", decl);
15582 return false;
15585 tree type = non_reference (TREE_VALUE (arg));
15586 if (type == error_mark_node)
15587 return false;
15589 /* MAYBE_CLASS_TYPE_P, rather than CLASS_TYPE_P, is used
15590 because these checks are performed even on template
15591 functions. */
15592 if (MAYBE_CLASS_TYPE_P (type)
15593 || TREE_CODE (type) == ENUMERAL_TYPE)
15594 break;
15598 if (operator_code == CALL_EXPR)
15599 /* There are no further restrictions on the arguments to an overloaded
15600 "operator ()". */
15601 return true;
15603 /* C++23 allows an arbitrary number of parameters and default arguments for
15604 operator[], and none of the other checks below apply. */
15605 if (operator_code == ARRAY_REF && cxx_dialect >= cxx23)
15606 return true;
15608 if (operator_code == COND_EXPR)
15610 /* 13.4.0.3 */
15611 error_at (loc, "ISO C++ prohibits overloading %<operator ?:%>");
15612 return false;
15615 /* Count the number of arguments and check for ellipsis. */
15616 int arity = 0;
15617 for (tree arg = argtypes; arg != void_list_node; arg = TREE_CHAIN (arg))
15619 if (!arg)
15621 error_at (loc, "%qD must not have variable number of arguments",
15622 decl);
15623 return false;
15625 ++arity;
15628 /* Verify correct number of arguments. */
15629 switch (op_flags)
15631 case OVL_OP_FLAG_AMBIARY:
15632 if (arity == 1)
15634 /* We have a unary instance of an ambi-ary op. Remap to the
15635 unary one. */
15636 unsigned alt = ovl_op_alternate[ovl_op_mapping [operator_code]];
15637 const ovl_op_info_t *ovl_op = &ovl_op_info[false][alt];
15638 gcc_checking_assert (ovl_op->flags == OVL_OP_FLAG_UNARY);
15639 operator_code = ovl_op->tree_code;
15640 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
15642 else if (arity != 2)
15644 /* This was an ambiguous operator but is invalid. */
15645 error_at (loc,
15646 methodp
15647 ? G_("%qD must have either zero or one argument")
15648 : G_("%qD must have either one or two arguments"), decl);
15649 return false;
15651 else if ((operator_code == POSTINCREMENT_EXPR
15652 || operator_code == POSTDECREMENT_EXPR)
15653 && ! processing_template_decl
15654 /* x++ and x--'s second argument must be an int. */
15655 && ! same_type_p (TREE_VALUE (TREE_CHAIN (argtypes)),
15656 integer_type_node))
15658 error_at (loc,
15659 methodp
15660 ? G_("postfix %qD must have %<int%> as its argument")
15661 : G_("postfix %qD must have %<int%> as its second argument"),
15662 decl);
15663 return false;
15665 break;
15667 case OVL_OP_FLAG_UNARY:
15668 if (arity != 1)
15670 error_at (loc,
15671 methodp
15672 ? G_("%qD must have no arguments")
15673 : G_("%qD must have exactly one argument"), decl);
15674 return false;
15676 break;
15678 case OVL_OP_FLAG_BINARY:
15679 if (arity != 2)
15681 error_at (loc,
15682 methodp
15683 ? G_("%qD must have exactly one argument")
15684 : G_("%qD must have exactly two arguments"), decl);
15685 return false;
15687 break;
15689 default:
15690 gcc_unreachable ();
15693 /* There can be no default arguments. */
15694 for (tree arg = argtypes; arg && arg != void_list_node;
15695 arg = TREE_CHAIN (arg))
15696 if (TREE_PURPOSE (arg))
15698 TREE_PURPOSE (arg) = NULL_TREE;
15699 error_at (loc, "%qD cannot have default arguments", decl);
15700 return false;
15703 /* At this point the declaration is well-formed. It may not be
15704 sensible though. */
15706 /* Check member function warnings only on the in-class declaration.
15707 There's no point warning on an out-of-class definition. */
15708 if (class_type && class_type != current_class_type)
15709 return true;
15711 /* Warn about conversion operators that will never be used. */
15712 if (IDENTIFIER_CONV_OP_P (name)
15713 && ! DECL_TEMPLATE_INFO (decl)
15714 && warn_class_conversion)
15716 tree t = TREE_TYPE (name);
15717 int ref = TYPE_REF_P (t);
15719 if (ref)
15720 t = TYPE_MAIN_VARIANT (TREE_TYPE (t));
15722 if (VOID_TYPE_P (t))
15723 warning_at (loc, OPT_Wclass_conversion, "converting %qT to %<void%> "
15724 "will never use a type conversion operator", class_type);
15725 else if (class_type)
15727 if (same_type_ignoring_top_level_qualifiers_p (t, class_type))
15728 warning_at (loc, OPT_Wclass_conversion,
15730 ? G_("converting %qT to a reference to the same type "
15731 "will never use a type conversion operator")
15732 : G_("converting %qT to the same type "
15733 "will never use a type conversion operator"),
15734 class_type);
15735 /* Don't force t to be complete here. */
15736 else if (MAYBE_CLASS_TYPE_P (t)
15737 && COMPLETE_TYPE_P (t)
15738 && DERIVED_FROM_P (t, class_type))
15739 warning_at (loc, OPT_Wclass_conversion,
15741 ? G_("converting %qT to a reference to a base class "
15742 "%qT will never use a type conversion operator")
15743 : G_("converting %qT to a base class %qT "
15744 "will never use a type conversion operator"),
15745 class_type, t);
15749 if (!warn_ecpp)
15750 return true;
15752 /* Effective C++ rules below. */
15754 /* More Effective C++ rule 7. */
15755 if (operator_code == TRUTH_ANDIF_EXPR
15756 || operator_code == TRUTH_ORIF_EXPR
15757 || operator_code == COMPOUND_EXPR)
15758 warning_at (loc, OPT_Weffc__,
15759 "user-defined %qD always evaluates both arguments", decl);
15761 /* More Effective C++ rule 6. */
15762 if (operator_code == POSTINCREMENT_EXPR
15763 || operator_code == POSTDECREMENT_EXPR
15764 || operator_code == PREINCREMENT_EXPR
15765 || operator_code == PREDECREMENT_EXPR)
15767 tree arg = TREE_VALUE (argtypes);
15768 tree ret = TREE_TYPE (TREE_TYPE (decl));
15769 if (methodp || TYPE_REF_P (arg))
15770 arg = TREE_TYPE (arg);
15771 arg = TYPE_MAIN_VARIANT (arg);
15773 if (operator_code == PREINCREMENT_EXPR
15774 || operator_code == PREDECREMENT_EXPR)
15776 if (!TYPE_REF_P (ret)
15777 || !same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (ret)), arg))
15778 warning_at (loc, OPT_Weffc__, "prefix %qD should return %qT", decl,
15779 build_reference_type (arg));
15781 else
15783 if (!same_type_p (TYPE_MAIN_VARIANT (ret), arg))
15784 warning_at (loc, OPT_Weffc__,
15785 "postfix %qD should return %qT", decl, arg);
15789 /* Effective C++ rule 23. */
15790 if (!DECL_ASSIGNMENT_OPERATOR_P (decl)
15791 && (operator_code == PLUS_EXPR
15792 || operator_code == MINUS_EXPR
15793 || operator_code == TRUNC_DIV_EXPR
15794 || operator_code == MULT_EXPR
15795 || operator_code == TRUNC_MOD_EXPR)
15796 && TYPE_REF_P (TREE_TYPE (TREE_TYPE (decl))))
15797 warning_at (loc, OPT_Weffc__, "%qD should return by value", decl);
15799 return true;
15802 /* Return a string giving the keyword associate with CODE. */
15804 static const char *
15805 tag_name (enum tag_types code)
15807 switch (code)
15809 case record_type:
15810 return "struct";
15811 case class_type:
15812 return "class";
15813 case union_type:
15814 return "union";
15815 case enum_type:
15816 return "enum";
15817 case typename_type:
15818 return "typename";
15819 default:
15820 gcc_unreachable ();
15824 /* Name lookup in an elaborated-type-specifier (after the keyword
15825 indicated by TAG_CODE) has found the TYPE_DECL DECL. If the
15826 elaborated-type-specifier is invalid, issue a diagnostic and return
15827 error_mark_node; otherwise, return the *_TYPE to which it referred.
15828 If ALLOW_TEMPLATE_P is true, TYPE may be a class template. */
15830 tree
15831 check_elaborated_type_specifier (enum tag_types tag_code,
15832 tree decl,
15833 bool allow_template_p)
15835 tree type;
15837 /* In the case of:
15839 struct S { struct S *p; };
15841 name lookup will find the TYPE_DECL for the implicit "S::S"
15842 typedef. Adjust for that here. */
15843 if (DECL_SELF_REFERENCE_P (decl))
15844 decl = TYPE_NAME (TREE_TYPE (decl));
15846 type = TREE_TYPE (decl);
15848 /* Check TEMPLATE_TYPE_PARM first because DECL_IMPLICIT_TYPEDEF_P
15849 is false for this case as well. */
15850 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
15852 error ("using template type parameter %qT after %qs",
15853 type, tag_name (tag_code));
15854 return error_mark_node;
15856 /* Accept template template parameters. */
15857 else if (allow_template_p
15858 && (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
15859 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM))
15861 /* [dcl.type.elab]
15863 If the identifier resolves to a typedef-name or the
15864 simple-template-id resolves to an alias template
15865 specialization, the elaborated-type-specifier is ill-formed.
15867 In other words, the only legitimate declaration to use in the
15868 elaborated type specifier is the implicit typedef created when
15869 the type is declared. */
15870 else if (!DECL_IMPLICIT_TYPEDEF_P (decl)
15871 && !DECL_SELF_REFERENCE_P (decl)
15872 && tag_code != typename_type)
15874 if (alias_template_specialization_p (type, nt_opaque))
15875 error ("using alias template specialization %qT after %qs",
15876 type, tag_name (tag_code));
15877 else
15878 error ("using typedef-name %qD after %qs", decl, tag_name (tag_code));
15879 inform (DECL_SOURCE_LOCATION (decl),
15880 "%qD has a previous declaration here", decl);
15881 return error_mark_node;
15883 else if (TREE_CODE (type) != RECORD_TYPE
15884 && TREE_CODE (type) != UNION_TYPE
15885 && tag_code != enum_type
15886 && tag_code != typename_type)
15888 error ("%qT referred to as %qs", type, tag_name (tag_code));
15889 inform (location_of (type), "%qT has a previous declaration here", type);
15890 return error_mark_node;
15892 else if (TREE_CODE (type) != ENUMERAL_TYPE
15893 && tag_code == enum_type)
15895 error ("%qT referred to as enum", type);
15896 inform (location_of (type), "%qT has a previous declaration here", type);
15897 return error_mark_node;
15899 else if (!allow_template_p
15900 && TREE_CODE (type) == RECORD_TYPE
15901 && CLASSTYPE_IS_TEMPLATE (type))
15903 /* If a class template appears as elaborated type specifier
15904 without a template header such as:
15906 template <class T> class C {};
15907 void f(class C); // No template header here
15909 then the required template argument is missing. */
15910 error ("template argument required for %<%s %T%>",
15911 tag_name (tag_code),
15912 DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)));
15913 return error_mark_node;
15916 return type;
15919 /* Lookup NAME of an elaborated type specifier according to SCOPE and
15920 issue diagnostics if necessary. Return *_TYPE node upon success,
15921 NULL_TREE when the NAME is not found, and ERROR_MARK_NODE for type
15922 error. */
15924 static tree
15925 lookup_and_check_tag (enum tag_types tag_code, tree name,
15926 TAG_how how, bool template_header_p)
15928 tree decl;
15929 if (how == TAG_how::GLOBAL)
15931 /* First try ordinary name lookup, ignoring hidden class name
15932 injected via friend declaration. */
15933 decl = lookup_name (name, LOOK_want::TYPE);
15934 decl = strip_using_decl (decl);
15935 /* If that fails, the name will be placed in the smallest
15936 non-class, non-function-prototype scope according to 3.3.1/5.
15937 We may already have a hidden name declared as friend in this
15938 scope. So lookup again but not ignoring hidden names.
15939 If we find one, that name will be made visible rather than
15940 creating a new tag. */
15941 if (!decl)
15942 decl = lookup_elaborated_type (name, TAG_how::INNERMOST_NON_CLASS);
15944 else
15945 decl = lookup_elaborated_type (name, how);
15947 if (!decl)
15948 /* We found nothing. */
15949 return NULL_TREE;
15951 if (TREE_CODE (decl) == TREE_LIST)
15953 error ("reference to %qD is ambiguous", name);
15954 print_candidates (decl);
15955 return error_mark_node;
15958 if (DECL_CLASS_TEMPLATE_P (decl)
15959 && !template_header_p
15960 && how == TAG_how::CURRENT_ONLY)
15962 error ("class template %qD redeclared as non-template", name);
15963 inform (location_of (decl), "previous declaration here");
15964 CLASSTYPE_ERRONEOUS (TREE_TYPE (decl)) = true;
15965 return error_mark_node;
15968 if (DECL_CLASS_TEMPLATE_P (decl)
15969 /* If scope is TAG_how::CURRENT_ONLY we're defining a class,
15970 so ignore a template template parameter. */
15971 || (how != TAG_how::CURRENT_ONLY && DECL_TEMPLATE_TEMPLATE_PARM_P (decl)))
15972 decl = DECL_TEMPLATE_RESULT (decl);
15974 if (TREE_CODE (decl) != TYPE_DECL)
15975 /* Found not-a-type. */
15976 return NULL_TREE;
15978 /* Look for invalid nested type:
15979 class C {
15980 class C {};
15981 }; */
15982 if (how == TAG_how::CURRENT_ONLY && DECL_SELF_REFERENCE_P (decl))
15984 error ("%qD has the same name as the class in which it is "
15985 "declared", decl);
15986 return error_mark_node;
15989 /* Two cases we need to consider when deciding if a class
15990 template is allowed as an elaborated type specifier:
15991 1. It is a self reference to its own class.
15992 2. It comes with a template header.
15994 For example:
15996 template <class T> class C {
15997 class C *c1; // DECL_SELF_REFERENCE_P is true
15998 class D;
16000 template <class U> class C; // template_header_p is true
16001 template <class T> class C<T>::D {
16002 class C *c2; // DECL_SELF_REFERENCE_P is true
16003 }; */
16005 tree t = check_elaborated_type_specifier (tag_code, decl,
16006 template_header_p
16007 | DECL_SELF_REFERENCE_P (decl));
16008 if (template_header_p && t && CLASS_TYPE_P (t)
16009 && (!CLASSTYPE_TEMPLATE_INFO (t)
16010 || (!PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))))
16012 error ("%qT is not a template", t);
16013 inform (location_of (t), "previous declaration here");
16014 if (TYPE_CLASS_SCOPE_P (t)
16015 && CLASSTYPE_TEMPLATE_INFO (TYPE_CONTEXT (t)))
16016 inform (input_location,
16017 "perhaps you want to explicitly add %<%T::%>",
16018 TYPE_CONTEXT (t));
16019 return error_mark_node;
16022 return t;
16025 /* Get the struct, enum or union (TAG_CODE says which) with tag NAME.
16026 Define the tag as a forward-reference if it is not defined.
16028 If a declaration is given, process it here, and report an error if
16029 multiple declarations are not identical.
16031 SCOPE is TS_CURRENT when this is also a definition. Only look in
16032 the current frame for the name (since C++ allows new names in any
16033 scope.) It is TS_WITHIN_ENCLOSING_NON_CLASS if this is a friend
16034 declaration. Only look beginning from the current scope outward up
16035 till the nearest non-class scope. Otherwise it is TS_GLOBAL.
16037 TEMPLATE_HEADER_P is true when this declaration is preceded by
16038 a set of template parameters. */
16040 tree
16041 xref_tag (enum tag_types tag_code, tree name,
16042 TAG_how how, bool template_header_p)
16044 enum tree_code code;
16045 tree context = NULL_TREE;
16047 auto_cond_timevar tv (TV_NAME_LOOKUP);
16049 gcc_assert (identifier_p (name));
16051 switch (tag_code)
16053 case record_type:
16054 case class_type:
16055 code = RECORD_TYPE;
16056 break;
16057 case union_type:
16058 code = UNION_TYPE;
16059 break;
16060 case enum_type:
16061 code = ENUMERAL_TYPE;
16062 break;
16063 default:
16064 gcc_unreachable ();
16067 /* In case of anonymous name, xref_tag is only called to
16068 make type node and push name. Name lookup is not required. */
16069 tree t = NULL_TREE;
16070 if (!IDENTIFIER_ANON_P (name))
16071 t = lookup_and_check_tag (tag_code, name, how, template_header_p);
16073 if (t == error_mark_node)
16074 return error_mark_node;
16076 if (how != TAG_how::CURRENT_ONLY && t && current_class_type
16077 && template_class_depth (current_class_type)
16078 && template_header_p)
16080 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
16081 return t;
16083 /* Since HOW is not TAG_how::CURRENT_ONLY, we are not looking at
16084 a definition of this tag. Since, in addition, we are
16085 currently processing a (member) template declaration of a
16086 template class, we must be very careful; consider:
16088 template <class X> struct S1
16090 template <class U> struct S2
16092 template <class V> friend struct S1;
16095 Here, the S2::S1 declaration should not be confused with the
16096 outer declaration. In particular, the inner version should
16097 have a template parameter of level 2, not level 1.
16099 On the other hand, when presented with:
16101 template <class T> struct S1
16103 template <class U> struct S2 {};
16104 template <class U> friend struct S2;
16107 the friend must find S1::S2 eventually. We accomplish this
16108 by making sure that the new type we create to represent this
16109 declaration has the right TYPE_CONTEXT. */
16110 context = TYPE_CONTEXT (t);
16111 t = NULL_TREE;
16114 if (! t)
16116 /* If no such tag is yet defined, create a forward-reference node
16117 and record it as the "definition".
16118 When a real declaration of this type is found,
16119 the forward-reference will be altered into a real type. */
16120 if (code == ENUMERAL_TYPE)
16122 error ("use of enum %q#D without previous declaration", name);
16123 return error_mark_node;
16126 t = make_class_type (code);
16127 TYPE_CONTEXT (t) = context;
16128 if (IDENTIFIER_LAMBDA_P (name))
16129 /* Mark it as a lambda type right now. Our caller will
16130 correct the value. */
16131 CLASSTYPE_LAMBDA_EXPR (t) = error_mark_node;
16132 t = pushtag (name, t, how);
16134 else
16136 if (template_header_p && MAYBE_CLASS_TYPE_P (t))
16138 /* Check that we aren't trying to overload a class with different
16139 constraints. */
16140 if (!redeclare_class_template (t, current_template_parms,
16141 current_template_constraints ()))
16142 return error_mark_node;
16144 else if (!processing_template_decl
16145 && CLASS_TYPE_P (t)
16146 && CLASSTYPE_IS_TEMPLATE (t))
16148 error ("redeclaration of %qT as a non-template", t);
16149 inform (location_of (t), "previous declaration %qD", t);
16150 return error_mark_node;
16153 if (modules_p ()
16154 && how == TAG_how::CURRENT_ONLY)
16156 tree decl = TYPE_NAME (t);
16157 if (!module_may_redeclare (decl))
16159 error ("cannot declare %qD in a different module", decl);
16160 inform (DECL_SOURCE_LOCATION (decl), "declared here");
16161 return error_mark_node;
16164 tree maybe_tmpl = decl;
16165 if (CLASS_TYPE_P (t) && CLASSTYPE_IS_TEMPLATE (t))
16166 maybe_tmpl = CLASSTYPE_TI_TEMPLATE (t);
16168 if (DECL_LANG_SPECIFIC (decl)
16169 && DECL_MODULE_IMPORT_P (decl)
16170 && TREE_CODE (CP_DECL_CONTEXT (decl)) == NAMESPACE_DECL)
16172 /* Push it into this TU's symbol slot. */
16173 gcc_checking_assert (current_namespace == CP_DECL_CONTEXT (decl));
16174 if (maybe_tmpl != decl)
16175 /* We're in the template parm binding level.
16176 Pushtag has logic to slide under that, but we're
16177 not pushing a *new* type. */
16178 push_nested_namespace (CP_DECL_CONTEXT (decl));
16180 pushdecl (maybe_tmpl);
16181 if (maybe_tmpl != decl)
16182 pop_nested_namespace (CP_DECL_CONTEXT (decl));
16185 set_instantiating_module (maybe_tmpl);
16189 return t;
16192 /* Create the binfo hierarchy for REF with (possibly NULL) base list
16193 BASE_LIST. For each element on BASE_LIST the TREE_PURPOSE is an
16194 access_* node, and the TREE_VALUE is the type of the base-class.
16195 Non-NULL TREE_TYPE indicates virtual inheritance. */
16197 void
16198 xref_basetypes (tree ref, tree base_list)
16200 tree *basep;
16201 tree binfo, base_binfo;
16202 unsigned max_vbases = 0; /* Maximum direct & indirect virtual bases. */
16203 unsigned max_bases = 0; /* Maximum direct bases. */
16204 unsigned max_dvbases = 0; /* Maximum direct virtual bases. */
16205 int i;
16206 tree default_access;
16207 tree igo_prev; /* Track Inheritance Graph Order. */
16209 if (ref == error_mark_node)
16210 return;
16212 /* The base of a derived class is private by default, all others are
16213 public. */
16214 default_access = (TREE_CODE (ref) == RECORD_TYPE
16215 && CLASSTYPE_DECLARED_CLASS (ref)
16216 ? access_private_node : access_public_node);
16218 /* First, make sure that any templates in base-classes are
16219 instantiated. This ensures that if we call ourselves recursively
16220 we do not get confused about which classes are marked and which
16221 are not. */
16222 basep = &base_list;
16223 while (*basep)
16225 tree basetype = TREE_VALUE (*basep);
16227 /* The dependent_type_p call below should really be dependent_scope_p
16228 so that we give a hard error about using an incomplete type as a
16229 base, but we allow it with a pedwarn for backward
16230 compatibility. */
16231 if (processing_template_decl
16232 && CLASS_TYPE_P (basetype) && TYPE_BEING_DEFINED (basetype))
16233 cxx_incomplete_type_diagnostic (NULL_TREE, basetype, DK_PEDWARN);
16234 if (!dependent_type_p (basetype)
16235 && !complete_type_or_else (basetype, NULL))
16236 /* An incomplete type. Remove it from the list. */
16237 *basep = TREE_CHAIN (*basep);
16238 else
16240 max_bases++;
16241 if (TREE_TYPE (*basep))
16242 max_dvbases++;
16243 if (CLASS_TYPE_P (basetype))
16244 max_vbases += vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
16245 basep = &TREE_CHAIN (*basep);
16248 max_vbases += max_dvbases;
16250 TYPE_MARKED_P (ref) = 1;
16252 /* The binfo slot should be empty, unless this is an (ill-formed)
16253 redefinition. */
16254 gcc_assert (!TYPE_BINFO (ref) || TYPE_SIZE (ref));
16256 gcc_assert (TYPE_MAIN_VARIANT (ref) == ref);
16258 binfo = make_tree_binfo (max_bases);
16260 TYPE_BINFO (ref) = binfo;
16261 BINFO_OFFSET (binfo) = size_zero_node;
16262 BINFO_TYPE (binfo) = ref;
16264 /* Apply base-class info set up to the variants of this type. */
16265 fixup_type_variants (ref);
16267 if (max_bases)
16269 vec_alloc (BINFO_BASE_ACCESSES (binfo), max_bases);
16270 /* A C++98 POD cannot have base classes. */
16271 CLASSTYPE_NON_LAYOUT_POD_P (ref) = true;
16273 if (TREE_CODE (ref) == UNION_TYPE)
16275 error ("derived union %qT invalid", ref);
16276 return;
16280 if (max_bases > 1)
16281 warning (OPT_Wmultiple_inheritance,
16282 "%qT defined with multiple direct bases", ref);
16284 if (max_vbases)
16286 /* An aggregate can't have virtual base classes. */
16287 CLASSTYPE_NON_AGGREGATE (ref) = true;
16289 vec_alloc (CLASSTYPE_VBASECLASSES (ref), max_vbases);
16291 if (max_dvbases)
16292 warning (OPT_Wvirtual_inheritance,
16293 "%qT defined with direct virtual base", ref);
16296 for (igo_prev = binfo; base_list; base_list = TREE_CHAIN (base_list))
16298 tree access = TREE_PURPOSE (base_list);
16299 int via_virtual = TREE_TYPE (base_list) != NULL_TREE;
16300 tree basetype = TREE_VALUE (base_list);
16302 if (access == access_default_node)
16303 access = default_access;
16305 /* Before C++17, an aggregate cannot have base classes. In C++17, an
16306 aggregate can't have virtual, private, or protected base classes. */
16307 if (cxx_dialect < cxx17
16308 || access != access_public_node
16309 || via_virtual)
16310 CLASSTYPE_NON_AGGREGATE (ref) = true;
16312 if (PACK_EXPANSION_P (basetype))
16313 basetype = PACK_EXPANSION_PATTERN (basetype);
16314 if (TREE_CODE (basetype) == TYPE_DECL)
16315 basetype = TREE_TYPE (basetype);
16316 if (!MAYBE_CLASS_TYPE_P (basetype) || TREE_CODE (basetype) == UNION_TYPE)
16318 error ("base type %qT fails to be a struct or class type",
16319 basetype);
16320 goto dropped_base;
16323 base_binfo = NULL_TREE;
16324 if (CLASS_TYPE_P (basetype) && !dependent_scope_p (basetype))
16326 base_binfo = TYPE_BINFO (basetype);
16327 /* The original basetype could have been a typedef'd type. */
16328 basetype = BINFO_TYPE (base_binfo);
16330 /* Inherit flags from the base. */
16331 TYPE_HAS_NEW_OPERATOR (ref)
16332 |= TYPE_HAS_NEW_OPERATOR (basetype);
16333 TYPE_HAS_ARRAY_NEW_OPERATOR (ref)
16334 |= TYPE_HAS_ARRAY_NEW_OPERATOR (basetype);
16335 TYPE_GETS_DELETE (ref) |= TYPE_GETS_DELETE (basetype);
16336 TYPE_HAS_CONVERSION (ref) |= TYPE_HAS_CONVERSION (basetype);
16337 CLASSTYPE_DIAMOND_SHAPED_P (ref)
16338 |= CLASSTYPE_DIAMOND_SHAPED_P (basetype);
16339 CLASSTYPE_REPEATED_BASE_P (ref)
16340 |= CLASSTYPE_REPEATED_BASE_P (basetype);
16343 /* We must do this test after we've seen through a typedef
16344 type. */
16345 if (TYPE_MARKED_P (basetype))
16347 if (basetype == ref)
16348 error ("recursive type %qT undefined", basetype);
16349 else
16350 error ("duplicate base type %qT invalid", basetype);
16351 goto dropped_base;
16354 if (PACK_EXPANSION_P (TREE_VALUE (base_list)))
16355 /* Regenerate the pack expansion for the bases. */
16356 basetype = make_pack_expansion (basetype);
16358 TYPE_MARKED_P (basetype) = 1;
16360 base_binfo = copy_binfo (base_binfo, basetype, ref,
16361 &igo_prev, via_virtual);
16362 if (!BINFO_INHERITANCE_CHAIN (base_binfo))
16363 BINFO_INHERITANCE_CHAIN (base_binfo) = binfo;
16365 BINFO_BASE_APPEND (binfo, base_binfo);
16366 BINFO_BASE_ACCESS_APPEND (binfo, access);
16367 continue;
16369 dropped_base:
16370 /* Update max_vbases to reflect the reality that we are dropping
16371 this base: if it reaches zero we want to undo the vec_alloc
16372 above to avoid inconsistencies during error-recovery: eg, in
16373 build_special_member_call, CLASSTYPE_VBASECLASSES non null
16374 and vtt null (c++/27952). */
16375 if (via_virtual)
16376 max_vbases--;
16377 if (CLASS_TYPE_P (basetype))
16378 max_vbases
16379 -= vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
16382 if (CLASSTYPE_VBASECLASSES (ref)
16383 && max_vbases == 0)
16384 vec_free (CLASSTYPE_VBASECLASSES (ref));
16386 if (vec_safe_length (CLASSTYPE_VBASECLASSES (ref)) < max_vbases)
16387 /* If we didn't get max_vbases vbases, we must have shared at
16388 least one of them, and are therefore diamond shaped. */
16389 CLASSTYPE_DIAMOND_SHAPED_P (ref) = 1;
16391 /* Unmark all the types. */
16392 for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
16393 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
16394 TYPE_MARKED_P (ref) = 0;
16396 /* Now see if we have a repeated base type. */
16397 if (!CLASSTYPE_REPEATED_BASE_P (ref))
16399 for (base_binfo = binfo; base_binfo;
16400 base_binfo = TREE_CHAIN (base_binfo))
16402 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
16404 CLASSTYPE_REPEATED_BASE_P (ref) = 1;
16405 break;
16407 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 1;
16409 for (base_binfo = binfo; base_binfo;
16410 base_binfo = TREE_CHAIN (base_binfo))
16411 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
16412 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
16413 else
16414 break;
16419 /* Copies the enum-related properties from type SRC to type DST.
16420 Used with the underlying type of an enum and the enum itself. */
16421 static void
16422 copy_type_enum (tree dst, tree src)
16424 tree t;
16425 for (t = dst; t; t = TYPE_NEXT_VARIANT (t))
16427 TYPE_MIN_VALUE (t) = TYPE_MIN_VALUE (src);
16428 TYPE_MAX_VALUE (t) = TYPE_MAX_VALUE (src);
16429 TYPE_SIZE (t) = TYPE_SIZE (src);
16430 TYPE_SIZE_UNIT (t) = TYPE_SIZE_UNIT (src);
16431 SET_TYPE_MODE (dst, TYPE_MODE (src));
16432 TYPE_PRECISION (t) = TYPE_PRECISION (src);
16433 unsigned valign = TYPE_ALIGN (src);
16434 if (TYPE_USER_ALIGN (t))
16435 valign = MAX (valign, TYPE_ALIGN (t));
16436 else
16437 TYPE_USER_ALIGN (t) = TYPE_USER_ALIGN (src);
16438 SET_TYPE_ALIGN (t, valign);
16439 TYPE_UNSIGNED (t) = TYPE_UNSIGNED (src);
16443 /* Begin compiling the definition of an enumeration type.
16444 NAME is its name,
16446 if ENUMTYPE is not NULL_TREE then the type has alredy been found.
16448 UNDERLYING_TYPE is the type that will be used as the storage for
16449 the enumeration type. This should be NULL_TREE if no storage type
16450 was specified.
16452 ATTRIBUTES are any attributes specified after the enum-key.
16454 SCOPED_ENUM_P is true if this is a scoped enumeration type.
16456 if IS_NEW is not NULL, gets TRUE iff a new type is created.
16458 Returns the type object, as yet incomplete.
16459 Also records info about it so that build_enumerator
16460 may be used to declare the individual values as they are read. */
16462 tree
16463 start_enum (tree name, tree enumtype, tree underlying_type,
16464 tree attributes, bool scoped_enum_p, bool *is_new)
16466 tree prevtype = NULL_TREE;
16467 gcc_assert (identifier_p (name));
16469 if (is_new)
16470 *is_new = false;
16471 /* [C++0x dcl.enum]p5:
16473 If not explicitly specified, the underlying type of a scoped
16474 enumeration type is int. */
16475 if (!underlying_type && scoped_enum_p)
16476 underlying_type = integer_type_node;
16478 if (underlying_type)
16479 underlying_type = cv_unqualified (underlying_type);
16481 /* If this is the real definition for a previous forward reference,
16482 fill in the contents in the same object that used to be the
16483 forward reference. */
16484 if (!enumtype)
16485 enumtype = lookup_and_check_tag (enum_type, name,
16486 /*tag_scope=*/TAG_how::CURRENT_ONLY,
16487 /*template_header_p=*/false);
16489 /* In case of a template_decl, the only check that should be deferred
16490 to instantiation time is the comparison of underlying types. */
16491 if (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE)
16493 if (scoped_enum_p != SCOPED_ENUM_P (enumtype))
16495 error_at (input_location, "scoped/unscoped mismatch "
16496 "in enum %q#T", enumtype);
16497 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16498 "previous definition here");
16499 enumtype = error_mark_node;
16501 else if (ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) != !! underlying_type)
16503 error_at (input_location, "underlying type mismatch "
16504 "in enum %q#T", enumtype);
16505 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16506 "previous definition here");
16507 enumtype = error_mark_node;
16509 else if (underlying_type && ENUM_UNDERLYING_TYPE (enumtype)
16510 && !same_type_p (underlying_type,
16511 ENUM_UNDERLYING_TYPE (enumtype)))
16513 error_at (input_location, "different underlying type "
16514 "in enum %q#T", enumtype);
16515 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16516 "previous definition here");
16517 underlying_type = NULL_TREE;
16520 if (modules_p ())
16522 if (!module_may_redeclare (TYPE_NAME (enumtype)))
16524 error ("cannot define %qD in different module",
16525 TYPE_NAME (enumtype));
16526 inform (DECL_SOURCE_LOCATION (TYPE_NAME (enumtype)),
16527 "declared here");
16528 enumtype = error_mark_node;
16530 set_instantiating_module (TYPE_NAME (enumtype));
16534 if (!enumtype || TREE_CODE (enumtype) != ENUMERAL_TYPE
16535 || processing_template_decl)
16537 /* In case of error, make a dummy enum to allow parsing to
16538 continue. */
16539 if (enumtype == error_mark_node)
16541 name = make_anon_name ();
16542 enumtype = NULL_TREE;
16545 /* enumtype may be an ENUMERAL_TYPE if this is a redefinition
16546 of an opaque enum, or an opaque enum of an already defined
16547 enumeration (C++11).
16548 In any other case, it'll be NULL_TREE. */
16549 if (!enumtype)
16551 if (is_new)
16552 *is_new = true;
16554 prevtype = enumtype;
16556 /* Do not push the decl more than once. */
16557 if (!enumtype
16558 || TREE_CODE (enumtype) != ENUMERAL_TYPE)
16560 enumtype = cxx_make_type (ENUMERAL_TYPE);
16561 enumtype = pushtag (name, enumtype);
16563 /* std::byte aliases anything. */
16564 if (enumtype != error_mark_node
16565 && TYPE_CONTEXT (enumtype) == std_node
16566 && !strcmp ("byte", TYPE_NAME_STRING (enumtype)))
16567 TYPE_ALIAS_SET (enumtype) = 0;
16569 else
16570 enumtype = xref_tag (enum_type, name);
16572 if (enumtype == error_mark_node)
16573 return error_mark_node;
16575 /* The enum is considered opaque until the opening '{' of the
16576 enumerator list. */
16577 SET_OPAQUE_ENUM_P (enumtype, true);
16578 ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) = !! underlying_type;
16581 SET_SCOPED_ENUM_P (enumtype, scoped_enum_p);
16583 cplus_decl_attributes (&enumtype, attributes, (int)ATTR_FLAG_TYPE_IN_PLACE);
16585 if (underlying_type)
16587 if (ENUM_UNDERLYING_TYPE (enumtype))
16588 /* We already checked that it matches, don't change it to a different
16589 typedef variant. */;
16590 else if (CP_INTEGRAL_TYPE_P (underlying_type))
16592 copy_type_enum (enumtype, underlying_type);
16593 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
16595 else if (dependent_type_p (underlying_type))
16596 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
16597 else
16599 error ("underlying type %qT of %qT must be an integral type",
16600 underlying_type, enumtype);
16601 ENUM_UNDERLYING_TYPE (enumtype) = integer_type_node;
16605 /* If into a template class, the returned enum is always the first
16606 declaration (opaque or not) seen. This way all the references to
16607 this type will be to the same declaration. The following ones are used
16608 only to check for definition errors. */
16609 if (prevtype && processing_template_decl)
16610 return prevtype;
16611 else
16612 return enumtype;
16615 /* After processing and defining all the values of an enumeration type,
16616 install their decls in the enumeration type.
16617 ENUMTYPE is the type object. */
16619 void
16620 finish_enum_value_list (tree enumtype)
16622 tree values;
16623 tree underlying_type;
16624 tree decl;
16625 tree value;
16626 tree minnode, maxnode;
16627 tree t;
16629 bool fixed_underlying_type_p
16630 = ENUM_UNDERLYING_TYPE (enumtype) != NULL_TREE;
16632 /* We built up the VALUES in reverse order. */
16633 TYPE_VALUES (enumtype) = nreverse (TYPE_VALUES (enumtype));
16635 /* For an enum defined in a template, just set the type of the values;
16636 all further processing is postponed until the template is
16637 instantiated. We need to set the type so that tsubst of a CONST_DECL
16638 works. */
16639 if (processing_template_decl)
16641 for (values = TYPE_VALUES (enumtype);
16642 values;
16643 values = TREE_CHAIN (values))
16644 TREE_TYPE (TREE_VALUE (values)) = enumtype;
16645 return;
16648 /* Determine the minimum and maximum values of the enumerators. */
16649 if (TYPE_VALUES (enumtype))
16651 minnode = maxnode = NULL_TREE;
16653 for (values = TYPE_VALUES (enumtype);
16654 values;
16655 values = TREE_CHAIN (values))
16657 decl = TREE_VALUE (values);
16659 /* [dcl.enum]: Following the closing brace of an enum-specifier,
16660 each enumerator has the type of its enumeration. Prior to the
16661 closing brace, the type of each enumerator is the type of its
16662 initializing value. */
16663 TREE_TYPE (decl) = enumtype;
16665 /* Update the minimum and maximum values, if appropriate. */
16666 value = DECL_INITIAL (decl);
16667 if (TREE_CODE (value) != INTEGER_CST)
16668 value = integer_zero_node;
16669 /* Figure out what the minimum and maximum values of the
16670 enumerators are. */
16671 if (!minnode)
16672 minnode = maxnode = value;
16673 else if (tree_int_cst_lt (maxnode, value))
16674 maxnode = value;
16675 else if (tree_int_cst_lt (value, minnode))
16676 minnode = value;
16679 else
16680 /* [dcl.enum]
16682 If the enumerator-list is empty, the underlying type is as if
16683 the enumeration had a single enumerator with value 0. */
16684 minnode = maxnode = integer_zero_node;
16686 if (!fixed_underlying_type_p)
16688 /* Compute the number of bits require to represent all values of the
16689 enumeration. We must do this before the type of MINNODE and
16690 MAXNODE are transformed, since tree_int_cst_min_precision relies
16691 on the TREE_TYPE of the value it is passed. */
16692 signop sgn = tree_int_cst_sgn (minnode) >= 0 ? UNSIGNED : SIGNED;
16693 int lowprec = tree_int_cst_min_precision (minnode, sgn);
16694 int highprec = tree_int_cst_min_precision (maxnode, sgn);
16695 int precision = MAX (lowprec, highprec);
16696 unsigned int itk;
16697 bool use_short_enum;
16699 /* Determine the underlying type of the enumeration.
16701 [dcl.enum]
16703 The underlying type of an enumeration is an integral type that
16704 can represent all the enumerator values defined in the
16705 enumeration. It is implementation-defined which integral type is
16706 used as the underlying type for an enumeration except that the
16707 underlying type shall not be larger than int unless the value of
16708 an enumerator cannot fit in an int or unsigned int.
16710 We use "int" or an "unsigned int" as the underlying type, even if
16711 a smaller integral type would work, unless the user has
16712 explicitly requested that we use the smallest possible type. The
16713 user can request that for all enumerations with a command line
16714 flag, or for just one enumeration with an attribute. */
16716 use_short_enum = flag_short_enums
16717 || lookup_attribute ("packed", TYPE_ATTRIBUTES (enumtype));
16719 /* If the precision of the type was specified with an attribute and it
16720 was too small, give an error. Otherwise, use it. */
16721 if (TYPE_PRECISION (enumtype))
16723 if (precision > TYPE_PRECISION (enumtype))
16724 error ("specified mode too small for enumerated values");
16725 else
16727 use_short_enum = true;
16728 precision = TYPE_PRECISION (enumtype);
16732 for (itk = (use_short_enum ? itk_char : itk_int);
16733 itk != itk_none;
16734 itk++)
16736 underlying_type = integer_types[itk];
16737 if (underlying_type != NULL_TREE
16738 && TYPE_PRECISION (underlying_type) >= precision
16739 && TYPE_SIGN (underlying_type) == sgn)
16740 break;
16742 if (itk == itk_none)
16744 /* DR 377
16746 IF no integral type can represent all the enumerator values, the
16747 enumeration is ill-formed. */
16748 error ("no integral type can represent all of the enumerator values "
16749 "for %qT", enumtype);
16750 precision = TYPE_PRECISION (long_long_integer_type_node);
16751 underlying_type = integer_types[itk_unsigned_long_long];
16754 /* [dcl.enum]
16756 The value of sizeof() applied to an enumeration type, an object
16757 of an enumeration type, or an enumerator, is the value of sizeof()
16758 applied to the underlying type. */
16759 copy_type_enum (enumtype, underlying_type);
16761 /* Compute the minimum and maximum values for the type.
16763 [dcl.enum]
16765 For an enumeration where emin is the smallest enumerator and emax
16766 is the largest, the values of the enumeration are the values of the
16767 underlying type in the range bmin to bmax, where bmin and bmax are,
16768 respectively, the smallest and largest values of the smallest bit-
16769 field that can store emin and emax. */
16771 /* The middle-end currently assumes that types with TYPE_PRECISION
16772 narrower than their underlying type are suitably zero or sign
16773 extended to fill their mode. Similarly, it assumes that the front
16774 end assures that a value of a particular type must be within
16775 TYPE_MIN_VALUE and TYPE_MAX_VALUE.
16777 We used to set these fields based on bmin and bmax, but that led
16778 to invalid assumptions like optimizing away bounds checking. So
16779 now we just set the TYPE_PRECISION, TYPE_MIN_VALUE, and
16780 TYPE_MAX_VALUE to the values for the mode above and only restrict
16781 the ENUM_UNDERLYING_TYPE for the benefit of diagnostics. */
16782 ENUM_UNDERLYING_TYPE (enumtype)
16783 = build_distinct_type_copy (underlying_type);
16784 TYPE_PRECISION (ENUM_UNDERLYING_TYPE (enumtype)) = precision;
16785 set_min_and_max_values_for_integral_type
16786 (ENUM_UNDERLYING_TYPE (enumtype), precision, sgn);
16788 /* If -fstrict-enums, still constrain TYPE_MIN/MAX_VALUE. */
16789 if (flag_strict_enums)
16790 set_min_and_max_values_for_integral_type (enumtype, precision, sgn);
16792 else
16793 underlying_type = ENUM_UNDERLYING_TYPE (enumtype);
16795 /* If the enum is exported, mark the consts too. */
16796 bool export_p = (UNSCOPED_ENUM_P (enumtype)
16797 && DECL_MODULE_EXPORT_P (TYPE_STUB_DECL (enumtype))
16798 && at_namespace_scope_p ());
16800 /* Convert each of the enumerators to the type of the underlying
16801 type of the enumeration. */
16802 for (values = TYPE_VALUES (enumtype); values; values = TREE_CHAIN (values))
16804 decl = TREE_VALUE (values);
16805 iloc_sentinel ils (DECL_SOURCE_LOCATION (decl));
16806 if (fixed_underlying_type_p)
16807 /* If the enumeration type has a fixed underlying type, we
16808 already checked all of the enumerator values. */
16809 value = DECL_INITIAL (decl);
16810 else
16811 value = perform_implicit_conversion (underlying_type,
16812 DECL_INITIAL (decl),
16813 tf_warning_or_error);
16814 /* Do not clobber shared ints. */
16815 if (value != error_mark_node)
16817 value = copy_node (value);
16819 TREE_TYPE (value) = enumtype;
16821 DECL_INITIAL (decl) = value;
16822 if (export_p)
16823 DECL_MODULE_EXPORT_P (decl) = true;
16826 /* Fix up all variant types of this enum type. */
16827 for (t = TYPE_MAIN_VARIANT (enumtype); t; t = TYPE_NEXT_VARIANT (t))
16828 TYPE_VALUES (t) = TYPE_VALUES (enumtype);
16830 if (at_class_scope_p ()
16831 && COMPLETE_TYPE_P (current_class_type)
16832 && UNSCOPED_ENUM_P (enumtype))
16834 insert_late_enum_def_bindings (current_class_type, enumtype);
16835 /* TYPE_FIELDS needs fixup. */
16836 fixup_type_variants (current_class_type);
16839 /* Finish debugging output for this type. */
16840 rest_of_type_compilation (enumtype, namespace_bindings_p ());
16842 /* Each enumerator now has the type of its enumeration. Clear the cache
16843 so that this change in types doesn't confuse us later on. */
16844 clear_cv_and_fold_caches ();
16847 /* Finishes the enum type. This is called only the first time an
16848 enumeration is seen, be it opaque or odinary.
16849 ENUMTYPE is the type object. */
16851 void
16852 finish_enum (tree enumtype)
16854 if (processing_template_decl)
16856 if (at_function_scope_p ())
16857 add_stmt (build_min (TAG_DEFN, enumtype));
16858 return;
16861 /* If this is a forward declaration, there should not be any variants,
16862 though we can get a variant in the middle of an enum-specifier with
16863 wacky code like 'enum E { e = sizeof(const E*) };' */
16864 gcc_assert (enumtype == TYPE_MAIN_VARIANT (enumtype)
16865 && (TYPE_VALUES (enumtype)
16866 || !TYPE_NEXT_VARIANT (enumtype)));
16869 /* Build and install a CONST_DECL for an enumeration constant of the
16870 enumeration type ENUMTYPE whose NAME and VALUE (if any) are provided.
16871 Apply ATTRIBUTES if available. LOC is the location of NAME.
16872 Assignment of sequential values by default is handled here. */
16874 tree
16875 build_enumerator (tree name, tree value, tree enumtype, tree attributes,
16876 location_t loc)
16878 tree decl;
16879 tree context;
16880 tree type;
16882 /* scalar_constant_value will pull out this expression, so make sure
16883 it's folded as appropriate. */
16884 if (processing_template_decl)
16885 value = fold_non_dependent_expr (value);
16887 /* If the VALUE was erroneous, pretend it wasn't there; that will
16888 result in the enum being assigned the next value in sequence. */
16889 if (value == error_mark_node)
16890 value = NULL_TREE;
16892 /* Remove no-op casts from the value. */
16893 if (value)
16894 STRIP_TYPE_NOPS (value);
16896 if (! processing_template_decl)
16898 /* Validate and default VALUE. */
16899 if (value != NULL_TREE)
16901 if (!ENUM_UNDERLYING_TYPE (enumtype))
16903 tree tmp_value = build_expr_type_conversion (WANT_INT | WANT_ENUM,
16904 value, true);
16905 if (tmp_value)
16906 value = tmp_value;
16908 else if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
16909 (TREE_TYPE (value)))
16910 value = perform_implicit_conversion_flags
16911 (ENUM_UNDERLYING_TYPE (enumtype), value, tf_warning_or_error,
16912 LOOKUP_IMPLICIT | LOOKUP_NO_NARROWING);
16914 if (value == error_mark_node)
16915 value = NULL_TREE;
16917 if (value != NULL_TREE)
16919 if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
16920 (TREE_TYPE (value)))
16922 error_at (cp_expr_loc_or_input_loc (value),
16923 "enumerator value for %qD must have integral or "
16924 "unscoped enumeration type", name);
16925 value = NULL_TREE;
16927 else
16929 value = cxx_constant_value (value);
16931 if (TREE_CODE (value) != INTEGER_CST)
16933 error ("enumerator value for %qD is not an integer "
16934 "constant", name);
16935 value = NULL_TREE;
16941 /* Default based on previous value. */
16942 if (value == NULL_TREE)
16944 if (TYPE_VALUES (enumtype))
16946 tree prev_value;
16948 /* C++03 7.2/4: If no initializer is specified for the first
16949 enumerator, the type is an unspecified integral
16950 type. Otherwise the type is the same as the type of the
16951 initializing value of the preceding enumerator unless the
16952 incremented value is not representable in that type, in
16953 which case the type is an unspecified integral type
16954 sufficient to contain the incremented value. */
16955 prev_value = DECL_INITIAL (TREE_VALUE (TYPE_VALUES (enumtype)));
16956 if (TREE_CODE (prev_value) != INTEGER_CST)
16957 value = error_mark_node;
16958 else
16960 wi::overflow_type overflowed;
16961 tree type = TREE_TYPE (prev_value);
16962 signop sgn = TYPE_SIGN (type);
16963 widest_int wi = wi::add (wi::to_widest (prev_value), 1, sgn,
16964 &overflowed);
16965 if (!overflowed)
16967 bool pos = !wi::neg_p (wi, sgn);
16968 if (!wi::fits_to_tree_p (wi, type))
16970 unsigned int itk;
16971 for (itk = itk_int; itk != itk_none; itk++)
16973 type = integer_types[itk];
16974 if (type != NULL_TREE
16975 && (pos || !TYPE_UNSIGNED (type))
16976 && wi::fits_to_tree_p (wi, type))
16977 break;
16979 if (type && cxx_dialect < cxx11
16980 && itk > itk_unsigned_long)
16981 pedwarn (input_location, OPT_Wlong_long,
16982 pos ? G_("\
16983 incremented enumerator value is too large for %<unsigned long%>") : G_("\
16984 incremented enumerator value is too large for %<long%>"));
16986 if (type == NULL_TREE)
16987 overflowed = wi::OVF_UNKNOWN;
16988 else
16989 value = wide_int_to_tree (type, wi);
16992 if (overflowed)
16994 error ("overflow in enumeration values at %qD", name);
16995 value = error_mark_node;
16999 else
17000 value = integer_zero_node;
17003 /* Remove no-op casts from the value. */
17004 STRIP_TYPE_NOPS (value);
17006 /* If the underlying type of the enum is fixed, check whether
17007 the enumerator values fits in the underlying type. If it
17008 does not fit, the program is ill-formed [C++0x dcl.enum]. */
17009 if (ENUM_UNDERLYING_TYPE (enumtype)
17010 && value
17011 && TREE_CODE (value) == INTEGER_CST)
17013 if (!int_fits_type_p (value, ENUM_UNDERLYING_TYPE (enumtype)))
17014 error ("enumerator value %qE is outside the range of underlying "
17015 "type %qT", value, ENUM_UNDERLYING_TYPE (enumtype));
17017 /* Convert the value to the appropriate type. */
17018 value = fold_convert (ENUM_UNDERLYING_TYPE (enumtype), value);
17022 /* C++ associates enums with global, function, or class declarations. */
17023 context = current_scope ();
17025 /* Build the actual enumeration constant. Note that the enumeration
17026 constants have the underlying type of the enum (if it is fixed)
17027 or the type of their initializer (if the underlying type of the
17028 enum is not fixed):
17030 [ C++0x dcl.enum ]
17032 If the underlying type is fixed, the type of each enumerator
17033 prior to the closing brace is the underlying type; if the
17034 initializing value of an enumerator cannot be represented by
17035 the underlying type, the program is ill-formed. If the
17036 underlying type is not fixed, the type of each enumerator is
17037 the type of its initializing value.
17039 If the underlying type is not fixed, it will be computed by
17040 finish_enum and we will reset the type of this enumerator. Of
17041 course, if we're processing a template, there may be no value. */
17042 type = value ? TREE_TYPE (value) : NULL_TREE;
17044 decl = build_decl (loc, CONST_DECL, name, type);
17046 DECL_CONTEXT (decl) = enumtype;
17047 TREE_CONSTANT (decl) = 1;
17048 TREE_READONLY (decl) = 1;
17049 DECL_INITIAL (decl) = value;
17051 if (attributes)
17052 cplus_decl_attributes (&decl, attributes, 0);
17054 if (context && context == current_class_type && !SCOPED_ENUM_P (enumtype))
17056 /* In something like `struct S { enum E { i = 7 }; };' we put `i'
17057 on the TYPE_FIELDS list for `S'. (That's so that you can say
17058 things like `S::i' later.) */
17060 /* The enumerator may be getting declared outside of its enclosing
17061 class, like so:
17063 class S { public: enum E : int; }; enum S::E : int { i = 7; };
17065 For which case we need to make sure that the access of `S::i'
17066 matches the access of `S::E'. */
17067 auto cas = make_temp_override (current_access_specifier);
17068 set_current_access_from_decl (TYPE_NAME (enumtype));
17069 finish_member_declaration (decl);
17071 else
17072 pushdecl (decl);
17074 /* Add this enumeration constant to the list for this type. */
17075 TYPE_VALUES (enumtype) = tree_cons (name, decl, TYPE_VALUES (enumtype));
17077 return decl;
17080 /* Look for an enumerator with the given NAME within the enumeration
17081 type ENUMTYPE. This routine is used primarily for qualified name
17082 lookup into an enumerator in C++0x, e.g.,
17084 enum class Color { Red, Green, Blue };
17086 Color color = Color::Red;
17088 Returns the value corresponding to the enumerator, or
17089 NULL_TREE if no such enumerator was found. */
17090 tree
17091 lookup_enumerator (tree enumtype, tree name)
17093 tree e;
17094 gcc_assert (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE);
17096 e = purpose_member (name, TYPE_VALUES (enumtype));
17097 return e? TREE_VALUE (e) : NULL_TREE;
17100 /* Implement LANG_HOOKS_SIMULATE_ENUM_DECL. */
17102 tree
17103 cxx_simulate_enum_decl (location_t loc, const char *name,
17104 vec<string_int_pair> *values)
17106 location_t saved_loc = input_location;
17107 input_location = loc;
17109 tree enumtype = start_enum (get_identifier (name), NULL_TREE, NULL_TREE,
17110 NULL_TREE, false, NULL);
17111 if (!OPAQUE_ENUM_P (enumtype))
17113 error_at (loc, "multiple definition of %q#T", enumtype);
17114 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
17115 "previous definition here");
17116 return enumtype;
17118 SET_OPAQUE_ENUM_P (enumtype, false);
17119 DECL_SOURCE_LOCATION (TYPE_NAME (enumtype)) = loc;
17121 for (const string_int_pair &value : values)
17122 build_enumerator (get_identifier (value.first),
17123 build_int_cst (integer_type_node, value.second),
17124 enumtype, NULL_TREE, loc);
17126 finish_enum_value_list (enumtype);
17127 finish_enum (enumtype);
17129 input_location = saved_loc;
17130 return enumtype;
17133 /* Implement LANG_HOOKS_SIMULATE_RECORD_DECL. */
17135 tree
17136 cxx_simulate_record_decl (location_t loc, const char *name,
17137 array_slice<const tree> fields)
17139 iloc_sentinel ils (loc);
17141 tree ident = get_identifier (name);
17142 tree type = xref_tag (/*tag_code=*/record_type, ident);
17143 if (type != error_mark_node
17144 && (TREE_CODE (type) != RECORD_TYPE || COMPLETE_TYPE_P (type)))
17146 error ("redefinition of %q#T", type);
17147 type = error_mark_node;
17149 if (type == error_mark_node)
17150 return lhd_simulate_record_decl (loc, name, fields);
17152 xref_basetypes (type, NULL_TREE);
17153 type = begin_class_definition (type);
17154 if (type == error_mark_node)
17155 return lhd_simulate_record_decl (loc, name, fields);
17157 for (tree field : fields)
17158 finish_member_declaration (field);
17160 type = finish_struct (type, NULL_TREE);
17162 tree decl = build_decl (loc, TYPE_DECL, ident, type);
17163 set_underlying_type (decl);
17164 lang_hooks.decls.pushdecl (decl);
17166 return type;
17169 /* We're defining DECL. Make sure that its type is OK. */
17171 static void
17172 check_function_type (tree decl, tree current_function_parms)
17174 tree fntype = TREE_TYPE (decl);
17175 tree return_type = complete_type (TREE_TYPE (fntype));
17177 /* In a function definition, arg types must be complete. */
17178 require_complete_types_for_parms (current_function_parms);
17180 if (dependent_type_p (return_type)
17181 || type_uses_auto (return_type))
17182 return;
17183 if (!COMPLETE_OR_VOID_TYPE_P (return_type))
17185 tree args = TYPE_ARG_TYPES (fntype);
17187 error ("return type %q#T is incomplete", return_type);
17189 /* Make it return void instead. */
17190 if (TREE_CODE (fntype) == METHOD_TYPE)
17191 fntype = build_method_type_directly (TREE_TYPE (TREE_VALUE (args)),
17192 void_type_node,
17193 TREE_CHAIN (args));
17194 else
17195 fntype = build_function_type (void_type_node, args);
17196 fntype = (cp_build_type_attribute_variant
17197 (fntype, TYPE_ATTRIBUTES (TREE_TYPE (decl))));
17198 fntype = cxx_copy_lang_qualifiers (fntype, TREE_TYPE (decl));
17199 TREE_TYPE (decl) = fntype;
17201 else
17203 abstract_virtuals_error (decl, TREE_TYPE (fntype));
17204 maybe_warn_parm_abi (TREE_TYPE (fntype),
17205 DECL_SOURCE_LOCATION (decl));
17209 /* True iff FN is an implicitly-defined default constructor. */
17211 static bool
17212 implicit_default_ctor_p (tree fn)
17214 return (DECL_CONSTRUCTOR_P (fn)
17215 && !user_provided_p (fn)
17216 && sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (fn)));
17219 /* Clobber the contents of *this to let the back end know that the object
17220 storage is dead when we enter the constructor or leave the destructor. */
17222 static tree
17223 build_clobber_this ()
17225 /* Clobbering an empty base is pointless, and harmful if its one byte
17226 TYPE_SIZE overlays real data. */
17227 if (is_empty_class (current_class_type))
17228 return void_node;
17230 /* If we have virtual bases, clobber the whole object, but only if we're in
17231 charge. If we don't have virtual bases, clobber the as-base type so we
17232 don't mess with tail padding. */
17233 bool vbases = CLASSTYPE_VBASECLASSES (current_class_type);
17235 tree ctype = current_class_type;
17236 if (!vbases)
17237 ctype = CLASSTYPE_AS_BASE (ctype);
17239 tree clobber = build_clobber (ctype);
17241 tree thisref = current_class_ref;
17242 if (ctype != current_class_type)
17244 thisref = build_nop (build_reference_type (ctype), current_class_ptr);
17245 thisref = convert_from_reference (thisref);
17248 tree exprstmt = build2 (MODIFY_EXPR, void_type_node, thisref, clobber);
17249 if (vbases)
17250 exprstmt = build_if_in_charge (exprstmt);
17252 return exprstmt;
17255 /* Create the FUNCTION_DECL for a function definition.
17256 DECLSPECS and DECLARATOR are the parts of the declaration;
17257 they describe the function's name and the type it returns,
17258 but twisted together in a fashion that parallels the syntax of C.
17260 FLAGS is a bitwise or of SF_PRE_PARSED (indicating that the
17261 DECLARATOR is really the DECL for the function we are about to
17262 process and that DECLSPECS should be ignored), SF_INCLASS_INLINE
17263 indicating that the function is an inline defined in-class.
17265 This function creates a binding context for the function body
17266 as well as setting up the FUNCTION_DECL in current_function_decl.
17268 For C++, we must first check whether that datum makes any sense.
17269 For example, "class A local_a(1,2);" means that variable local_a
17270 is an aggregate of type A, which should have a constructor
17271 applied to it with the argument list [1, 2].
17273 On entry, DECL_INITIAL (decl1) should be NULL_TREE or error_mark_node,
17274 or may be a BLOCK if the function has been defined previously
17275 in this translation unit. On exit, DECL_INITIAL (decl1) will be
17276 error_mark_node if the function has never been defined, or
17277 a BLOCK if the function has been defined somewhere. */
17279 bool
17280 start_preparsed_function (tree decl1, tree attrs, int flags)
17282 tree ctype = NULL_TREE;
17283 bool doing_friend = false;
17285 /* Sanity check. */
17286 gcc_assert (VOID_TYPE_P (TREE_VALUE (void_list_node)));
17287 gcc_assert (TREE_CHAIN (void_list_node) == NULL_TREE);
17289 tree fntype = TREE_TYPE (decl1);
17290 if (TREE_CODE (fntype) == METHOD_TYPE)
17291 ctype = TYPE_METHOD_BASETYPE (fntype);
17292 else
17294 ctype = DECL_FRIEND_CONTEXT (decl1);
17296 if (ctype)
17297 doing_friend = true;
17300 if (DECL_DECLARED_INLINE_P (decl1)
17301 && lookup_attribute ("noinline", attrs))
17302 warning_at (DECL_SOURCE_LOCATION (decl1), 0,
17303 "inline function %qD given attribute %qs", decl1, "noinline");
17305 /* Handle gnu_inline attribute. */
17306 if (GNU_INLINE_P (decl1))
17308 DECL_EXTERNAL (decl1) = 1;
17309 DECL_NOT_REALLY_EXTERN (decl1) = 0;
17310 DECL_INTERFACE_KNOWN (decl1) = 1;
17311 DECL_DISREGARD_INLINE_LIMITS (decl1) = 1;
17314 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl1))
17315 /* This is a constructor, we must ensure that any default args
17316 introduced by this definition are propagated to the clones
17317 now. The clones are used directly in overload resolution. */
17318 adjust_clone_args (decl1);
17320 /* Sometimes we don't notice that a function is a static member, and
17321 build a METHOD_TYPE for it. Fix that up now. */
17322 gcc_assert (!(ctype != NULL_TREE && DECL_STATIC_FUNCTION_P (decl1)
17323 && TREE_CODE (TREE_TYPE (decl1)) == METHOD_TYPE));
17325 /* Set up current_class_type, and enter the scope of the class, if
17326 appropriate. */
17327 if (ctype)
17328 push_nested_class (ctype);
17329 else if (DECL_STATIC_FUNCTION_P (decl1))
17330 push_nested_class (DECL_CONTEXT (decl1));
17332 /* Now that we have entered the scope of the class, we must restore
17333 the bindings for any template parameters surrounding DECL1, if it
17334 is an inline member template. (Order is important; consider the
17335 case where a template parameter has the same name as a field of
17336 the class.) It is not until after this point that
17337 PROCESSING_TEMPLATE_DECL is guaranteed to be set up correctly. */
17338 if (flags & SF_INCLASS_INLINE)
17339 maybe_begin_member_template_processing (decl1);
17341 /* Effective C++ rule 15. */
17342 if (warn_ecpp
17343 && DECL_ASSIGNMENT_OPERATOR_P (decl1)
17344 && DECL_OVERLOADED_OPERATOR_IS (decl1, NOP_EXPR)
17345 && VOID_TYPE_P (TREE_TYPE (fntype)))
17346 warning (OPT_Weffc__,
17347 "%<operator=%> should return a reference to %<*this%>");
17349 /* Make the init_value nonzero so pushdecl knows this is not tentative.
17350 error_mark_node is replaced below (in poplevel) with the BLOCK. */
17351 if (!DECL_INITIAL (decl1))
17352 DECL_INITIAL (decl1) = error_mark_node;
17354 /* This function exists in static storage.
17355 (This does not mean `static' in the C sense!) */
17356 TREE_STATIC (decl1) = 1;
17358 /* We must call push_template_decl after current_class_type is set
17359 up. (If we are processing inline definitions after exiting a
17360 class scope, current_class_type will be NULL_TREE until set above
17361 by push_nested_class.) */
17362 if (processing_template_decl)
17364 tree newdecl1 = push_template_decl (decl1, doing_friend);
17365 if (newdecl1 == error_mark_node)
17367 if (ctype || DECL_STATIC_FUNCTION_P (decl1))
17368 pop_nested_class ();
17369 return false;
17371 decl1 = newdecl1;
17374 /* Make sure the parameter and return types are reasonable. When
17375 you declare a function, these types can be incomplete, but they
17376 must be complete when you define the function. */
17377 check_function_type (decl1, DECL_ARGUMENTS (decl1));
17379 /* Build the return declaration for the function. */
17380 tree restype = TREE_TYPE (fntype);
17382 if (DECL_RESULT (decl1) == NULL_TREE)
17384 /* In a template instantiation, copy the return type location. When
17385 parsing, the location will be set in grokdeclarator. */
17386 location_t loc = input_location;
17387 if (DECL_TEMPLATE_INSTANTIATION (decl1))
17389 tree tmpl = template_for_substitution (decl1);
17390 if (tree res = DECL_RESULT (DECL_TEMPLATE_RESULT (tmpl)))
17391 loc = DECL_SOURCE_LOCATION (res);
17394 tree resdecl = build_decl (loc, RESULT_DECL, 0, restype);
17395 DECL_ARTIFICIAL (resdecl) = 1;
17396 DECL_IGNORED_P (resdecl) = 1;
17397 DECL_RESULT (decl1) = resdecl;
17399 cp_apply_type_quals_to_decl (cp_type_quals (restype), resdecl);
17402 /* Record the decl so that the function name is defined.
17403 If we already have a decl for this name, and it is a FUNCTION_DECL,
17404 use the old decl. */
17405 if (!processing_template_decl && !(flags & SF_PRE_PARSED))
17407 /* A specialization is not used to guide overload resolution. */
17408 if (!DECL_FUNCTION_MEMBER_P (decl1)
17409 && !(DECL_USE_TEMPLATE (decl1) &&
17410 PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl1))))
17412 tree olddecl = pushdecl (decl1);
17414 if (olddecl == error_mark_node)
17415 /* If something went wrong when registering the declaration,
17416 use DECL1; we have to have a FUNCTION_DECL to use when
17417 parsing the body of the function. */
17419 else
17421 /* Otherwise, OLDDECL is either a previous declaration
17422 of the same function or DECL1 itself. */
17424 if (warn_missing_declarations
17425 && olddecl == decl1
17426 && !DECL_MAIN_P (decl1)
17427 && TREE_PUBLIC (decl1)
17428 && !DECL_DECLARED_INLINE_P (decl1))
17430 tree context;
17432 /* Check whether DECL1 is in an anonymous
17433 namespace. */
17434 for (context = DECL_CONTEXT (decl1);
17435 context;
17436 context = DECL_CONTEXT (context))
17438 if (TREE_CODE (context) == NAMESPACE_DECL
17439 && DECL_NAME (context) == NULL_TREE)
17440 break;
17443 if (context == NULL)
17444 warning_at (DECL_SOURCE_LOCATION (decl1),
17445 OPT_Wmissing_declarations,
17446 "no previous declaration for %qD", decl1);
17449 decl1 = olddecl;
17452 else
17454 /* We need to set the DECL_CONTEXT. */
17455 if (!DECL_CONTEXT (decl1) && DECL_TEMPLATE_INFO (decl1))
17456 DECL_CONTEXT (decl1) = DECL_CONTEXT (DECL_TI_TEMPLATE (decl1));
17458 fntype = TREE_TYPE (decl1);
17459 restype = TREE_TYPE (fntype);
17461 /* If #pragma weak applies, mark the decl appropriately now.
17462 The pragma only applies to global functions. Because
17463 determining whether or not the #pragma applies involves
17464 computing the mangled name for the declaration, we cannot
17465 apply the pragma until after we have merged this declaration
17466 with any previous declarations; if the original declaration
17467 has a linkage specification, that specification applies to
17468 the definition as well, and may affect the mangled name. */
17469 if (DECL_FILE_SCOPE_P (decl1))
17470 maybe_apply_pragma_weak (decl1);
17473 /* We are now in the scope of the function being defined. */
17474 current_function_decl = decl1;
17476 /* Save the parm names or decls from this function's declarator
17477 where store_parm_decls will find them. */
17478 tree current_function_parms = DECL_ARGUMENTS (decl1);
17480 /* Let the user know we're compiling this function. */
17481 announce_function (decl1);
17483 gcc_assert (DECL_INITIAL (decl1));
17485 /* This function may already have been parsed, in which case just
17486 return; our caller will skip over the body without parsing. */
17487 if (DECL_INITIAL (decl1) != error_mark_node)
17488 return true;
17490 /* Initialize RTL machinery. We cannot do this until
17491 CURRENT_FUNCTION_DECL and DECL_RESULT are set up. We do this
17492 even when processing a template; this is how we get
17493 CFUN set up, and our per-function variables initialized.
17494 FIXME factor out the non-RTL stuff. */
17495 cp_binding_level *bl = current_binding_level;
17496 allocate_struct_function (decl1, processing_template_decl);
17498 /* Initialize the language data structures. Whenever we start
17499 a new function, we destroy temporaries in the usual way. */
17500 cfun->language = ggc_cleared_alloc<language_function> ();
17501 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
17502 current_binding_level = bl;
17504 /* If we are (erroneously) defining a function that we have already
17505 defined before, wipe out what we knew before. */
17506 gcc_checking_assert (!DECL_PENDING_INLINE_P (decl1));
17507 FNDECL_USED_AUTO (decl1) = false;
17508 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = NULL;
17510 if (!processing_template_decl && type_uses_auto (restype))
17512 FNDECL_USED_AUTO (decl1) = true;
17513 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = restype;
17516 /* Start the statement-tree, start the tree now. */
17517 DECL_SAVED_TREE (decl1) = push_stmt_list ();
17519 if (ctype && !doing_friend && !DECL_STATIC_FUNCTION_P (decl1))
17521 /* We know that this was set up by `grokclassfn'. We do not
17522 wait until `store_parm_decls', since evil parse errors may
17523 never get us to that point. Here we keep the consistency
17524 between `current_class_type' and `current_class_ptr'. */
17525 tree t = DECL_ARGUMENTS (decl1);
17527 gcc_assert (t != NULL_TREE && TREE_CODE (t) == PARM_DECL);
17528 gcc_assert (TYPE_PTR_P (TREE_TYPE (t)));
17530 cp_function_chain->x_current_class_ref
17531 = cp_build_fold_indirect_ref (t);
17532 /* Set this second to avoid shortcut in cp_build_indirect_ref. */
17533 cp_function_chain->x_current_class_ptr = t;
17535 /* Constructors and destructors need to know whether they're "in
17536 charge" of initializing virtual base classes. */
17537 t = DECL_CHAIN (t);
17538 if (DECL_HAS_IN_CHARGE_PARM_P (decl1))
17540 current_in_charge_parm = t;
17541 t = DECL_CHAIN (t);
17543 if (DECL_HAS_VTT_PARM_P (decl1))
17545 gcc_assert (DECL_NAME (t) == vtt_parm_identifier);
17546 current_vtt_parm = t;
17550 bool honor_interface = (!DECL_TEMPLATE_INSTANTIATION (decl1)
17551 /* Implicitly-defined methods (like the
17552 destructor for a class in which no destructor
17553 is explicitly declared) must not be defined
17554 until their definition is needed. So, we
17555 ignore interface specifications for
17556 compiler-generated functions. */
17557 && !DECL_ARTIFICIAL (decl1));
17558 struct c_fileinfo *finfo
17559 = get_fileinfo (LOCATION_FILE (DECL_SOURCE_LOCATION (decl1)));
17561 if (processing_template_decl)
17562 /* Don't mess with interface flags. */;
17563 else if (DECL_INTERFACE_KNOWN (decl1))
17565 tree ctx = decl_function_context (decl1);
17567 if (DECL_NOT_REALLY_EXTERN (decl1))
17568 DECL_EXTERNAL (decl1) = 0;
17570 if (ctx != NULL_TREE && vague_linkage_p (ctx))
17571 /* This is a function in a local class in an extern inline
17572 or template function. */
17573 comdat_linkage (decl1);
17575 /* If this function belongs to an interface, it is public.
17576 If it belongs to someone else's interface, it is also external.
17577 This only affects inlines and template instantiations. */
17578 else if (!finfo->interface_unknown && honor_interface)
17580 if (DECL_DECLARED_INLINE_P (decl1)
17581 || DECL_TEMPLATE_INSTANTIATION (decl1))
17583 DECL_EXTERNAL (decl1)
17584 = (finfo->interface_only
17585 || (DECL_DECLARED_INLINE_P (decl1)
17586 && ! flag_implement_inlines
17587 && !DECL_VINDEX (decl1)));
17589 /* For WIN32 we also want to put these in linkonce sections. */
17590 maybe_make_one_only (decl1);
17592 else
17593 DECL_EXTERNAL (decl1) = 0;
17594 DECL_INTERFACE_KNOWN (decl1) = 1;
17595 /* If this function is in an interface implemented in this file,
17596 make sure that the back end knows to emit this function
17597 here. */
17598 if (!DECL_EXTERNAL (decl1))
17599 mark_needed (decl1);
17601 else if (finfo->interface_unknown && finfo->interface_only
17602 && honor_interface)
17604 /* If MULTIPLE_SYMBOL_SPACES is defined and we saw a #pragma
17605 interface, we will have both finfo->interface_unknown and
17606 finfo->interface_only set. In that case, we don't want to
17607 use the normal heuristics because someone will supply a
17608 #pragma implementation elsewhere, and deducing it here would
17609 produce a conflict. */
17610 comdat_linkage (decl1);
17611 DECL_EXTERNAL (decl1) = 0;
17612 DECL_INTERFACE_KNOWN (decl1) = 1;
17613 DECL_DEFER_OUTPUT (decl1) = 1;
17615 else
17617 /* This is a definition, not a reference.
17618 So clear DECL_EXTERNAL, unless this is a GNU extern inline. */
17619 if (!GNU_INLINE_P (decl1))
17620 DECL_EXTERNAL (decl1) = 0;
17622 if ((DECL_DECLARED_INLINE_P (decl1)
17623 || DECL_TEMPLATE_INSTANTIATION (decl1))
17624 && ! DECL_INTERFACE_KNOWN (decl1))
17625 DECL_DEFER_OUTPUT (decl1) = 1;
17626 else
17627 DECL_INTERFACE_KNOWN (decl1) = 1;
17630 /* Determine the ELF visibility attribute for the function. We must not
17631 do this before calling "pushdecl", as we must allow "duplicate_decls"
17632 to merge any attributes appropriately. We also need to wait until
17633 linkage is set. */
17634 if (!DECL_CLONED_FUNCTION_P (decl1))
17635 determine_visibility (decl1);
17637 if (!processing_template_decl)
17638 maybe_instantiate_noexcept (decl1);
17640 begin_scope (sk_function_parms, decl1);
17642 ++function_depth;
17644 start_fname_decls ();
17646 store_parm_decls (current_function_parms);
17648 start_function_contracts (decl1);
17650 if (!processing_template_decl
17651 && (flag_lifetime_dse > 1)
17652 && DECL_CONSTRUCTOR_P (decl1)
17653 && !DECL_CLONED_FUNCTION_P (decl1)
17654 /* Clobbering an empty base is harmful if it overlays real data. */
17655 && !is_empty_class (current_class_type)
17656 /* We can't clobber safely for an implicitly-defined default constructor
17657 because part of the initialization might happen before we enter the
17658 constructor, via AGGR_INIT_ZERO_FIRST (c++/68006). */
17659 && !implicit_default_ctor_p (decl1))
17660 finish_expr_stmt (build_clobber_this ());
17662 if (!processing_template_decl
17663 && DECL_CONSTRUCTOR_P (decl1)
17664 && sanitize_flags_p (SANITIZE_VPTR)
17665 && !DECL_CLONED_FUNCTION_P (decl1)
17666 && !implicit_default_ctor_p (decl1))
17667 cp_ubsan_maybe_initialize_vtbl_ptrs (current_class_ptr);
17669 if (!DECL_OMP_DECLARE_REDUCTION_P (decl1))
17670 start_lambda_scope (decl1);
17672 return true;
17676 /* Like start_preparsed_function, except that instead of a
17677 FUNCTION_DECL, this function takes DECLSPECS and DECLARATOR.
17679 Returns true on success. If the DECLARATOR is not suitable
17680 for a function, we return false, which tells the parser to
17681 skip the entire function. */
17683 bool
17684 start_function (cp_decl_specifier_seq *declspecs,
17685 const cp_declarator *declarator,
17686 tree attrs)
17688 tree decl1;
17690 decl1 = grokdeclarator (declarator, declspecs, FUNCDEF, 1, &attrs);
17691 invoke_plugin_callbacks (PLUGIN_START_PARSE_FUNCTION, decl1);
17692 if (decl1 == error_mark_node)
17693 return false;
17695 if (DECL_MAIN_P (decl1))
17696 /* main must return int. grokfndecl should have corrected it
17697 (and issued a diagnostic) if the user got it wrong. */
17698 gcc_assert (same_type_p (TREE_TYPE (TREE_TYPE (decl1)),
17699 integer_type_node));
17701 return start_preparsed_function (decl1, attrs, /*flags=*/SF_DEFAULT);
17704 /* Returns true iff an EH_SPEC_BLOCK should be created in the body of
17705 FN. */
17707 static bool
17708 use_eh_spec_block (tree fn)
17710 return (flag_exceptions && flag_enforce_eh_specs
17711 && !processing_template_decl
17712 /* We insert the EH_SPEC_BLOCK only in the original
17713 function; then, it is copied automatically to the
17714 clones. */
17715 && !DECL_CLONED_FUNCTION_P (fn)
17716 /* Implicitly-generated constructors and destructors have
17717 exception specifications. However, those specifications
17718 are the union of the possible exceptions specified by the
17719 constructors/destructors for bases and members, so no
17720 unallowed exception will ever reach this function. By
17721 not creating the EH_SPEC_BLOCK we save a little memory,
17722 and we avoid spurious warnings about unreachable
17723 code. */
17724 && !DECL_DEFAULTED_FN (fn)
17725 && !type_throw_all_p (TREE_TYPE (fn)));
17728 /* Helper function to push ARGS into the current lexical scope. DECL
17729 is the function declaration. NONPARMS is used to handle enum
17730 constants. */
17732 void
17733 do_push_parm_decls (tree decl, tree args, tree *nonparms)
17735 /* If we're doing semantic analysis, then we'll call pushdecl
17736 for each of these. We must do them in reverse order so that
17737 they end in the correct forward order. */
17738 args = nreverse (args);
17740 tree next;
17741 for (tree parm = args; parm; parm = next)
17743 next = DECL_CHAIN (parm);
17744 if (TREE_CODE (parm) == PARM_DECL)
17745 pushdecl (parm);
17746 else if (nonparms)
17748 /* If we find an enum constant or a type tag, put it aside for
17749 the moment. */
17750 TREE_CHAIN (parm) = NULL_TREE;
17751 *nonparms = chainon (*nonparms, parm);
17755 /* Get the decls in their original chain order and record in the
17756 function. This is all and only the PARM_DECLs that were
17757 pushed into scope by the loop above. */
17758 DECL_ARGUMENTS (decl) = get_local_decls ();
17761 /* Store the parameter declarations into the current function declaration.
17762 This is called after parsing the parameter declarations, before
17763 digesting the body of the function.
17765 Also install to binding contour return value identifier, if any. */
17767 static void
17768 store_parm_decls (tree current_function_parms)
17770 tree fndecl = current_function_decl;
17772 /* This is a chain of any other decls that came in among the parm
17773 declarations. If a parm is declared with enum {foo, bar} x;
17774 then CONST_DECLs for foo and bar are put here. */
17775 tree nonparms = NULL_TREE;
17777 if (current_function_parms)
17779 /* This case is when the function was defined with an ANSI prototype.
17780 The parms already have decls, so we need not do anything here
17781 except record them as in effect
17782 and complain if any redundant old-style parm decls were written. */
17784 tree specparms = current_function_parms;
17786 /* Must clear this because it might contain TYPE_DECLs declared
17787 at class level. */
17788 current_binding_level->names = NULL;
17790 do_push_parm_decls (fndecl, specparms, &nonparms);
17792 else
17793 DECL_ARGUMENTS (fndecl) = NULL_TREE;
17795 /* Now store the final chain of decls for the arguments
17796 as the decl-chain of the current lexical scope.
17797 Put the enumerators in as well, at the front so that
17798 DECL_ARGUMENTS is not modified. */
17799 current_binding_level->names = chainon (nonparms, DECL_ARGUMENTS (fndecl));
17801 if (use_eh_spec_block (current_function_decl))
17802 current_eh_spec_block = begin_eh_spec_block ();
17806 /* Set the return value of the [cd]tor if the ABI wants that. */
17808 void
17809 maybe_return_this (void)
17811 if (targetm.cxx.cdtor_returns_this ())
17813 /* Return the address of the object. */
17814 tree val = DECL_ARGUMENTS (current_function_decl);
17815 suppress_warning (val, OPT_Wuse_after_free);
17816 val = fold_convert (TREE_TYPE (DECL_RESULT (current_function_decl)), val);
17817 val = build2 (MODIFY_EXPR, TREE_TYPE (val),
17818 DECL_RESULT (current_function_decl), val);
17819 tree exprstmt = build_stmt (input_location, RETURN_EXPR, val);
17820 add_stmt (exprstmt);
17824 /* Do all the processing for the beginning of a destructor; set up the
17825 vtable pointers and cleanups for bases and members. */
17827 static void
17828 begin_destructor_body (void)
17830 tree compound_stmt;
17832 /* If the CURRENT_CLASS_TYPE is incomplete, we will have already
17833 issued an error message. We still want to try to process the
17834 body of the function, but initialize_vtbl_ptrs will crash if
17835 TYPE_BINFO is NULL. */
17836 if (COMPLETE_TYPE_P (current_class_type))
17838 compound_stmt = begin_compound_stmt (0);
17839 /* Make all virtual function table pointers in non-virtual base
17840 classes point to CURRENT_CLASS_TYPE's virtual function
17841 tables. */
17842 initialize_vtbl_ptrs (current_class_ptr);
17843 finish_compound_stmt (compound_stmt);
17845 if (flag_lifetime_dse
17846 /* Clobbering an empty base is harmful if it overlays real data. */
17847 && !is_empty_class (current_class_type))
17849 if (sanitize_flags_p (SANITIZE_VPTR)
17850 && (flag_sanitize_recover & SANITIZE_VPTR) == 0
17851 && TYPE_CONTAINS_VPTR_P (current_class_type))
17853 tree binfo = TYPE_BINFO (current_class_type);
17854 tree ref
17855 = cp_build_fold_indirect_ref (current_class_ptr);
17857 tree vtbl_ptr = build_vfield_ref (ref, TREE_TYPE (binfo));
17858 tree vtbl = build_zero_cst (TREE_TYPE (vtbl_ptr));
17859 tree stmt = cp_build_modify_expr (input_location, vtbl_ptr,
17860 NOP_EXPR, vtbl,
17861 tf_warning_or_error);
17862 /* If the vptr is shared with some virtual nearly empty base,
17863 don't clear it if not in charge, the dtor of the virtual
17864 nearly empty base will do that later. */
17865 if (CLASSTYPE_VBASECLASSES (current_class_type))
17867 tree c = current_class_type;
17868 while (CLASSTYPE_PRIMARY_BINFO (c))
17870 if (BINFO_VIRTUAL_P (CLASSTYPE_PRIMARY_BINFO (c)))
17872 stmt = convert_to_void (stmt, ICV_STATEMENT,
17873 tf_warning_or_error);
17874 stmt = build_if_in_charge (stmt);
17875 break;
17877 c = BINFO_TYPE (CLASSTYPE_PRIMARY_BINFO (c));
17880 finish_decl_cleanup (NULL_TREE, stmt);
17882 else
17883 finish_decl_cleanup (NULL_TREE, build_clobber_this ());
17886 /* And insert cleanups for our bases and members so that they
17887 will be properly destroyed if we throw. */
17888 push_base_cleanups ();
17892 /* Do the necessary processing for the beginning of a function body, which
17893 in this case includes member-initializers, but not the catch clauses of
17894 a function-try-block. Currently, this means opening a binding level
17895 for the member-initializers (in a ctor), member cleanups (in a dtor),
17896 and capture proxies (in a lambda operator()). */
17898 tree
17899 begin_function_body (void)
17901 if (! FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
17902 return NULL_TREE;
17904 if (processing_template_decl)
17905 /* Do nothing now. */;
17906 else
17907 /* Always keep the BLOCK node associated with the outermost pair of
17908 curly braces of a function. These are needed for correct
17909 operation of dwarfout.c. */
17910 keep_next_level (true);
17912 tree stmt = begin_compound_stmt (BCS_FN_BODY);
17914 if (processing_template_decl)
17915 /* Do nothing now. */;
17916 else if (DECL_DESTRUCTOR_P (current_function_decl))
17917 begin_destructor_body ();
17919 return stmt;
17922 /* Do the processing for the end of a function body. Currently, this means
17923 closing out the cleanups for fully-constructed bases and members, and in
17924 the case of the destructor, deleting the object if desired. Again, this
17925 is only meaningful for [cd]tors, since they are the only functions where
17926 there is a significant distinction between the main body and any
17927 function catch clauses. Handling, say, main() return semantics here
17928 would be wrong, as flowing off the end of a function catch clause for
17929 main() would also need to return 0. */
17931 void
17932 finish_function_body (tree compstmt)
17934 if (compstmt == NULL_TREE)
17935 return;
17937 /* Close the block. */
17938 finish_compound_stmt (compstmt);
17940 if (processing_template_decl)
17941 /* Do nothing now. */;
17942 else if (DECL_CONSTRUCTOR_P (current_function_decl)
17943 || DECL_DESTRUCTOR_P (current_function_decl))
17944 maybe_return_this ();
17947 /* Given a function, returns the BLOCK corresponding to the outermost level
17948 of curly braces, skipping the artificial block created for constructor
17949 initializers. */
17951 tree
17952 outer_curly_brace_block (tree fndecl)
17954 tree block = DECL_INITIAL (fndecl);
17955 if (BLOCK_OUTER_CURLY_BRACE_P (block))
17956 return block;
17957 block = BLOCK_SUBBLOCKS (block);
17958 if (BLOCK_OUTER_CURLY_BRACE_P (block))
17959 return block;
17960 block = BLOCK_SUBBLOCKS (block);
17961 gcc_assert (BLOCK_OUTER_CURLY_BRACE_P (block));
17962 return block;
17965 /* If FNDECL is a class's key method, add the class to the list of
17966 keyed classes that should be emitted. */
17968 static void
17969 record_key_method_defined (tree fndecl)
17971 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
17972 && DECL_VIRTUAL_P (fndecl)
17973 && !processing_template_decl)
17975 tree fnclass = DECL_CONTEXT (fndecl);
17976 if (fndecl == CLASSTYPE_KEY_METHOD (fnclass))
17977 vec_safe_push (keyed_classes, fnclass);
17981 /* Attempt to add a fix-it hint to RICHLOC suggesting the insertion
17982 of "return *this;" immediately before its location, using FNDECL's
17983 first statement (if any) to give the indentation, if appropriate. */
17985 static void
17986 add_return_star_this_fixit (gcc_rich_location *richloc, tree fndecl)
17988 location_t indent = UNKNOWN_LOCATION;
17989 tree stmts = expr_first (DECL_SAVED_TREE (fndecl));
17990 if (stmts)
17991 indent = EXPR_LOCATION (stmts);
17992 richloc->add_fixit_insert_formatted ("return *this;",
17993 richloc->get_loc (),
17994 indent);
17997 /* This function carries out the subset of finish_function operations needed
17998 to emit the compiler-generated outlined helper functions used by the
17999 coroutines implementation. */
18001 static void
18002 emit_coro_helper (tree helper)
18004 /* This is a partial set of the operations done by finish_function()
18005 plus emitting the result. */
18006 set_cfun (NULL);
18007 current_function_decl = helper;
18008 begin_scope (sk_function_parms, NULL);
18009 store_parm_decls (DECL_ARGUMENTS (helper));
18010 announce_function (helper);
18011 allocate_struct_function (helper, false);
18012 cfun->language = ggc_cleared_alloc<language_function> ();
18013 poplevel (1, 0, 1);
18014 maybe_save_constexpr_fundef (helper);
18015 /* We must start each function with a clear fold cache. */
18016 clear_fold_cache ();
18017 cp_fold_function (helper);
18018 DECL_CONTEXT (DECL_RESULT (helper)) = helper;
18019 BLOCK_SUPERCONTEXT (DECL_INITIAL (helper)) = helper;
18020 /* This function has coroutine IFNs that we should handle in middle
18021 end lowering. */
18022 cfun->coroutine_component = true;
18023 cp_genericize (helper);
18024 expand_or_defer_fn (helper);
18027 /* Finish up a function declaration and compile that function
18028 all the way to assembler language output. The free the storage
18029 for the function definition. INLINE_P is TRUE if we just
18030 finished processing the body of an in-class inline function
18031 definition. (This processing will have taken place after the
18032 class definition is complete.) */
18034 tree
18035 finish_function (bool inline_p)
18037 tree fndecl = current_function_decl;
18038 tree fntype, ctype = NULL_TREE;
18039 tree resumer = NULL_TREE, destroyer = NULL_TREE;
18040 bool coro_p = flag_coroutines
18041 && !processing_template_decl
18042 && DECL_COROUTINE_P (fndecl);
18043 bool coro_emit_helpers = false;
18045 /* When we get some parse errors, we can end up without a
18046 current_function_decl, so cope. */
18047 if (fndecl == NULL_TREE)
18048 return error_mark_node;
18050 if (!DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18051 finish_lambda_scope ();
18053 if (c_dialect_objc ())
18054 objc_finish_function ();
18056 record_key_method_defined (fndecl);
18058 fntype = TREE_TYPE (fndecl);
18060 /* TREE_READONLY (fndecl) = 1;
18061 This caused &foo to be of type ptr-to-const-function
18062 which then got a warning when stored in a ptr-to-function variable. */
18064 gcc_assert (building_stmt_list_p ());
18065 /* The current function is being defined, so its DECL_INITIAL should
18066 be set, and unless there's a multiple definition, it should be
18067 error_mark_node. */
18068 gcc_assert (DECL_INITIAL (fndecl) == error_mark_node);
18070 if (coro_p)
18072 /* Only try to emit the coroutine outlined helper functions if the
18073 transforms succeeded. Otherwise, treat errors in the same way as
18074 a regular function. */
18075 coro_emit_helpers = morph_fn_to_coro (fndecl, &resumer, &destroyer);
18077 /* We should handle coroutine IFNs in middle end lowering. */
18078 cfun->coroutine_component = true;
18080 /* Do not try to process the ramp's EH unless outlining succeeded. */
18081 if (coro_emit_helpers && use_eh_spec_block (fndecl))
18082 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
18083 (TREE_TYPE (fndecl)),
18084 current_eh_spec_block);
18086 else
18087 /* For a cloned function, we've already got all the code we need;
18088 there's no need to add any extra bits. */
18089 if (!DECL_CLONED_FUNCTION_P (fndecl))
18091 /* Make it so that `main' always returns 0 by default. */
18092 if (DECL_MAIN_FREESTANDING_P (current_function_decl)
18093 && !TREE_THIS_VOLATILE (current_function_decl))
18094 finish_return_stmt (integer_zero_node);
18096 if (use_eh_spec_block (current_function_decl))
18097 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
18098 (TREE_TYPE (current_function_decl)),
18099 current_eh_spec_block);
18102 /* If we're saving up tree structure, tie off the function now. */
18103 DECL_SAVED_TREE (fndecl) = pop_stmt_list (DECL_SAVED_TREE (fndecl));
18105 finish_fname_decls ();
18107 /* This must come after expand_function_end because cleanups might
18108 have declarations (from inline functions) that need to go into
18109 this function's blocks. */
18111 /* If the current binding level isn't the outermost binding level
18112 for this function, either there is a bug, or we have experienced
18113 syntax errors and the statement tree is malformed. */
18114 if (current_binding_level->kind != sk_function_parms)
18116 /* Make sure we have already experienced errors. */
18117 gcc_assert (errorcount);
18119 /* Throw away the broken statement tree and extra binding
18120 levels. */
18121 DECL_SAVED_TREE (fndecl) = alloc_stmt_list ();
18123 while (current_binding_level->kind != sk_function_parms)
18125 if (current_binding_level->kind == sk_class)
18126 pop_nested_class ();
18127 else
18128 poplevel (0, 0, 0);
18131 poplevel (1, 0, 1);
18133 /* Statements should always be full-expressions at the outermost set
18134 of curly braces for a function. */
18135 gcc_assert (stmts_are_full_exprs_p ());
18137 /* If there are no return statements in a function with auto return type,
18138 the return type is void. But if the declared type is something like
18139 auto*, this is an error. */
18140 if (!processing_template_decl && FNDECL_USED_AUTO (fndecl)
18141 && TREE_TYPE (fntype) == DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
18143 if (is_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
18144 && !current_function_returns_value
18145 && !current_function_returns_null)
18147 /* We haven't applied return type deduction because we haven't
18148 seen any return statements. Do that now. */
18149 tree node = type_uses_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
18150 do_auto_deduction (DECL_SAVED_AUTO_RETURN_TYPE (fndecl),
18151 void_node, node, tf_warning_or_error,
18152 adc_return_type);
18154 apply_deduced_return_type (fndecl, void_type_node);
18155 fntype = TREE_TYPE (fndecl);
18157 else if (!current_function_returns_value
18158 && !current_function_returns_null)
18160 error ("no return statements in function returning %qT",
18161 DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
18162 inform (input_location, "only plain %<auto%> return type can be "
18163 "deduced to %<void%>");
18167 /* Remember that we were in class scope. */
18168 if (current_class_name)
18169 ctype = current_class_type;
18171 if (DECL_DELETED_FN (fndecl))
18173 DECL_INITIAL (fndecl) = error_mark_node;
18174 DECL_SAVED_TREE (fndecl) = NULL_TREE;
18175 goto cleanup;
18178 // If this is a concept, check that the definition is reasonable.
18179 if (DECL_DECLARED_CONCEPT_P (fndecl))
18180 check_function_concept (fndecl);
18182 if (flag_openmp)
18183 if (tree attr = lookup_attribute ("omp declare variant base",
18184 DECL_ATTRIBUTES (fndecl)))
18185 omp_declare_variant_finalize (fndecl, attr);
18187 /* Complain if there's just no return statement. */
18188 if ((warn_return_type
18189 || (cxx_dialect >= cxx14
18190 && DECL_DECLARED_CONSTEXPR_P (fndecl)))
18191 && !VOID_TYPE_P (TREE_TYPE (fntype))
18192 && !dependent_type_p (TREE_TYPE (fntype))
18193 && !current_function_returns_value && !current_function_returns_null
18194 /* Don't complain if we abort or throw. */
18195 && !current_function_returns_abnormally
18196 /* Don't complain if there's an infinite loop. */
18197 && !current_function_infinite_loop
18198 /* Don't complain if we are declared noreturn. */
18199 && !TREE_THIS_VOLATILE (fndecl)
18200 && !DECL_NAME (DECL_RESULT (fndecl))
18201 && !warning_suppressed_p (fndecl, OPT_Wreturn_type)
18202 /* Structor return values (if any) are set by the compiler. */
18203 && !DECL_CONSTRUCTOR_P (fndecl)
18204 && !DECL_DESTRUCTOR_P (fndecl)
18205 && targetm.warn_func_return (fndecl))
18207 gcc_rich_location richloc (input_location);
18208 /* Potentially add a "return *this;" fix-it hint for
18209 assignment operators. */
18210 if (IDENTIFIER_ASSIGN_OP_P (DECL_NAME (fndecl)))
18212 tree valtype = TREE_TYPE (DECL_RESULT (fndecl));
18213 if (TREE_CODE (valtype) == REFERENCE_TYPE
18214 && current_class_ref
18215 && same_type_ignoring_top_level_qualifiers_p
18216 (TREE_TYPE (valtype), TREE_TYPE (current_class_ref))
18217 && global_dc->option_enabled (OPT_Wreturn_type,
18218 global_dc->lang_mask,
18219 global_dc->option_state))
18220 add_return_star_this_fixit (&richloc, fndecl);
18222 if (cxx_dialect >= cxx14
18223 && DECL_DECLARED_CONSTEXPR_P (fndecl))
18224 error_at (&richloc, "no return statement in %<constexpr%> function "
18225 "returning non-void");
18226 else if (warning_at (&richloc, OPT_Wreturn_type,
18227 "no return statement in function returning "
18228 "non-void"))
18229 suppress_warning (fndecl, OPT_Wreturn_type);
18232 /* Lambda closure members are implicitly constexpr if possible. */
18233 if (cxx_dialect >= cxx17
18234 && LAMBDA_TYPE_P (CP_DECL_CONTEXT (fndecl)))
18235 DECL_DECLARED_CONSTEXPR_P (fndecl)
18236 = ((processing_template_decl
18237 || is_valid_constexpr_fn (fndecl, /*complain*/false))
18238 && potential_constant_expression (DECL_SAVED_TREE (fndecl)));
18240 /* Save constexpr function body before it gets munged by
18241 the NRV transformation. */
18242 maybe_save_constexpr_fundef (fndecl);
18244 /* Invoke the pre-genericize plugin before we start munging things. */
18245 if (!processing_template_decl)
18246 invoke_plugin_callbacks (PLUGIN_PRE_GENERICIZE, fndecl);
18248 /* Perform delayed folding before NRV transformation. */
18249 if (!processing_template_decl
18250 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
18251 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18252 cp_fold_function (fndecl);
18254 /* Set up the named return value optimization, if we can. Candidate
18255 variables are selected in check_return_expr. */
18256 if (tree r = current_function_return_value)
18258 if (r != error_mark_node)
18259 finalize_nrv (fndecl, r);
18260 current_function_return_value = NULL_TREE;
18263 /* Must mark the RESULT_DECL as being in this function. */
18264 DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
18266 /* Set the BLOCK_SUPERCONTEXT of the outermost function scope to point
18267 to the FUNCTION_DECL node itself. */
18268 BLOCK_SUPERCONTEXT (DECL_INITIAL (fndecl)) = fndecl;
18270 /* Store the end of the function, so that we get good line number
18271 info for the epilogue. */
18272 cfun->function_end_locus = input_location;
18274 /* Complain about parameters that are only set, but never otherwise used. */
18275 if (warn_unused_but_set_parameter
18276 && !processing_template_decl
18277 && errorcount == unused_but_set_errorcount
18278 && !DECL_CLONED_FUNCTION_P (fndecl))
18280 tree decl;
18282 for (decl = DECL_ARGUMENTS (fndecl);
18283 decl;
18284 decl = DECL_CHAIN (decl))
18285 if (TREE_USED (decl)
18286 && TREE_CODE (decl) == PARM_DECL
18287 && !DECL_READ_P (decl)
18288 && DECL_NAME (decl)
18289 && !DECL_ARTIFICIAL (decl)
18290 && !warning_suppressed_p (decl,OPT_Wunused_but_set_parameter)
18291 && !DECL_IN_SYSTEM_HEADER (decl)
18292 && TREE_TYPE (decl) != error_mark_node
18293 && !TYPE_REF_P (TREE_TYPE (decl))
18294 && (!CLASS_TYPE_P (TREE_TYPE (decl))
18295 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl))))
18296 warning_at (DECL_SOURCE_LOCATION (decl),
18297 OPT_Wunused_but_set_parameter,
18298 "parameter %qD set but not used", decl);
18299 unused_but_set_errorcount = errorcount;
18302 /* Complain about locally defined typedefs that are not used in this
18303 function. */
18304 maybe_warn_unused_local_typedefs ();
18306 /* Possibly warn about unused parameters. */
18307 if (warn_unused_parameter
18308 && !processing_template_decl
18309 && !DECL_CLONED_FUNCTION_P (fndecl))
18310 do_warn_unused_parameter (fndecl);
18312 /* Genericize before inlining. */
18313 if (!processing_template_decl
18314 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
18315 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18316 cp_genericize (fndecl);
18318 /* If this function can't throw any exceptions, remember that. */
18319 if (!processing_template_decl
18320 && !cp_function_chain->can_throw
18321 && !flag_non_call_exceptions
18322 && !decl_replaceable_p (fndecl,
18323 opt_for_fn (fndecl, flag_semantic_interposition)))
18324 TREE_NOTHROW (fndecl) = 1;
18326 /* Emit the resumer and destroyer functions now, providing that we have
18327 not encountered some fatal error. */
18328 if (coro_emit_helpers)
18330 emit_coro_helper (resumer);
18331 emit_coro_helper (destroyer);
18334 cleanup:
18335 /* We're leaving the context of this function, so zap cfun. It's still in
18336 DECL_STRUCT_FUNCTION, and we'll restore it in tree_rest_of_compilation. */
18337 set_cfun (NULL);
18338 current_function_decl = NULL;
18340 /* If this is an in-class inline definition, we may have to pop the
18341 bindings for the template parameters that we added in
18342 maybe_begin_member_template_processing when start_function was
18343 called. */
18344 if (inline_p)
18345 maybe_end_member_template_processing ();
18347 /* Leave the scope of the class. */
18348 if (ctype)
18349 pop_nested_class ();
18351 --function_depth;
18353 /* Clean up. */
18354 current_function_decl = NULL_TREE;
18356 invoke_plugin_callbacks (PLUGIN_FINISH_PARSE_FUNCTION, fndecl);
18358 finish_function_contracts (fndecl);
18360 return fndecl;
18363 /* Create the FUNCTION_DECL for a function definition.
18364 DECLSPECS and DECLARATOR are the parts of the declaration;
18365 they describe the return type and the name of the function,
18366 but twisted together in a fashion that parallels the syntax of C.
18368 This function creates a binding context for the function body
18369 as well as setting up the FUNCTION_DECL in current_function_decl.
18371 Returns a FUNCTION_DECL on success.
18373 If the DECLARATOR is not suitable for a function (it defines a datum
18374 instead), we return 0, which tells yyparse to report a parse error.
18376 May return void_type_node indicating that this method is actually
18377 a friend. See grokfield for more details.
18379 Came here with a `.pushlevel' .
18381 DO NOT MAKE ANY CHANGES TO THIS CODE WITHOUT MAKING CORRESPONDING
18382 CHANGES TO CODE IN `grokfield'. */
18384 tree
18385 grokmethod (cp_decl_specifier_seq *declspecs,
18386 const cp_declarator *declarator, tree attrlist)
18388 tree fndecl = grokdeclarator (declarator, declspecs, MEMFUNCDEF, 0,
18389 &attrlist);
18391 if (fndecl == error_mark_node)
18392 return error_mark_node;
18394 if (attrlist)
18395 cplus_decl_attributes (&fndecl, attrlist, 0);
18397 /* Pass friends other than inline friend functions back. */
18398 if (fndecl == void_type_node)
18399 return fndecl;
18401 if (DECL_IN_AGGR_P (fndecl))
18403 if (DECL_CLASS_SCOPE_P (fndecl))
18404 error ("%qD is already defined in class %qT", fndecl,
18405 DECL_CONTEXT (fndecl));
18406 return error_mark_node;
18409 check_template_shadow (fndecl);
18411 /* p1779 ABI-Isolation makes inline not a default for in-class
18412 definitions in named module purview. If the user explicitly
18413 made it inline, grokdeclarator will already have done the right
18414 things. */
18415 if ((!named_module_purview_p ()
18416 || flag_module_implicit_inline
18417 /* Lambda's operator function remains inline. */
18418 || LAMBDA_TYPE_P (DECL_CONTEXT (fndecl)))
18419 /* If the user explicitly asked for this to be inline, we don't
18420 need to do more, but more importantly we want to warn if we
18421 can't inline it. */
18422 && !DECL_DECLARED_INLINE_P (fndecl))
18424 if (TREE_PUBLIC (fndecl))
18425 DECL_COMDAT (fndecl) = 1;
18426 DECL_DECLARED_INLINE_P (fndecl) = 1;
18427 /* It's ok if we can't inline this. */
18428 DECL_NO_INLINE_WARNING_P (fndecl) = 1;
18431 /* We process method specializations in finish_struct_1. */
18432 if (processing_template_decl && !DECL_TEMPLATE_SPECIALIZATION (fndecl))
18434 /* Avoid calling decl_spec_seq... until we have to. */
18435 bool friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
18436 fndecl = push_template_decl (fndecl, friendp);
18437 if (fndecl == error_mark_node)
18438 return fndecl;
18441 if (DECL_CHAIN (fndecl) && !decl_spec_seq_has_spec_p (declspecs, ds_friend))
18443 fndecl = copy_node (fndecl);
18444 TREE_CHAIN (fndecl) = NULL_TREE;
18447 cp_finish_decl (fndecl, NULL_TREE, false, NULL_TREE, 0);
18449 DECL_IN_AGGR_P (fndecl) = 1;
18450 return fndecl;
18454 /* VAR is a VAR_DECL. If its type is incomplete, remember VAR so that
18455 we can lay it out later, when and if its type becomes complete.
18457 Also handle constexpr variables where the initializer involves
18458 an unlowered PTRMEM_CST because the class isn't complete yet. */
18460 void
18461 maybe_register_incomplete_var (tree var)
18463 gcc_assert (VAR_P (var));
18465 /* Keep track of variables with incomplete types. */
18466 if (!processing_template_decl && TREE_TYPE (var) != error_mark_node
18467 && DECL_EXTERNAL (var))
18469 tree inner_type = TREE_TYPE (var);
18471 while (TREE_CODE (inner_type) == ARRAY_TYPE)
18472 inner_type = TREE_TYPE (inner_type);
18473 inner_type = TYPE_MAIN_VARIANT (inner_type);
18475 if ((!COMPLETE_TYPE_P (inner_type) && CLASS_TYPE_P (inner_type))
18476 /* RTTI TD entries are created while defining the type_info. */
18477 || (TYPE_LANG_SPECIFIC (inner_type)
18478 && TYPE_BEING_DEFINED (inner_type)))
18480 incomplete_var iv = {var, inner_type};
18481 vec_safe_push (incomplete_vars, iv);
18483 else if (!(DECL_LANG_SPECIFIC (var) && DECL_TEMPLATE_INFO (var))
18484 && decl_constant_var_p (var)
18485 && (TYPE_PTRMEM_P (inner_type) || CLASS_TYPE_P (inner_type)))
18487 /* When the outermost open class is complete we can resolve any
18488 pointers-to-members. */
18489 tree context = outermost_open_class ();
18490 incomplete_var iv = {var, context};
18491 vec_safe_push (incomplete_vars, iv);
18496 /* Called when a class type (given by TYPE) is defined. If there are
18497 any existing VAR_DECLs whose type has been completed by this
18498 declaration, update them now. */
18500 void
18501 complete_vars (tree type)
18503 unsigned ix;
18504 incomplete_var *iv;
18506 for (ix = 0; vec_safe_iterate (incomplete_vars, ix, &iv); )
18508 if (same_type_p (type, iv->incomplete_type))
18510 tree var = iv->decl;
18511 tree type = TREE_TYPE (var);
18513 if (type != error_mark_node
18514 && (TYPE_MAIN_VARIANT (strip_array_types (type))
18515 == iv->incomplete_type))
18517 /* Complete the type of the variable. */
18518 complete_type (type);
18519 cp_apply_type_quals_to_decl (cp_type_quals (type), var);
18520 if (COMPLETE_TYPE_P (type))
18521 layout_var_decl (var);
18524 /* Remove this entry from the list. */
18525 incomplete_vars->unordered_remove (ix);
18527 else
18528 ix++;
18532 /* If DECL is of a type which needs a cleanup, build and return an
18533 expression to perform that cleanup here. Return NULL_TREE if no
18534 cleanup need be done. DECL can also be a _REF when called from
18535 split_nonconstant_init_1. */
18537 tree
18538 cxx_maybe_build_cleanup (tree decl, tsubst_flags_t complain)
18540 tree type;
18541 tree attr;
18542 tree cleanup;
18544 /* Assume no cleanup is required. */
18545 cleanup = NULL_TREE;
18547 if (error_operand_p (decl))
18548 return cleanup;
18550 /* Handle "__attribute__((cleanup))". We run the cleanup function
18551 before the destructor since the destructor is what actually
18552 terminates the lifetime of the object. */
18553 if (DECL_P (decl))
18554 attr = lookup_attribute ("cleanup", DECL_ATTRIBUTES (decl));
18555 else
18556 attr = NULL_TREE;
18557 if (attr)
18559 tree id;
18560 tree fn;
18561 tree arg;
18563 /* Get the name specified by the user for the cleanup function. */
18564 id = TREE_VALUE (TREE_VALUE (attr));
18565 /* Look up the name to find the cleanup function to call. It is
18566 important to use lookup_name here because that is what is
18567 used in c-common.cc:handle_cleanup_attribute when performing
18568 initial checks on the attribute. Note that those checks
18569 include ensuring that the function found is not an overloaded
18570 function, or an object with an overloaded call operator,
18571 etc.; we can rely on the fact that the function found is an
18572 ordinary FUNCTION_DECL. */
18573 fn = lookup_name (id);
18574 arg = build_address (decl);
18575 if (!mark_used (decl, complain) && !(complain & tf_error))
18576 return error_mark_node;
18577 cleanup = cp_build_function_call_nary (fn, complain, arg, NULL_TREE);
18578 if (cleanup == error_mark_node)
18579 return error_mark_node;
18581 /* Handle ordinary C++ destructors. */
18582 type = TREE_TYPE (decl);
18583 if (type_build_dtor_call (type))
18585 int flags = LOOKUP_NORMAL|LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR;
18586 tree addr;
18587 tree call;
18589 if (TREE_CODE (type) == ARRAY_TYPE)
18590 addr = decl;
18591 else
18592 addr = build_address (decl);
18594 call = build_delete (input_location, TREE_TYPE (addr), addr,
18595 sfk_complete_destructor, flags, 0, complain);
18596 if (call == error_mark_node)
18597 cleanup = error_mark_node;
18598 else if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
18599 /* Discard the call. */;
18600 else if (decl_maybe_constant_destruction (decl, type)
18601 && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
18602 cxx_constant_dtor (call, decl);
18603 else if (cleanup)
18604 cleanup = cp_build_compound_expr (cleanup, call, complain);
18605 else
18606 cleanup = call;
18609 /* build_delete sets the location of the destructor call to the
18610 current location, even though the destructor is going to be
18611 called later, at the end of the current scope. This can lead to
18612 a "jumpy" behavior for users of debuggers when they step around
18613 the end of the block. So let's unset the location of the
18614 destructor call instead. */
18615 protected_set_expr_location (cleanup, UNKNOWN_LOCATION);
18616 if (cleanup && CONVERT_EXPR_P (cleanup))
18617 protected_set_expr_location (TREE_OPERAND (cleanup, 0), UNKNOWN_LOCATION);
18619 if (cleanup
18620 && DECL_P (decl)
18621 && !lookup_attribute ("warn_unused", TYPE_ATTRIBUTES (TREE_TYPE (decl)))
18622 /* Treat objects with destructors as used; the destructor may do
18623 something substantive. */
18624 && !mark_used (decl, complain) && !(complain & tf_error))
18625 return error_mark_node;
18627 if (cleanup && cfun && !processing_template_decl
18628 && !expr_noexcept_p (cleanup, tf_none))
18629 cp_function_chain->throwing_cleanup = true;
18631 return cleanup;
18635 /* Return the FUNCTION_TYPE that corresponds to MEMFNTYPE, which can be a
18636 FUNCTION_DECL, METHOD_TYPE, FUNCTION_TYPE, pointer or reference to
18637 METHOD_TYPE or FUNCTION_TYPE, or pointer to member function. */
18639 tree
18640 static_fn_type (tree memfntype)
18642 tree fntype;
18643 tree args;
18645 if (TYPE_PTRMEMFUNC_P (memfntype))
18646 memfntype = TYPE_PTRMEMFUNC_FN_TYPE (memfntype);
18647 if (INDIRECT_TYPE_P (memfntype)
18648 || TREE_CODE (memfntype) == FUNCTION_DECL)
18649 memfntype = TREE_TYPE (memfntype);
18650 if (TREE_CODE (memfntype) == FUNCTION_TYPE)
18651 return memfntype;
18652 gcc_assert (TREE_CODE (memfntype) == METHOD_TYPE);
18653 args = TYPE_ARG_TYPES (memfntype);
18654 fntype = build_function_type (TREE_TYPE (memfntype), TREE_CHAIN (args));
18655 fntype = apply_memfn_quals (fntype, type_memfn_quals (memfntype));
18656 fntype = (cp_build_type_attribute_variant
18657 (fntype, TYPE_ATTRIBUTES (memfntype)));
18658 fntype = cxx_copy_lang_qualifiers (fntype, memfntype);
18659 return fntype;
18662 /* DECL was originally constructed as a non-static member function,
18663 but turned out to be static. Update it accordingly. */
18665 void
18666 revert_static_member_fn (tree decl)
18668 tree stype = static_fn_type (decl);
18669 cp_cv_quals quals = type_memfn_quals (stype);
18670 cp_ref_qualifier rqual = type_memfn_rqual (stype);
18672 if (quals != TYPE_UNQUALIFIED || rqual != REF_QUAL_NONE)
18673 stype = apply_memfn_quals (stype, TYPE_UNQUALIFIED, REF_QUAL_NONE);
18675 TREE_TYPE (decl) = stype;
18677 if (DECL_ARGUMENTS (decl))
18678 DECL_ARGUMENTS (decl) = DECL_CHAIN (DECL_ARGUMENTS (decl));
18679 DECL_STATIC_FUNCTION_P (decl) = 1;
18682 /* Return which tree structure is used by T, or TS_CP_GENERIC if T is
18683 one of the language-independent trees. */
18685 enum cp_tree_node_structure_enum
18686 cp_tree_node_structure (union lang_tree_node * t)
18688 switch (TREE_CODE (&t->generic))
18690 case ARGUMENT_PACK_SELECT: return TS_CP_ARGUMENT_PACK_SELECT;
18691 case BASELINK: return TS_CP_BASELINK;
18692 case CONSTRAINT_INFO: return TS_CP_CONSTRAINT_INFO;
18693 case DEFERRED_NOEXCEPT: return TS_CP_DEFERRED_NOEXCEPT;
18694 case DEFERRED_PARSE: return TS_CP_DEFERRED_PARSE;
18695 case IDENTIFIER_NODE: return TS_CP_IDENTIFIER;
18696 case LAMBDA_EXPR: return TS_CP_LAMBDA_EXPR;
18697 case BINDING_VECTOR: return TS_CP_BINDING_VECTOR;
18698 case OVERLOAD: return TS_CP_OVERLOAD;
18699 case PTRMEM_CST: return TS_CP_PTRMEM;
18700 case STATIC_ASSERT: return TS_CP_STATIC_ASSERT;
18701 case TEMPLATE_DECL: return TS_CP_TEMPLATE_DECL;
18702 case TEMPLATE_INFO: return TS_CP_TEMPLATE_INFO;
18703 case TEMPLATE_PARM_INDEX: return TS_CP_TPI;
18704 case TRAIT_EXPR: return TS_CP_TRAIT_EXPR;
18705 case USERDEF_LITERAL: return TS_CP_USERDEF_LITERAL;
18706 default: return TS_CP_GENERIC;
18710 bool
18711 cp_missing_noreturn_ok_p (tree decl)
18713 /* A missing noreturn is ok for the `main' function. */
18714 return DECL_MAIN_P (decl);
18717 /* Return the decl used to identify the COMDAT group into which DECL should
18718 be placed. */
18720 tree
18721 cxx_comdat_group (tree decl)
18723 /* Virtual tables, construction virtual tables, and virtual table
18724 tables all go in a single COMDAT group, named after the primary
18725 virtual table. */
18726 if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
18727 decl = CLASSTYPE_VTABLES (DECL_CONTEXT (decl));
18728 /* For all other DECLs, the COMDAT group is the mangled name of the
18729 declaration itself. */
18730 else
18732 while (DECL_THUNK_P (decl))
18734 /* If TARGET_USE_LOCAL_THUNK_ALIAS_P, use_thunk puts the thunk
18735 into the same section as the target function. In that case
18736 we must return target's name. */
18737 tree target = THUNK_TARGET (decl);
18738 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (target)
18739 && DECL_SECTION_NAME (target) != NULL
18740 && DECL_ONE_ONLY (target))
18741 decl = target;
18742 else
18743 break;
18747 return decl;
18750 /* Returns the return type for FN as written by the user, which may include
18751 a placeholder for a deduced return type. */
18753 tree
18754 fndecl_declared_return_type (tree fn)
18756 fn = STRIP_TEMPLATE (fn);
18757 if (FNDECL_USED_AUTO (fn))
18758 return DECL_SAVED_AUTO_RETURN_TYPE (fn);
18760 return TREE_TYPE (TREE_TYPE (fn));
18763 /* Returns true iff DECL is a variable or function declared with an auto type
18764 that has not yet been deduced to a real type. */
18766 bool
18767 undeduced_auto_decl (tree decl)
18769 if (cxx_dialect < cxx11)
18770 return false;
18771 STRIP_ANY_LOCATION_WRAPPER (decl);
18772 return ((VAR_OR_FUNCTION_DECL_P (decl)
18773 || TREE_CODE (decl) == TEMPLATE_DECL)
18774 && type_uses_auto (TREE_TYPE (decl)));
18777 /* Complain if DECL has an undeduced return type. */
18779 bool
18780 require_deduced_type (tree decl, tsubst_flags_t complain)
18782 if (undeduced_auto_decl (decl))
18784 if (TREE_CODE (decl) == FUNCTION_DECL
18785 && fndecl_built_in_p (decl, BUILT_IN_FRONTEND)
18786 && DECL_FE_FUNCTION_CODE (decl) == CP_BUILT_IN_SOURCE_LOCATION)
18788 /* Set the return type of __builtin_source_location. */
18789 tree type = get_source_location_impl_type ();
18790 if (type == error_mark_node)
18792 inform (input_location, "using %qs", "__builtin_source_location");
18793 return false;
18795 type = cp_build_qualified_type (type, TYPE_QUAL_CONST);
18796 type = build_pointer_type (type);
18797 apply_deduced_return_type (decl, type);
18798 return true;
18801 if (warning_suppressed_p (decl) && seen_error ())
18802 /* We probably already complained about deduction failure. */;
18803 else if (complain & tf_error)
18804 error ("use of %qD before deduction of %<auto%>", decl);
18805 note_failed_type_completion_for_satisfaction (decl);
18806 return false;
18808 return true;
18811 /* Create a representation of the explicit-specifier with
18812 constant-expression of EXPR. COMPLAIN is as for tsubst. */
18814 tree
18815 build_explicit_specifier (tree expr, tsubst_flags_t complain)
18817 if (check_for_bare_parameter_packs (expr))
18818 return error_mark_node;
18820 if (instantiation_dependent_expression_p (expr))
18821 /* Wait for instantiation, tsubst_function_decl will handle it. */
18822 return expr;
18824 expr = build_converted_constant_bool_expr (expr, complain);
18825 expr = instantiate_non_dependent_expr (expr, complain);
18826 expr = cxx_constant_value (expr, complain);
18827 return expr;
18830 #include "gt-cp-decl.h"