c++: redeclared hidden friend [PR105761]
[official-gcc.git] / gcc / cp / decl.cc
blob90b12d69414c851966bce0988f9ddeaa1a0bcde9
1 /* Process declarations and variables for -*- C++ -*- compiler.
2 Copyright (C) 1988-2022 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 #include "system.h"
31 #include "coretypes.h"
32 #include "target.h"
33 #include "c-family/c-target.h"
34 #include "cp-tree.h"
35 #include "timevar.h"
36 #include "stringpool.h"
37 #include "cgraph.h"
38 #include "stor-layout.h"
39 #include "varasm.h"
40 #include "attribs.h"
41 #include "flags.h"
42 #include "tree-iterator.h"
43 #include "decl.h"
44 #include "intl.h"
45 #include "toplev.h"
46 #include "c-family/c-objc.h"
47 #include "c-family/c-pragma.h"
48 #include "c-family/c-ubsan.h"
49 #include "debug.h"
50 #include "plugin.h"
51 #include "builtins.h"
52 #include "gimplify.h"
53 #include "asan.h"
54 #include "gcc-rich-location.h"
55 #include "langhooks.h"
56 #include "context.h" /* For 'g'. */
57 #include "omp-general.h"
58 #include "omp-offload.h" /* For offload_vars. */
59 #include "opts.h"
60 #include "langhooks-def.h" /* For lhd_simulate_record_decl */
62 /* Possible cases of bad specifiers type used by bad_specifiers. */
63 enum bad_spec_place {
64 BSP_VAR, /* variable */
65 BSP_PARM, /* parameter */
66 BSP_TYPE, /* type */
67 BSP_FIELD /* field */
70 static const char *redeclaration_error_message (tree, tree);
72 static int decl_jump_unsafe (tree);
73 static void require_complete_types_for_parms (tree);
74 static tree grok_reference_init (tree, tree, tree, int);
75 static tree grokvardecl (tree, tree, tree, const cp_decl_specifier_seq *,
76 int, int, int, bool, int, tree, location_t);
77 static void check_static_variable_definition (tree, tree);
78 static void record_unknown_type (tree, const char *);
79 static int member_function_or_else (tree, tree, enum overload_flags);
80 static tree local_variable_p_walkfn (tree *, int *, void *);
81 static const char *tag_name (enum tag_types);
82 static tree lookup_and_check_tag (enum tag_types, tree, TAG_how, bool);
83 static void maybe_deduce_size_from_array_init (tree, tree);
84 static void layout_var_decl (tree);
85 static tree check_initializer (tree, tree, int, vec<tree, va_gc> **);
86 static void make_rtl_for_nonlocal_decl (tree, tree, const char *);
87 static void copy_type_enum (tree , tree);
88 static void check_function_type (tree, tree);
89 static void begin_destructor_body (void);
90 static void record_key_method_defined (tree);
91 static tree create_array_type_for_decl (tree, tree, tree, location_t);
92 static tree get_atexit_node (void);
93 static tree get_dso_handle_node (void);
94 static tree start_cleanup_fn (void);
95 static void end_cleanup_fn (void);
96 static tree cp_make_fname_decl (location_t, tree, int);
97 static void initialize_predefined_identifiers (void);
98 static tree check_special_function_return_type
99 (special_function_kind, tree, tree, int, const location_t*);
100 static tree push_cp_library_fn (enum tree_code, tree, int);
101 static tree build_cp_library_fn (tree, enum tree_code, tree, int);
102 static void store_parm_decls (tree);
103 static void initialize_local_var (tree, tree);
104 static void expand_static_init (tree, tree);
105 static location_t smallest_type_location (const cp_decl_specifier_seq*);
107 /* The following symbols are subsumed in the cp_global_trees array, and
108 listed here individually for documentation purposes.
110 C++ extensions
111 tree wchar_decl_node;
113 tree vtable_entry_type;
114 tree delta_type_node;
115 tree __t_desc_type_node;
117 tree class_type_node;
118 tree unknown_type_node;
120 Array type `vtable_entry_type[]'
122 tree vtbl_type_node;
123 tree vtbl_ptr_type_node;
125 Namespaces,
127 tree std_node;
128 tree abi_node;
130 A FUNCTION_DECL which can call `abort'. Not necessarily the
131 one that the user will declare, but sufficient to be called
132 by routines that want to abort the program.
134 tree abort_fndecl;
136 Used by RTTI
137 tree type_info_type_node, tinfo_decl_id, tinfo_decl_type;
138 tree tinfo_var_id; */
140 tree cp_global_trees[CPTI_MAX];
142 /* A list of objects which have constructors or destructors
143 which reside in namespace scope. The decl is stored in
144 the TREE_VALUE slot and the initializer is stored
145 in the TREE_PURPOSE slot. */
146 tree static_aggregates;
148 /* Like static_aggregates, but for thread_local variables. */
149 tree tls_aggregates;
151 /* A hash-map mapping from variable decls to the dynamic initializer for
152 the decl. This is currently only used by OpenMP. */
153 decl_tree_map *dynamic_initializers;
155 /* -- end of C++ */
157 /* A node for the integer constant 2. */
159 tree integer_two_node;
161 /* vector of static decls. */
162 vec<tree, va_gc> *static_decls;
164 /* vector of keyed classes. */
165 vec<tree, va_gc> *keyed_classes;
167 /* Used only for jumps to as-yet undefined labels, since jumps to
168 defined labels can have their validity checked immediately. */
170 struct GTY((chain_next ("%h.next"))) named_label_use_entry {
171 struct named_label_use_entry *next;
172 /* The binding level to which this entry is *currently* attached.
173 This is initially the binding level in which the goto appeared,
174 but is modified as scopes are closed. */
175 cp_binding_level *binding_level;
176 /* The head of the names list that was current when the goto appeared,
177 or the inner scope popped. These are the decls that will *not* be
178 skipped when jumping to the label. */
179 tree names_in_scope;
180 /* The location of the goto, for error reporting. */
181 location_t o_goto_locus;
182 /* True if an OpenMP structured block scope has been closed since
183 the goto appeared. This means that the branch from the label will
184 illegally exit an OpenMP scope. */
185 bool in_omp_scope;
188 /* A list of all LABEL_DECLs in the function that have names. Here so
189 we can clear out their names' definitions at the end of the
190 function, and so we can check the validity of jumps to these labels. */
192 struct GTY((for_user)) named_label_entry {
194 tree name; /* Name of decl. */
196 tree label_decl; /* LABEL_DECL, unless deleted local label. */
198 named_label_entry *outer; /* Outer shadowed chain. */
200 /* The binding level to which the label is *currently* attached.
201 This is initially set to the binding level in which the label
202 is defined, but is modified as scopes are closed. */
203 cp_binding_level *binding_level;
205 /* The head of the names list that was current when the label was
206 defined, or the inner scope popped. These are the decls that will
207 be skipped when jumping to the label. */
208 tree names_in_scope;
210 /* A vector of all decls from all binding levels that would be
211 crossed by a backward branch to the label. */
212 vec<tree, va_gc> *bad_decls;
214 /* A list of uses of the label, before the label is defined. */
215 named_label_use_entry *uses;
217 /* The following bits are set after the label is defined, and are
218 updated as scopes are popped. They indicate that a jump to the
219 label will illegally enter a scope of the given flavor. */
220 bool in_try_scope;
221 bool in_catch_scope;
222 bool in_omp_scope;
223 bool in_transaction_scope;
224 bool in_constexpr_if;
225 bool in_consteval_if;
228 #define named_labels cp_function_chain->x_named_labels
230 /* The number of function bodies which we are currently processing.
231 (Zero if we are at namespace scope, one inside the body of a
232 function, two inside the body of a function in a local class, etc.) */
233 int function_depth;
235 /* Whether the exception-specifier is part of a function type (i.e. C++17). */
236 bool flag_noexcept_type;
238 /* States indicating how grokdeclarator() should handle declspecs marked
239 with __attribute__((deprecated)). An object declared as
240 __attribute__((deprecated)) suppresses warnings of uses of other
241 deprecated items. */
242 enum deprecated_states deprecated_state = DEPRECATED_NORMAL;
245 /* A list of VAR_DECLs whose type was incomplete at the time the
246 variable was declared. */
248 struct GTY(()) incomplete_var {
249 tree decl;
250 tree incomplete_type;
254 static GTY(()) vec<incomplete_var, va_gc> *incomplete_vars;
256 /* Returns the kind of template specialization we are currently
257 processing, given that it's declaration contained N_CLASS_SCOPES
258 explicit scope qualifications. */
260 tmpl_spec_kind
261 current_tmpl_spec_kind (int n_class_scopes)
263 int n_template_parm_scopes = 0;
264 int seen_specialization_p = 0;
265 int innermost_specialization_p = 0;
266 cp_binding_level *b;
268 /* Scan through the template parameter scopes. */
269 for (b = current_binding_level;
270 b->kind == sk_template_parms;
271 b = b->level_chain)
273 /* If we see a specialization scope inside a parameter scope,
274 then something is wrong. That corresponds to a declaration
275 like:
277 template <class T> template <> ...
279 which is always invalid since [temp.expl.spec] forbids the
280 specialization of a class member template if the enclosing
281 class templates are not explicitly specialized as well. */
282 if (b->explicit_spec_p)
284 if (n_template_parm_scopes == 0)
285 innermost_specialization_p = 1;
286 else
287 seen_specialization_p = 1;
289 else if (seen_specialization_p == 1)
290 return tsk_invalid_member_spec;
292 ++n_template_parm_scopes;
295 /* Handle explicit instantiations. */
296 if (processing_explicit_instantiation)
298 if (n_template_parm_scopes != 0)
299 /* We've seen a template parameter list during an explicit
300 instantiation. For example:
302 template <class T> template void f(int);
304 This is erroneous. */
305 return tsk_invalid_expl_inst;
306 else
307 return tsk_expl_inst;
310 if (n_template_parm_scopes < n_class_scopes)
311 /* We've not seen enough template headers to match all the
312 specialized classes present. For example:
314 template <class T> void R<T>::S<T>::f(int);
316 This is invalid; there needs to be one set of template
317 parameters for each class. */
318 return tsk_insufficient_parms;
319 else if (n_template_parm_scopes == n_class_scopes)
320 /* We're processing a non-template declaration (even though it may
321 be a member of a template class.) For example:
323 template <class T> void S<T>::f(int);
325 The `class T' matches the `S<T>', leaving no template headers
326 corresponding to the `f'. */
327 return tsk_none;
328 else if (n_template_parm_scopes > n_class_scopes + 1)
329 /* We've got too many template headers. For example:
331 template <> template <class T> void f (T);
333 There need to be more enclosing classes. */
334 return tsk_excessive_parms;
335 else
336 /* This must be a template. It's of the form:
338 template <class T> template <class U> void S<T>::f(U);
340 This is a specialization if the innermost level was a
341 specialization; otherwise it's just a definition of the
342 template. */
343 return innermost_specialization_p ? tsk_expl_spec : tsk_template;
346 /* Exit the current scope. */
348 void
349 finish_scope (void)
351 poplevel (0, 0, 0);
354 /* When a label goes out of scope, check to see if that label was used
355 in a valid manner, and issue any appropriate warnings or errors. */
357 static void
358 check_label_used (tree label)
360 if (!processing_template_decl)
362 if (DECL_INITIAL (label) == NULL_TREE)
364 location_t location;
366 error ("label %q+D used but not defined", label);
367 location = input_location;
368 /* FIXME want (LOCATION_FILE (input_location), (line)0) */
369 /* Avoid crashing later. */
370 define_label (location, DECL_NAME (label));
372 else
373 warn_for_unused_label (label);
377 /* Helper function to sort named label entries in a vector by DECL_UID. */
379 static int
380 sort_labels (const void *a, const void *b)
382 tree label1 = *(tree const *) a;
383 tree label2 = *(tree const *) b;
385 /* DECL_UIDs can never be equal. */
386 return DECL_UID (label1) > DECL_UID (label2) ? -1 : +1;
389 /* At the end of a function, all labels declared within the function
390 go out of scope. BLOCK is the top-level block for the
391 function. */
393 static void
394 pop_labels (tree block)
396 if (!named_labels)
397 return;
399 /* We need to add the labels to the block chain, so debug
400 information is emitted. But, we want the order to be stable so
401 need to sort them first. Otherwise the debug output could be
402 randomly ordered. I guess it's mostly stable, unless the hash
403 table implementation changes. */
404 auto_vec<tree, 32> labels (named_labels->elements ());
405 hash_table<named_label_hash>::iterator end (named_labels->end ());
406 for (hash_table<named_label_hash>::iterator iter
407 (named_labels->begin ()); iter != end; ++iter)
409 named_label_entry *ent = *iter;
411 gcc_checking_assert (!ent->outer);
412 if (ent->label_decl)
413 labels.quick_push (ent->label_decl);
414 ggc_free (ent);
416 named_labels = NULL;
417 labels.qsort (sort_labels);
419 while (labels.length ())
421 tree label = labels.pop ();
423 DECL_CHAIN (label) = BLOCK_VARS (block);
424 BLOCK_VARS (block) = label;
426 check_label_used (label);
430 /* At the end of a block with local labels, restore the outer definition. */
432 static void
433 pop_local_label (tree id, tree label)
435 check_label_used (label);
436 named_label_entry **slot = named_labels->find_slot_with_hash
437 (id, IDENTIFIER_HASH_VALUE (id), NO_INSERT);
438 named_label_entry *ent = *slot;
440 if (ent->outer)
441 ent = ent->outer;
442 else
444 ent = ggc_cleared_alloc<named_label_entry> ();
445 ent->name = id;
447 *slot = ent;
450 /* The following two routines are used to interface to Objective-C++.
451 The binding level is purposely treated as an opaque type. */
453 void *
454 objc_get_current_scope (void)
456 return current_binding_level;
459 /* The following routine is used by the NeXT-style SJLJ exceptions;
460 variables get marked 'volatile' so as to not be clobbered by
461 _setjmp()/_longjmp() calls. All variables in the current scope,
462 as well as parent scopes up to (but not including) ENCLOSING_BLK
463 shall be thusly marked. */
465 void
466 objc_mark_locals_volatile (void *enclosing_blk)
468 cp_binding_level *scope;
470 for (scope = current_binding_level;
471 scope && scope != enclosing_blk;
472 scope = scope->level_chain)
474 tree decl;
476 for (decl = scope->names; decl; decl = TREE_CHAIN (decl))
477 objc_volatilize_decl (decl);
479 /* Do not climb up past the current function. */
480 if (scope->kind == sk_function_parms)
481 break;
485 /* True if B is the level for the condition of a constexpr if. */
487 static bool
488 level_for_constexpr_if (cp_binding_level *b)
490 return (b->kind == sk_cond && b->this_entity
491 && TREE_CODE (b->this_entity) == IF_STMT
492 && IF_STMT_CONSTEXPR_P (b->this_entity));
495 /* True if B is the level for the condition of a consteval if. */
497 static bool
498 level_for_consteval_if (cp_binding_level *b)
500 return (b->kind == sk_cond && b->this_entity
501 && TREE_CODE (b->this_entity) == IF_STMT
502 && IF_STMT_CONSTEVAL_P (b->this_entity));
505 /* Update data for defined and undefined labels when leaving a scope. */
508 poplevel_named_label_1 (named_label_entry **slot, cp_binding_level *bl)
510 named_label_entry *ent = *slot;
511 cp_binding_level *obl = bl->level_chain;
513 if (ent->binding_level == bl)
515 tree decl;
517 /* ENT->NAMES_IN_SCOPE may contain a mixture of DECLs and
518 TREE_LISTs representing OVERLOADs, so be careful. */
519 for (decl = ent->names_in_scope; decl; decl = (DECL_P (decl)
520 ? DECL_CHAIN (decl)
521 : TREE_CHAIN (decl)))
522 if (decl_jump_unsafe (decl))
523 vec_safe_push (ent->bad_decls, decl);
525 ent->binding_level = obl;
526 ent->names_in_scope = obl->names;
527 switch (bl->kind)
529 case sk_try:
530 ent->in_try_scope = true;
531 break;
532 case sk_catch:
533 ent->in_catch_scope = true;
534 break;
535 case sk_omp:
536 ent->in_omp_scope = true;
537 break;
538 case sk_transaction:
539 ent->in_transaction_scope = true;
540 break;
541 case sk_block:
542 if (level_for_constexpr_if (bl->level_chain))
543 ent->in_constexpr_if = true;
544 else if (level_for_consteval_if (bl->level_chain))
545 ent->in_consteval_if = true;
546 break;
547 default:
548 break;
551 else if (ent->uses)
553 struct named_label_use_entry *use;
555 for (use = ent->uses; use ; use = use->next)
556 if (use->binding_level == bl)
558 use->binding_level = obl;
559 use->names_in_scope = obl->names;
560 if (bl->kind == sk_omp)
561 use->in_omp_scope = true;
565 return 1;
568 /* Saved errorcount to avoid -Wunused-but-set-{parameter,variable} warnings
569 when errors were reported, except for -Werror-unused-but-set-*. */
570 static int unused_but_set_errorcount;
572 /* Exit a binding level.
573 Pop the level off, and restore the state of the identifier-decl mappings
574 that were in effect when this level was entered.
576 If KEEP == 1, this level had explicit declarations, so
577 and create a "block" (a BLOCK node) for the level
578 to record its declarations and subblocks for symbol table output.
580 If FUNCTIONBODY is nonzero, this level is the body of a function,
581 so create a block as if KEEP were set and also clear out all
582 label names.
584 If REVERSE is nonzero, reverse the order of decls before putting
585 them into the BLOCK. */
587 tree
588 poplevel (int keep, int reverse, int functionbody)
590 tree link;
591 /* The chain of decls was accumulated in reverse order.
592 Put it into forward order, just for cleanliness. */
593 tree decls;
594 tree subblocks;
595 tree block;
596 tree decl;
597 scope_kind kind;
599 auto_cond_timevar tv (TV_NAME_LOOKUP);
600 restart:
602 block = NULL_TREE;
604 gcc_assert (current_binding_level->kind != sk_class
605 && current_binding_level->kind != sk_namespace);
607 if (current_binding_level->kind == sk_cleanup)
608 functionbody = 0;
609 subblocks = functionbody >= 0 ? current_binding_level->blocks : 0;
611 gcc_assert (!vec_safe_length (current_binding_level->class_shadowed));
613 /* We used to use KEEP == 2 to indicate that the new block should go
614 at the beginning of the list of blocks at this binding level,
615 rather than the end. This hack is no longer used. */
616 gcc_assert (keep == 0 || keep == 1);
618 if (current_binding_level->keep)
619 keep = 1;
621 /* Any uses of undefined labels, and any defined labels, now operate
622 under constraints of next binding contour. */
623 if (cfun && !functionbody && named_labels)
624 named_labels->traverse<cp_binding_level *, poplevel_named_label_1>
625 (current_binding_level);
627 /* Get the decls in the order they were written.
628 Usually current_binding_level->names is in reverse order.
629 But parameter decls were previously put in forward order. */
631 decls = current_binding_level->names;
632 if (reverse)
634 decls = nreverse (decls);
635 current_binding_level->names = decls;
638 /* If there were any declarations or structure tags in that level,
639 or if this level is a function body,
640 create a BLOCK to record them for the life of this function. */
641 block = NULL_TREE;
642 /* Avoid function body block if possible. */
643 if (functionbody && subblocks && BLOCK_CHAIN (subblocks) == NULL_TREE)
644 keep = 0;
645 else if (keep == 1 || functionbody)
646 block = make_node (BLOCK);
647 if (block != NULL_TREE)
649 BLOCK_VARS (block) = decls;
650 BLOCK_SUBBLOCKS (block) = subblocks;
653 /* In each subblock, record that this is its superior. */
654 if (keep >= 0)
655 for (link = subblocks; link; link = BLOCK_CHAIN (link))
656 BLOCK_SUPERCONTEXT (link) = block;
658 /* Before we remove the declarations first check for unused variables. */
659 if ((warn_unused_variable || warn_unused_but_set_variable)
660 && current_binding_level->kind != sk_template_parms
661 && !processing_template_decl)
662 for (tree d = get_local_decls (); d; d = TREE_CHAIN (d))
664 /* There are cases where D itself is a TREE_LIST. See in
665 push_local_binding where the list of decls returned by
666 getdecls is built. */
667 decl = TREE_CODE (d) == TREE_LIST ? TREE_VALUE (d) : d;
669 tree type = TREE_TYPE (decl);
670 if (VAR_P (decl)
671 && (! TREE_USED (decl) || !DECL_READ_P (decl))
672 && ! DECL_IN_SYSTEM_HEADER (decl)
673 /* For structured bindings, consider only real variables, not
674 subobjects. */
675 && (DECL_DECOMPOSITION_P (decl) ? !DECL_DECOMP_BASE (decl)
676 : (DECL_NAME (decl) && !DECL_ARTIFICIAL (decl)))
677 && type != error_mark_node
678 && (!CLASS_TYPE_P (type)
679 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
680 || lookup_attribute ("warn_unused",
681 TYPE_ATTRIBUTES (TREE_TYPE (decl)))))
683 if (! TREE_USED (decl))
685 if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
686 warning_at (DECL_SOURCE_LOCATION (decl),
687 OPT_Wunused_variable,
688 "unused structured binding declaration");
689 else
690 warning_at (DECL_SOURCE_LOCATION (decl),
691 OPT_Wunused_variable, "unused variable %qD", decl);
693 else if (DECL_CONTEXT (decl) == current_function_decl
694 // For -Wunused-but-set-variable leave references alone.
695 && !TYPE_REF_P (TREE_TYPE (decl))
696 && errorcount == unused_but_set_errorcount)
698 if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
699 warning_at (DECL_SOURCE_LOCATION (decl),
700 OPT_Wunused_but_set_variable, "structured "
701 "binding declaration set but not used");
702 else
703 warning_at (DECL_SOURCE_LOCATION (decl),
704 OPT_Wunused_but_set_variable,
705 "variable %qD set but not used", decl);
706 unused_but_set_errorcount = errorcount;
711 /* Remove declarations for all the DECLs in this level. */
712 for (link = decls; link; link = TREE_CHAIN (link))
714 tree name;
715 if (TREE_CODE (link) == TREE_LIST)
717 decl = TREE_VALUE (link);
718 name = TREE_PURPOSE (link);
719 gcc_checking_assert (name);
721 else
723 decl = link;
724 name = DECL_NAME (decl);
727 /* Remove the binding. */
728 if (TREE_CODE (decl) == LABEL_DECL)
729 pop_local_label (name, decl);
730 else
731 pop_local_binding (name, decl);
734 /* Restore the IDENTIFIER_TYPE_VALUEs. */
735 for (link = current_binding_level->type_shadowed;
736 link; link = TREE_CHAIN (link))
737 SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (link), TREE_VALUE (link));
739 /* There may be OVERLOADs (wrapped in TREE_LISTs) on the BLOCK_VARs
740 list if a `using' declaration put them there. The debugging
741 back ends won't understand OVERLOAD, so we remove them here.
742 Because the BLOCK_VARS are (temporarily) shared with
743 CURRENT_BINDING_LEVEL->NAMES we must do this fixup after we have
744 popped all the bindings. Also remove undeduced 'auto' decls,
745 which LTO doesn't understand, and can't have been used by anything. */
746 if (block)
748 tree* d;
750 for (d = &BLOCK_VARS (block); *d; )
752 if (TREE_CODE (*d) == TREE_LIST
753 || (!processing_template_decl
754 && undeduced_auto_decl (*d)))
755 *d = TREE_CHAIN (*d);
756 else
757 d = &DECL_CHAIN (*d);
761 /* If the level being exited is the top level of a function,
762 check over all the labels. */
763 if (functionbody)
765 if (block)
767 /* Since this is the top level block of a function, the vars are
768 the function's parameters. Don't leave them in the BLOCK
769 because they are found in the FUNCTION_DECL instead. */
770 BLOCK_VARS (block) = 0;
771 pop_labels (block);
773 else
774 pop_labels (subblocks);
777 kind = current_binding_level->kind;
778 if (kind == sk_cleanup)
780 tree stmt;
782 /* If this is a temporary binding created for a cleanup, then we'll
783 have pushed a statement list level. Pop that, create a new
784 BIND_EXPR for the block, and insert it into the stream. */
785 stmt = pop_stmt_list (current_binding_level->statement_list);
786 stmt = c_build_bind_expr (input_location, block, stmt);
787 add_stmt (stmt);
790 leave_scope ();
791 if (functionbody)
793 /* The current function is being defined, so its DECL_INITIAL
794 should be error_mark_node. */
795 gcc_assert (DECL_INITIAL (current_function_decl) == error_mark_node);
796 DECL_INITIAL (current_function_decl) = block ? block : subblocks;
797 if (subblocks)
799 if (FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
801 if (BLOCK_SUBBLOCKS (subblocks))
802 BLOCK_OUTER_CURLY_BRACE_P (BLOCK_SUBBLOCKS (subblocks)) = 1;
804 else
805 BLOCK_OUTER_CURLY_BRACE_P (subblocks) = 1;
808 else if (block)
809 current_binding_level->blocks
810 = block_chainon (current_binding_level->blocks, block);
812 /* If we did not make a block for the level just exited,
813 any blocks made for inner levels
814 (since they cannot be recorded as subblocks in that level)
815 must be carried forward so they will later become subblocks
816 of something else. */
817 else if (subblocks)
818 current_binding_level->blocks
819 = block_chainon (current_binding_level->blocks, subblocks);
821 /* Each and every BLOCK node created here in `poplevel' is important
822 (e.g. for proper debugging information) so if we created one
823 earlier, mark it as "used". */
824 if (block)
825 TREE_USED (block) = 1;
827 /* All temporary bindings created for cleanups are popped silently. */
828 if (kind == sk_cleanup)
829 goto restart;
831 return block;
834 /* Call wrapup_globals_declarations for the globals in NAMESPACE. */
835 /* Diagnose odr-used extern inline variables without definitions
836 in the current TU. */
839 wrapup_namespace_globals ()
841 if (vec<tree, va_gc> *statics = static_decls)
843 for (tree decl : *statics)
845 if (warn_unused_function
846 && TREE_CODE (decl) == FUNCTION_DECL
847 && DECL_INITIAL (decl) == 0
848 && DECL_EXTERNAL (decl)
849 && !TREE_PUBLIC (decl)
850 && !DECL_ARTIFICIAL (decl)
851 && !DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
852 && !warning_suppressed_p (decl, OPT_Wunused_function))
853 warning_at (DECL_SOURCE_LOCATION (decl),
854 OPT_Wunused_function,
855 "%qF declared %<static%> but never defined", decl);
857 if (VAR_P (decl)
858 && DECL_EXTERNAL (decl)
859 && DECL_INLINE_VAR_P (decl)
860 && DECL_ODR_USED (decl))
861 error_at (DECL_SOURCE_LOCATION (decl),
862 "odr-used inline variable %qD is not defined", decl);
865 /* Clear out the list, so we don't rescan next time. */
866 static_decls = NULL;
868 /* Write out any globals that need to be output. */
869 return wrapup_global_declarations (statics->address (),
870 statics->length ());
872 return 0;
875 /* In C++, you don't have to write `struct S' to refer to `S'; you
876 can just use `S'. We accomplish this by creating a TYPE_DECL as
877 if the user had written `typedef struct S S'. Create and return
878 the TYPE_DECL for TYPE. */
880 tree
881 create_implicit_typedef (tree name, tree type)
883 tree decl;
885 decl = build_decl (input_location, TYPE_DECL, name, type);
886 DECL_ARTIFICIAL (decl) = 1;
887 /* There are other implicit type declarations, like the one *within*
888 a class that allows you to write `S::S'. We must distinguish
889 amongst these. */
890 SET_DECL_IMPLICIT_TYPEDEF_P (decl);
891 TYPE_NAME (type) = decl;
892 TYPE_STUB_DECL (type) = decl;
894 return decl;
897 /* Function-scope local entities that need discriminators. Each entry
898 is a {decl,name} pair. VAR_DECLs for anon unions get their name
899 smashed, so we cannot rely on DECL_NAME. */
901 static GTY((deletable)) vec<tree, va_gc> *local_entities;
903 /* Determine the mangling discriminator of local DECL. There are
904 generally very few of these in any particular function. */
906 void
907 determine_local_discriminator (tree decl)
909 auto_cond_timevar tv (TV_NAME_LOOKUP);
910 retrofit_lang_decl (decl);
911 tree ctx = DECL_CONTEXT (decl);
912 tree name = (TREE_CODE (decl) == TYPE_DECL
913 && TYPE_UNNAMED_P (TREE_TYPE (decl))
914 ? NULL_TREE : DECL_NAME (decl));
915 size_t nelts = vec_safe_length (local_entities);
916 for (size_t i = 0; i < nelts; i += 2)
918 tree *pair = &(*local_entities)[i];
919 tree d = pair[0];
920 tree n = pair[1];
921 gcc_checking_assert (d != decl);
922 if (name == n
923 && TREE_CODE (decl) == TREE_CODE (d)
924 && ctx == DECL_CONTEXT (d))
926 tree disc = integer_one_node;
927 if (DECL_DISCRIMINATOR (d))
928 disc = build_int_cst (TREE_TYPE (disc),
929 TREE_INT_CST_LOW (DECL_DISCRIMINATOR (d)) + 1);
930 DECL_DISCRIMINATOR (decl) = disc;
931 /* Replace the saved decl. */
932 pair[0] = decl;
933 decl = NULL_TREE;
934 break;
938 if (decl)
940 vec_safe_reserve (local_entities, 2);
941 local_entities->quick_push (decl);
942 local_entities->quick_push (name);
948 /* Returns true if functions FN1 and FN2 have equivalent trailing
949 requires clauses. */
951 static bool
952 function_requirements_equivalent_p (tree newfn, tree oldfn)
954 /* In the concepts TS, the combined constraints are compared. */
955 if (cxx_dialect < cxx20
956 && (DECL_TEMPLATE_SPECIALIZATION (newfn)
957 <= DECL_TEMPLATE_SPECIALIZATION (oldfn)))
959 tree ci1 = get_constraints (oldfn);
960 tree ci2 = get_constraints (newfn);
961 tree req1 = ci1 ? CI_ASSOCIATED_CONSTRAINTS (ci1) : NULL_TREE;
962 tree req2 = ci2 ? CI_ASSOCIATED_CONSTRAINTS (ci2) : NULL_TREE;
963 return cp_tree_equal (req1, req2);
966 /* Compare only trailing requirements. */
967 tree reqs1 = get_trailing_function_requirements (newfn);
968 tree reqs2 = get_trailing_function_requirements (oldfn);
969 if ((reqs1 != NULL_TREE) != (reqs2 != NULL_TREE))
970 return false;
972 /* Substitution is needed when friends are involved. */
973 reqs1 = maybe_substitute_reqs_for (reqs1, newfn);
974 reqs2 = maybe_substitute_reqs_for (reqs2, oldfn);
976 return cp_tree_equal (reqs1, reqs2);
979 /* Subroutine of duplicate_decls: return truthvalue of whether
980 or not types of these decls match.
982 For C++, we must compare the parameter list so that `int' can match
983 `int&' in a parameter position, but `int&' is not confused with
984 `const int&'. */
987 decls_match (tree newdecl, tree olddecl, bool record_versions /* = true */)
989 int types_match;
991 if (newdecl == olddecl)
992 return 1;
994 if (TREE_CODE (newdecl) != TREE_CODE (olddecl))
995 /* If the two DECLs are not even the same kind of thing, we're not
996 interested in their types. */
997 return 0;
999 gcc_assert (DECL_P (newdecl));
1001 if (TREE_CODE (newdecl) == FUNCTION_DECL)
1003 /* Specializations of different templates are different functions
1004 even if they have the same type. */
1005 tree t1 = (DECL_USE_TEMPLATE (newdecl)
1006 ? DECL_TI_TEMPLATE (newdecl)
1007 : NULL_TREE);
1008 tree t2 = (DECL_USE_TEMPLATE (olddecl)
1009 ? DECL_TI_TEMPLATE (olddecl)
1010 : NULL_TREE);
1011 if (t1 != t2)
1012 return 0;
1014 if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1015 && ! (DECL_EXTERN_C_P (newdecl)
1016 && DECL_EXTERN_C_P (olddecl)))
1017 return 0;
1019 /* A new declaration doesn't match a built-in one unless it
1020 is also extern "C". */
1021 if (DECL_IS_UNDECLARED_BUILTIN (olddecl)
1022 && DECL_EXTERN_C_P (olddecl) && !DECL_EXTERN_C_P (newdecl))
1023 return 0;
1025 tree f1 = TREE_TYPE (newdecl);
1026 tree f2 = TREE_TYPE (olddecl);
1027 if (TREE_CODE (f1) != TREE_CODE (f2))
1028 return 0;
1030 /* A declaration with deduced return type should use its pre-deduction
1031 type for declaration matching. */
1032 tree r2 = fndecl_declared_return_type (olddecl);
1033 tree r1 = fndecl_declared_return_type (newdecl);
1035 tree p1 = TYPE_ARG_TYPES (f1);
1036 tree p2 = TYPE_ARG_TYPES (f2);
1038 if (same_type_p (r1, r2))
1040 if (!prototype_p (f2) && DECL_EXTERN_C_P (olddecl)
1041 && fndecl_built_in_p (olddecl))
1043 types_match = self_promoting_args_p (p1);
1044 if (p1 == void_list_node)
1045 TREE_TYPE (newdecl) = TREE_TYPE (olddecl);
1047 else
1048 types_match =
1049 compparms (p1, p2)
1050 && type_memfn_rqual (f1) == type_memfn_rqual (f2)
1051 && (TYPE_ATTRIBUTES (TREE_TYPE (newdecl)) == NULL_TREE
1052 || comp_type_attributes (TREE_TYPE (newdecl),
1053 TREE_TYPE (olddecl)) != 0);
1055 else
1056 types_match = 0;
1058 /* Two function declarations match if either has a requires-clause
1059 then both have a requires-clause and their constraints-expressions
1060 are equivalent. */
1061 if (types_match && flag_concepts)
1062 types_match = function_requirements_equivalent_p (newdecl, olddecl);
1064 /* The decls dont match if they correspond to two different versions
1065 of the same function. Disallow extern "C" functions to be
1066 versions for now. */
1067 if (types_match
1068 && !DECL_EXTERN_C_P (newdecl)
1069 && !DECL_EXTERN_C_P (olddecl)
1070 && targetm.target_option.function_versions (newdecl, olddecl))
1072 if (record_versions)
1073 maybe_version_functions (newdecl, olddecl,
1074 (!DECL_FUNCTION_VERSIONED (newdecl)
1075 || !DECL_FUNCTION_VERSIONED (olddecl)));
1076 return 0;
1079 else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1081 if (!template_heads_equivalent_p (newdecl, olddecl))
1082 return 0;
1084 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1085 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1087 if (TREE_CODE (newres) != TREE_CODE (oldres))
1088 return 0;
1090 /* Two template types match if they are the same. Otherwise, compare
1091 the underlying declarations. */
1092 if (TREE_CODE (newres) == TYPE_DECL)
1093 types_match = same_type_p (TREE_TYPE (newres), TREE_TYPE (oldres));
1094 else
1095 types_match = decls_match (newres, oldres);
1097 else
1099 /* Need to check scope for variable declaration (VAR_DECL).
1100 For typedef (TYPE_DECL), scope is ignored. */
1101 if (VAR_P (newdecl)
1102 && CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1103 /* [dcl.link]
1104 Two declarations for an object with C language linkage
1105 with the same name (ignoring the namespace that qualify
1106 it) that appear in different namespace scopes refer to
1107 the same object. */
1108 && !(DECL_EXTERN_C_P (olddecl) && DECL_EXTERN_C_P (newdecl)))
1109 return 0;
1111 if (TREE_TYPE (newdecl) == error_mark_node)
1112 types_match = TREE_TYPE (olddecl) == error_mark_node;
1113 else if (TREE_TYPE (olddecl) == NULL_TREE)
1114 types_match = TREE_TYPE (newdecl) == NULL_TREE;
1115 else if (TREE_TYPE (newdecl) == NULL_TREE)
1116 types_match = 0;
1117 else
1118 types_match = comptypes (TREE_TYPE (newdecl),
1119 TREE_TYPE (olddecl),
1120 COMPARE_REDECLARATION);
1123 return types_match;
1126 /* Mark DECL as versioned if it isn't already. */
1128 static void
1129 maybe_mark_function_versioned (tree decl)
1131 if (!DECL_FUNCTION_VERSIONED (decl))
1133 DECL_FUNCTION_VERSIONED (decl) = 1;
1134 /* If DECL_ASSEMBLER_NAME has already been set, re-mangle
1135 to include the version marker. */
1136 if (DECL_ASSEMBLER_NAME_SET_P (decl))
1137 mangle_decl (decl);
1141 /* NEWDECL and OLDDECL have identical signatures. If they are
1142 different versions adjust them and return true.
1143 If RECORD is set to true, record function versions. */
1145 bool
1146 maybe_version_functions (tree newdecl, tree olddecl, bool record)
1148 if (!targetm.target_option.function_versions (newdecl, olddecl))
1149 return false;
1151 maybe_mark_function_versioned (olddecl);
1152 if (DECL_LOCAL_DECL_P (olddecl))
1154 olddecl = DECL_LOCAL_DECL_ALIAS (olddecl);
1155 maybe_mark_function_versioned (olddecl);
1158 maybe_mark_function_versioned (newdecl);
1159 if (DECL_LOCAL_DECL_P (newdecl))
1161 /* Unfortunately, we can get here before pushdecl naturally calls
1162 push_local_extern_decl_alias, so we need to call it directly. */
1163 if (!DECL_LOCAL_DECL_ALIAS (newdecl))
1164 push_local_extern_decl_alias (newdecl);
1165 newdecl = DECL_LOCAL_DECL_ALIAS (newdecl);
1166 maybe_mark_function_versioned (newdecl);
1169 if (record)
1170 cgraph_node::record_function_versions (olddecl, newdecl);
1172 return true;
1175 /* If NEWDECL is `static' and an `extern' was seen previously,
1176 warn about it. OLDDECL is the previous declaration.
1178 Note that this does not apply to the C++ case of declaring
1179 a variable `extern const' and then later `const'.
1181 Don't complain about built-in functions, since they are beyond
1182 the user's control. */
1184 void
1185 warn_extern_redeclared_static (tree newdecl, tree olddecl)
1187 if (TREE_CODE (newdecl) == TYPE_DECL
1188 || TREE_CODE (newdecl) == TEMPLATE_DECL
1189 || TREE_CODE (newdecl) == CONST_DECL
1190 || TREE_CODE (newdecl) == NAMESPACE_DECL)
1191 return;
1193 /* Don't get confused by static member functions; that's a different
1194 use of `static'. */
1195 if (TREE_CODE (newdecl) == FUNCTION_DECL
1196 && DECL_STATIC_FUNCTION_P (newdecl))
1197 return;
1199 /* If the old declaration was `static', or the new one isn't, then
1200 everything is OK. */
1201 if (DECL_THIS_STATIC (olddecl) || !DECL_THIS_STATIC (newdecl))
1202 return;
1204 /* It's OK to declare a builtin function as `static'. */
1205 if (TREE_CODE (olddecl) == FUNCTION_DECL
1206 && DECL_ARTIFICIAL (olddecl))
1207 return;
1209 auto_diagnostic_group d;
1210 if (permerror (DECL_SOURCE_LOCATION (newdecl),
1211 "%qD was declared %<extern%> and later %<static%>", newdecl))
1212 inform (DECL_SOURCE_LOCATION (olddecl),
1213 "previous declaration of %qD", olddecl);
1216 /* NEW_DECL is a redeclaration of OLD_DECL; both are functions or
1217 function templates. If their exception specifications do not
1218 match, issue a diagnostic. */
1220 static void
1221 check_redeclaration_exception_specification (tree new_decl,
1222 tree old_decl)
1224 tree new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1225 tree old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1227 /* Two default specs are equivalent, don't force evaluation. */
1228 if (UNEVALUATED_NOEXCEPT_SPEC_P (new_exceptions)
1229 && UNEVALUATED_NOEXCEPT_SPEC_P (old_exceptions))
1230 return;
1232 if (!type_dependent_expression_p (old_decl))
1234 maybe_instantiate_noexcept (new_decl);
1235 maybe_instantiate_noexcept (old_decl);
1237 new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1238 old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1240 /* [except.spec]
1242 If any declaration of a function has an exception-specification,
1243 all declarations, including the definition and an explicit
1244 specialization, of that function shall have an
1245 exception-specification with the same set of type-ids. */
1246 if (!DECL_IS_UNDECLARED_BUILTIN (old_decl)
1247 && !DECL_IS_UNDECLARED_BUILTIN (new_decl)
1248 && !comp_except_specs (new_exceptions, old_exceptions, ce_normal))
1250 const char *const msg
1251 = G_("declaration of %qF has a different exception specifier");
1252 bool complained = true;
1253 location_t new_loc = DECL_SOURCE_LOCATION (new_decl);
1254 auto_diagnostic_group d;
1255 if (DECL_IN_SYSTEM_HEADER (old_decl))
1256 complained = pedwarn (new_loc, OPT_Wsystem_headers, msg, new_decl);
1257 else if (!flag_exceptions)
1258 /* We used to silently permit mismatched eh specs with
1259 -fno-exceptions, so make them a pedwarn now. */
1260 complained = pedwarn (new_loc, OPT_Wpedantic, msg, new_decl);
1261 else
1262 error_at (new_loc, msg, new_decl);
1263 if (complained)
1264 inform (DECL_SOURCE_LOCATION (old_decl),
1265 "from previous declaration %qF", old_decl);
1269 /* Return true if OLD_DECL and NEW_DECL agree on constexprness.
1270 Otherwise issue diagnostics. */
1272 static bool
1273 validate_constexpr_redeclaration (tree old_decl, tree new_decl)
1275 old_decl = STRIP_TEMPLATE (old_decl);
1276 new_decl = STRIP_TEMPLATE (new_decl);
1277 if (!VAR_OR_FUNCTION_DECL_P (old_decl)
1278 || !VAR_OR_FUNCTION_DECL_P (new_decl))
1279 return true;
1280 if (DECL_DECLARED_CONSTEXPR_P (old_decl)
1281 == DECL_DECLARED_CONSTEXPR_P (new_decl))
1283 if (TREE_CODE (old_decl) != FUNCTION_DECL)
1284 return true;
1285 if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1286 == DECL_IMMEDIATE_FUNCTION_P (new_decl))
1287 return true;
1289 if (TREE_CODE (old_decl) == FUNCTION_DECL)
1291 /* With -fimplicit-constexpr, ignore changes in the constexpr
1292 keyword. */
1293 if (flag_implicit_constexpr
1294 && (DECL_IMMEDIATE_FUNCTION_P (new_decl)
1295 == DECL_IMMEDIATE_FUNCTION_P (old_decl)))
1296 return true;
1297 if (fndecl_built_in_p (old_decl))
1299 /* Hide a built-in declaration. */
1300 DECL_DECLARED_CONSTEXPR_P (old_decl)
1301 = DECL_DECLARED_CONSTEXPR_P (new_decl);
1302 if (DECL_IMMEDIATE_FUNCTION_P (new_decl))
1303 SET_DECL_IMMEDIATE_FUNCTION_P (old_decl);
1304 return true;
1306 /* 7.1.5 [dcl.constexpr]
1307 Note: An explicit specialization can differ from the template
1308 declaration with respect to the constexpr specifier. */
1309 if (! DECL_TEMPLATE_SPECIALIZATION (old_decl)
1310 && DECL_TEMPLATE_SPECIALIZATION (new_decl))
1311 return true;
1313 const char *kind = "constexpr";
1314 if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1315 || DECL_IMMEDIATE_FUNCTION_P (new_decl))
1316 kind = "consteval";
1317 error_at (DECL_SOURCE_LOCATION (new_decl),
1318 "redeclaration %qD differs in %qs "
1319 "from previous declaration", new_decl,
1320 kind);
1321 inform (DECL_SOURCE_LOCATION (old_decl),
1322 "previous declaration %qD", old_decl);
1323 return false;
1325 return true;
1328 // If OLDDECL and NEWDECL are concept declarations with the same type
1329 // (i.e., and template parameters), but different requirements,
1330 // emit diagnostics and return true. Otherwise, return false.
1331 static inline bool
1332 check_concept_refinement (tree olddecl, tree newdecl)
1334 if (!DECL_DECLARED_CONCEPT_P (olddecl) || !DECL_DECLARED_CONCEPT_P (newdecl))
1335 return false;
1337 tree d1 = DECL_TEMPLATE_RESULT (olddecl);
1338 tree d2 = DECL_TEMPLATE_RESULT (newdecl);
1339 if (TREE_CODE (d1) != TREE_CODE (d2))
1340 return false;
1342 tree t1 = TREE_TYPE (d1);
1343 tree t2 = TREE_TYPE (d2);
1344 if (TREE_CODE (d1) == FUNCTION_DECL)
1346 if (compparms (TYPE_ARG_TYPES (t1), TYPE_ARG_TYPES (t2))
1347 && comp_template_parms (DECL_TEMPLATE_PARMS (olddecl),
1348 DECL_TEMPLATE_PARMS (newdecl))
1349 && !equivalently_constrained (olddecl, newdecl))
1351 error ("cannot specialize concept %q#D", olddecl);
1352 return true;
1355 return false;
1358 /* DECL is a redeclaration of a function or function template. If
1359 it does have default arguments issue a diagnostic. Note: this
1360 function is used to enforce the requirements in C++11 8.3.6 about
1361 no default arguments in redeclarations. */
1363 static void
1364 check_redeclaration_no_default_args (tree decl)
1366 gcc_assert (DECL_DECLARES_FUNCTION_P (decl));
1368 for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
1369 t && t != void_list_node; t = TREE_CHAIN (t))
1370 if (TREE_PURPOSE (t))
1372 permerror (DECL_SOURCE_LOCATION (decl),
1373 "redeclaration of %q#D may not have default "
1374 "arguments", decl);
1375 return;
1379 /* NEWDECL is a redeclaration of a function or function template OLDDECL,
1380 in any case represented as FUNCTION_DECLs (the DECL_TEMPLATE_RESULTs of
1381 the TEMPLATE_DECLs in case of function templates). This function is used
1382 to enforce the final part of C++17 11.3.6/4, about a single declaration:
1383 "If a friend declaration specifies a default argument expression, that
1384 declaration shall be a definition and shall be the only declaration of
1385 the function or function template in the translation unit." */
1387 static void
1388 check_no_redeclaration_friend_default_args (tree olddecl, tree newdecl)
1390 if (!DECL_UNIQUE_FRIEND_P (olddecl) && !DECL_UNIQUE_FRIEND_P (newdecl))
1391 return;
1393 for (tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl),
1394 t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1395 t1 && t1 != void_list_node;
1396 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1397 if ((DECL_UNIQUE_FRIEND_P (olddecl) && TREE_PURPOSE (t1))
1398 || (DECL_UNIQUE_FRIEND_P (newdecl) && TREE_PURPOSE (t2)))
1400 auto_diagnostic_group d;
1401 if (permerror (DECL_SOURCE_LOCATION (newdecl),
1402 "friend declaration of %q#D specifies default "
1403 "arguments and isn%'t the only declaration", newdecl))
1404 inform (DECL_SOURCE_LOCATION (olddecl),
1405 "previous declaration of %q#D", olddecl);
1406 return;
1410 /* Merge tree bits that correspond to attributes noreturn, nothrow,
1411 const, malloc, and pure from NEWDECL with those of OLDDECL. */
1413 static void
1414 merge_attribute_bits (tree newdecl, tree olddecl)
1416 TREE_THIS_VOLATILE (newdecl) |= TREE_THIS_VOLATILE (olddecl);
1417 TREE_THIS_VOLATILE (olddecl) |= TREE_THIS_VOLATILE (newdecl);
1418 TREE_NOTHROW (newdecl) |= TREE_NOTHROW (olddecl);
1419 TREE_NOTHROW (olddecl) |= TREE_NOTHROW (newdecl);
1420 TREE_READONLY (newdecl) |= TREE_READONLY (olddecl);
1421 TREE_READONLY (olddecl) |= TREE_READONLY (newdecl);
1422 DECL_IS_MALLOC (newdecl) |= DECL_IS_MALLOC (olddecl);
1423 DECL_IS_MALLOC (olddecl) |= DECL_IS_MALLOC (newdecl);
1424 DECL_PURE_P (newdecl) |= DECL_PURE_P (olddecl);
1425 DECL_PURE_P (olddecl) |= DECL_PURE_P (newdecl);
1426 DECL_UNINLINABLE (newdecl) |= DECL_UNINLINABLE (olddecl);
1427 DECL_UNINLINABLE (olddecl) |= DECL_UNINLINABLE (newdecl);
1430 #define GNU_INLINE_P(fn) (DECL_DECLARED_INLINE_P (fn) \
1431 && lookup_attribute ("gnu_inline", \
1432 DECL_ATTRIBUTES (fn)))
1434 /* A subroutine of duplicate_decls. Emits a diagnostic when newdecl
1435 ambiguates olddecl. Returns true if an error occurs. */
1437 static bool
1438 duplicate_function_template_decls (tree newdecl, tree olddecl)
1441 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1442 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1443 /* Function template declarations can be differentiated by parameter
1444 and return type. */
1445 if (compparms (TYPE_ARG_TYPES (TREE_TYPE (oldres)),
1446 TYPE_ARG_TYPES (TREE_TYPE (newres)))
1447 && same_type_p (TREE_TYPE (TREE_TYPE (newdecl)),
1448 TREE_TYPE (TREE_TYPE (olddecl))))
1450 /* ... and also by their template-heads and requires-clauses. */
1451 if (template_heads_equivalent_p (newdecl, olddecl)
1452 && function_requirements_equivalent_p (newres, oldres))
1454 error ("ambiguating new declaration %q+#D", newdecl);
1455 inform (DECL_SOURCE_LOCATION (olddecl),
1456 "old declaration %q#D", olddecl);
1457 return true;
1460 /* FIXME: The types are the same but the are differences
1461 in either the template heads or function requirements.
1462 We should be able to diagnose a set of common errors
1463 stemming from these declarations. For example:
1465 template<typename T> requires C void f(...);
1466 template<typename T> void f(...) requires C;
1468 These are functionally equivalent but not equivalent. */
1471 return false;
1474 /* OLD_PARMS is the innermost set of template parameters for some template
1475 declaration, and NEW_PARMS is the corresponding set of template parameters
1476 for a redeclaration of that template. Merge the default arguments within
1477 these two sets of parameters. CLASS_P is true iff the template in
1478 question is a class template. */
1480 bool
1481 merge_default_template_args (tree new_parms, tree old_parms, bool class_p)
1483 gcc_checking_assert (TREE_VEC_LENGTH (new_parms)
1484 == TREE_VEC_LENGTH (old_parms));
1485 for (int i = 0; i < TREE_VEC_LENGTH (new_parms); i++)
1487 tree new_parm = TREE_VALUE (TREE_VEC_ELT (new_parms, i));
1488 tree old_parm = TREE_VALUE (TREE_VEC_ELT (old_parms, i));
1489 tree& new_default = TREE_PURPOSE (TREE_VEC_ELT (new_parms, i));
1490 tree& old_default = TREE_PURPOSE (TREE_VEC_ELT (old_parms, i));
1491 if (new_default != NULL_TREE && old_default != NULL_TREE)
1493 auto_diagnostic_group d;
1494 error ("redefinition of default argument for %q+#D", new_parm);
1495 inform (DECL_SOURCE_LOCATION (old_parm),
1496 "original definition appeared here");
1497 return false;
1499 else if (new_default != NULL_TREE)
1500 /* Update the previous template parameters (which are the ones
1501 that will really count) with the new default value. */
1502 old_default = new_default;
1503 else if (class_p && old_default != NULL_TREE)
1504 /* Update the new parameters, too; they'll be used as the
1505 parameters for any members. */
1506 new_default = old_default;
1508 return true;
1511 /* If NEWDECL is a redeclaration of OLDDECL, merge the declarations.
1512 If the redeclaration is invalid, a diagnostic is issued, and the
1513 error_mark_node is returned. Otherwise, OLDDECL is returned.
1515 If NEWDECL is not a redeclaration of OLDDECL, NULL_TREE is
1516 returned.
1518 HIDING is true if the new decl is being hidden. WAS_HIDDEN is true
1519 if the old decl was hidden.
1521 Hidden decls can be anticipated builtins, injected friends, or
1522 (coming soon) injected from a local-extern decl. */
1524 tree
1525 duplicate_decls (tree newdecl, tree olddecl, bool hiding, bool was_hidden)
1527 unsigned olddecl_uid = DECL_UID (olddecl);
1528 int types_match = 0;
1529 int new_defines_function = 0;
1530 tree new_template_info;
1531 location_t olddecl_loc = DECL_SOURCE_LOCATION (olddecl);
1532 location_t newdecl_loc = DECL_SOURCE_LOCATION (newdecl);
1534 if (newdecl == olddecl)
1535 return olddecl;
1537 types_match = decls_match (newdecl, olddecl);
1539 /* If either the type of the new decl or the type of the old decl is an
1540 error_mark_node, then that implies that we have already issued an
1541 error (earlier) for some bogus type specification, and in that case,
1542 it is rather pointless to harass the user with yet more error message
1543 about the same declaration, so just pretend the types match here. */
1544 if (TREE_TYPE (newdecl) == error_mark_node
1545 || TREE_TYPE (olddecl) == error_mark_node)
1546 return error_mark_node;
1548 /* Check for redeclaration and other discrepancies. */
1549 if (TREE_CODE (olddecl) == FUNCTION_DECL
1550 && DECL_IS_UNDECLARED_BUILTIN (olddecl))
1552 if (TREE_CODE (newdecl) != FUNCTION_DECL)
1554 /* Avoid warnings redeclaring built-ins which have not been
1555 explicitly declared. */
1556 if (was_hidden)
1558 if (TREE_PUBLIC (newdecl)
1559 && CP_DECL_CONTEXT (newdecl) == global_namespace)
1560 warning_at (newdecl_loc,
1561 OPT_Wbuiltin_declaration_mismatch,
1562 "built-in function %qD declared as non-function",
1563 newdecl);
1564 return NULL_TREE;
1567 /* If you declare a built-in or predefined function name as static,
1568 the old definition is overridden, but optionally warn this was a
1569 bad choice of name. */
1570 if (! TREE_PUBLIC (newdecl))
1572 warning_at (newdecl_loc,
1573 OPT_Wshadow,
1574 fndecl_built_in_p (olddecl)
1575 ? G_("shadowing built-in function %q#D")
1576 : G_("shadowing library function %q#D"), olddecl);
1577 /* Discard the old built-in function. */
1578 return NULL_TREE;
1580 /* If the built-in is not ansi, then programs can override
1581 it even globally without an error. */
1582 else if (! fndecl_built_in_p (olddecl))
1583 warning_at (newdecl_loc, 0,
1584 "library function %q#D redeclared as non-function %q#D",
1585 olddecl, newdecl);
1586 else
1587 error_at (newdecl_loc,
1588 "declaration of %q#D conflicts with built-in "
1589 "declaration %q#D", newdecl, olddecl);
1590 return NULL_TREE;
1592 else if (!types_match)
1594 /* Avoid warnings redeclaring built-ins which have not been
1595 explicitly declared. */
1596 if (was_hidden)
1598 tree t1, t2;
1600 /* A new declaration doesn't match a built-in one unless it
1601 is also extern "C". */
1602 gcc_assert (DECL_IS_UNDECLARED_BUILTIN (olddecl));
1603 gcc_assert (DECL_EXTERN_C_P (olddecl));
1604 if (!DECL_EXTERN_C_P (newdecl))
1605 return NULL_TREE;
1607 for (t1 = TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1608 t2 = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1609 t1 || t2;
1610 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1612 if (!t1 || !t2)
1613 break;
1614 /* FILE, tm types are not known at the time
1615 we create the builtins. */
1616 for (unsigned i = 0;
1617 i < sizeof (builtin_structptr_types)
1618 / sizeof (builtin_structptr_type);
1619 ++i)
1620 if (TREE_VALUE (t2) == builtin_structptr_types[i].node)
1622 tree t = TREE_VALUE (t1);
1624 if (TYPE_PTR_P (t)
1625 && TYPE_IDENTIFIER (TREE_TYPE (t))
1626 == get_identifier (builtin_structptr_types[i].str)
1627 && compparms (TREE_CHAIN (t1), TREE_CHAIN (t2)))
1629 tree oldargs = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1631 TYPE_ARG_TYPES (TREE_TYPE (olddecl))
1632 = TYPE_ARG_TYPES (TREE_TYPE (newdecl));
1633 types_match = decls_match (newdecl, olddecl);
1634 if (types_match)
1635 return duplicate_decls (newdecl, olddecl,
1636 hiding, was_hidden);
1637 TYPE_ARG_TYPES (TREE_TYPE (olddecl)) = oldargs;
1639 goto next_arg;
1642 if (! same_type_p (TREE_VALUE (t1), TREE_VALUE (t2)))
1643 break;
1644 next_arg:;
1647 warning_at (newdecl_loc,
1648 OPT_Wbuiltin_declaration_mismatch,
1649 "declaration of %q#D conflicts with built-in "
1650 "declaration %q#D", newdecl, olddecl);
1652 else if ((DECL_EXTERN_C_P (newdecl)
1653 && DECL_EXTERN_C_P (olddecl))
1654 || compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1655 TYPE_ARG_TYPES (TREE_TYPE (olddecl))))
1657 /* Don't really override olddecl for __* prefixed builtins
1658 except for __[^b]*_chk, the compiler might be using those
1659 explicitly. */
1660 if (fndecl_built_in_p (olddecl))
1662 tree id = DECL_NAME (olddecl);
1663 const char *name = IDENTIFIER_POINTER (id);
1664 size_t len;
1666 if (name[0] == '_'
1667 && name[1] == '_'
1668 && (startswith (name + 2, "builtin_")
1669 || (len = strlen (name)) <= strlen ("___chk")
1670 || memcmp (name + len - strlen ("_chk"),
1671 "_chk", strlen ("_chk") + 1) != 0))
1673 if (DECL_INITIAL (newdecl))
1675 error_at (newdecl_loc,
1676 "definition of %q#D ambiguates built-in "
1677 "declaration %q#D", newdecl, olddecl);
1678 return error_mark_node;
1680 auto_diagnostic_group d;
1681 if (permerror (newdecl_loc,
1682 "new declaration %q#D ambiguates built-in"
1683 " declaration %q#D", newdecl, olddecl)
1684 && flag_permissive)
1685 inform (newdecl_loc,
1686 "ignoring the %q#D declaration", newdecl);
1687 return flag_permissive ? olddecl : error_mark_node;
1691 /* A near match; override the builtin. */
1693 if (TREE_PUBLIC (newdecl))
1694 warning_at (newdecl_loc,
1695 OPT_Wbuiltin_declaration_mismatch,
1696 "new declaration %q#D ambiguates built-in "
1697 "declaration %q#D", newdecl, olddecl);
1698 else
1699 warning (OPT_Wshadow,
1700 fndecl_built_in_p (olddecl)
1701 ? G_("shadowing built-in function %q#D")
1702 : G_("shadowing library function %q#D"), olddecl);
1704 else
1705 /* Discard the old built-in function. */
1706 return NULL_TREE;
1708 /* Replace the old RTL to avoid problems with inlining. */
1709 COPY_DECL_RTL (newdecl, olddecl);
1711 else
1713 /* Even if the types match, prefer the new declarations type
1714 for built-ins which have not been explicitly declared,
1715 for exception lists, etc... */
1716 tree type = TREE_TYPE (newdecl);
1717 tree attribs = (*targetm.merge_type_attributes)
1718 (TREE_TYPE (olddecl), type);
1720 type = cp_build_type_attribute_variant (type, attribs);
1721 TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = type;
1724 /* If a function is explicitly declared "throw ()", propagate that to
1725 the corresponding builtin. */
1726 if (DECL_BUILT_IN_CLASS (olddecl) == BUILT_IN_NORMAL
1727 && was_hidden
1728 && TREE_NOTHROW (newdecl)
1729 && !TREE_NOTHROW (olddecl))
1731 enum built_in_function fncode = DECL_FUNCTION_CODE (olddecl);
1732 tree tmpdecl = builtin_decl_explicit (fncode);
1733 if (tmpdecl && tmpdecl != olddecl && types_match)
1734 TREE_NOTHROW (tmpdecl) = 1;
1737 /* Whether or not the builtin can throw exceptions has no
1738 bearing on this declarator. */
1739 TREE_NOTHROW (olddecl) = 0;
1741 if (DECL_THIS_STATIC (newdecl) && !DECL_THIS_STATIC (olddecl))
1743 /* If a builtin function is redeclared as `static', merge
1744 the declarations, but make the original one static. */
1745 DECL_THIS_STATIC (olddecl) = 1;
1746 TREE_PUBLIC (olddecl) = 0;
1748 /* Make the old declaration consistent with the new one so
1749 that all remnants of the builtin-ness of this function
1750 will be banished. */
1751 SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
1752 COPY_DECL_RTL (newdecl, olddecl);
1755 else if (TREE_CODE (olddecl) != TREE_CODE (newdecl))
1757 /* C++ Standard, 3.3, clause 4:
1758 "[Note: a namespace name or a class template name must be unique
1759 in its declarative region (7.3.2, clause 14). ]" */
1760 if (TREE_CODE (olddecl) == NAMESPACE_DECL
1761 || TREE_CODE (newdecl) == NAMESPACE_DECL)
1762 /* Namespace conflicts with not namespace. */;
1763 else if (DECL_TYPE_TEMPLATE_P (olddecl)
1764 || DECL_TYPE_TEMPLATE_P (newdecl))
1765 /* Class template conflicts. */;
1766 else if ((TREE_CODE (olddecl) == TEMPLATE_DECL
1767 && DECL_TEMPLATE_RESULT (olddecl)
1768 && TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)) == VAR_DECL)
1769 || (TREE_CODE (newdecl) == TEMPLATE_DECL
1770 && DECL_TEMPLATE_RESULT (newdecl)
1771 && TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == VAR_DECL))
1772 /* Variable template conflicts. */;
1773 else if (concept_definition_p (olddecl)
1774 || concept_definition_p (newdecl))
1775 /* Concept conflicts. */;
1776 else if ((TREE_CODE (newdecl) == FUNCTION_DECL
1777 && DECL_FUNCTION_TEMPLATE_P (olddecl))
1778 || (TREE_CODE (olddecl) == FUNCTION_DECL
1779 && DECL_FUNCTION_TEMPLATE_P (newdecl)))
1781 /* One is a function and the other is a template
1782 function. */
1783 if (!UDLIT_OPER_P (DECL_NAME (newdecl)))
1784 return NULL_TREE;
1786 /* There can only be one! */
1787 if (TREE_CODE (newdecl) == TEMPLATE_DECL
1788 && check_raw_literal_operator (olddecl))
1789 error_at (newdecl_loc,
1790 "literal operator %q#D conflicts with"
1791 " raw literal operator", newdecl);
1792 else if (check_raw_literal_operator (newdecl))
1793 error_at (newdecl_loc,
1794 "raw literal operator %q#D conflicts with"
1795 " literal operator template", newdecl);
1796 else
1797 return NULL_TREE;
1799 inform (olddecl_loc, "previous declaration %q#D", olddecl);
1800 return error_mark_node;
1802 else if ((VAR_P (olddecl) && DECL_DECOMPOSITION_P (olddecl))
1803 || (VAR_P (newdecl) && DECL_DECOMPOSITION_P (newdecl)))
1804 /* A structured binding must be unique in its declarative region. */;
1805 else if (DECL_IMPLICIT_TYPEDEF_P (olddecl)
1806 || DECL_IMPLICIT_TYPEDEF_P (newdecl))
1807 /* One is an implicit typedef, that's ok. */
1808 return NULL_TREE;
1810 error ("%q#D redeclared as different kind of entity", newdecl);
1811 inform (olddecl_loc, "previous declaration %q#D", olddecl);
1813 return error_mark_node;
1815 else if (!types_match)
1817 if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl))
1818 /* These are certainly not duplicate declarations; they're
1819 from different scopes. */
1820 return NULL_TREE;
1822 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1824 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1825 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1827 /* The name of a class template may not be declared to refer to
1828 any other template, class, function, object, namespace, value,
1829 or type in the same scope. */
1830 if (TREE_CODE (oldres) == TYPE_DECL
1831 || TREE_CODE (newres) == TYPE_DECL)
1833 error_at (newdecl_loc,
1834 "conflicting declaration of template %q#D", newdecl);
1835 inform (olddecl_loc,
1836 "previous declaration %q#D", olddecl);
1837 return error_mark_node;
1840 else if (TREE_CODE (oldres) == FUNCTION_DECL
1841 && TREE_CODE (newres) == FUNCTION_DECL)
1843 if (duplicate_function_template_decls (newdecl, olddecl))
1844 return error_mark_node;
1845 return NULL_TREE;
1847 else if (check_concept_refinement (olddecl, newdecl))
1848 return error_mark_node;
1849 return NULL_TREE;
1851 if (TREE_CODE (newdecl) == FUNCTION_DECL)
1853 if (DECL_EXTERN_C_P (newdecl) && DECL_EXTERN_C_P (olddecl))
1855 error_at (newdecl_loc,
1856 "conflicting declaration of C function %q#D",
1857 newdecl);
1858 inform (olddecl_loc,
1859 "previous declaration %q#D", olddecl);
1860 return error_mark_node;
1862 /* For function versions, params and types match, but they
1863 are not ambiguous. */
1864 else if ((!DECL_FUNCTION_VERSIONED (newdecl)
1865 && !DECL_FUNCTION_VERSIONED (olddecl))
1866 // The functions have the same parameter types.
1867 && compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1868 TYPE_ARG_TYPES (TREE_TYPE (olddecl)))
1869 // And the same constraints.
1870 && equivalently_constrained (newdecl, olddecl))
1872 error_at (newdecl_loc,
1873 "ambiguating new declaration of %q#D", newdecl);
1874 inform (olddecl_loc,
1875 "old declaration %q#D", olddecl);
1876 return error_mark_node;
1878 else
1879 return NULL_TREE;
1881 else
1883 error_at (newdecl_loc, "conflicting declaration %q#D", newdecl);
1884 inform (olddecl_loc,
1885 "previous declaration as %q#D", olddecl);
1886 return error_mark_node;
1889 else if (TREE_CODE (newdecl) == FUNCTION_DECL
1890 && DECL_OMP_DECLARE_REDUCTION_P (newdecl))
1892 /* OMP UDRs are never duplicates. */
1893 gcc_assert (DECL_OMP_DECLARE_REDUCTION_P (olddecl));
1894 error_at (newdecl_loc,
1895 "redeclaration of %<pragma omp declare reduction%>");
1896 inform (olddecl_loc,
1897 "previous %<pragma omp declare reduction%> declaration");
1898 return error_mark_node;
1900 else if (TREE_CODE (newdecl) == FUNCTION_DECL
1901 && ((DECL_TEMPLATE_SPECIALIZATION (olddecl)
1902 && (!DECL_TEMPLATE_INFO (newdecl)
1903 || (DECL_TI_TEMPLATE (newdecl)
1904 != DECL_TI_TEMPLATE (olddecl))))
1905 || (DECL_TEMPLATE_SPECIALIZATION (newdecl)
1906 && (!DECL_TEMPLATE_INFO (olddecl)
1907 || (DECL_TI_TEMPLATE (olddecl)
1908 != DECL_TI_TEMPLATE (newdecl))))))
1909 /* It's OK to have a template specialization and a non-template
1910 with the same type, or to have specializations of two
1911 different templates with the same type. Note that if one is a
1912 specialization, and the other is an instantiation of the same
1913 template, that we do not exit at this point. That situation
1914 can occur if we instantiate a template class, and then
1915 specialize one of its methods. This situation is valid, but
1916 the declarations must be merged in the usual way. */
1917 return NULL_TREE;
1918 else if (TREE_CODE (newdecl) == FUNCTION_DECL
1919 && ((DECL_TEMPLATE_INSTANTIATION (olddecl)
1920 && !DECL_USE_TEMPLATE (newdecl))
1921 || (DECL_TEMPLATE_INSTANTIATION (newdecl)
1922 && !DECL_USE_TEMPLATE (olddecl))))
1923 /* One of the declarations is a template instantiation, and the
1924 other is not a template at all. That's OK. */
1925 return NULL_TREE;
1926 else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
1928 /* In [namespace.alias] we have:
1930 In a declarative region, a namespace-alias-definition can be
1931 used to redefine a namespace-alias declared in that declarative
1932 region to refer only to the namespace to which it already
1933 refers.
1935 Therefore, if we encounter a second alias directive for the same
1936 alias, we can just ignore the second directive. */
1937 if (DECL_NAMESPACE_ALIAS (newdecl)
1938 && (DECL_NAMESPACE_ALIAS (newdecl)
1939 == DECL_NAMESPACE_ALIAS (olddecl)))
1940 return olddecl;
1942 /* Leave it to update_binding to merge or report error. */
1943 return NULL_TREE;
1945 else
1947 const char *errmsg = redeclaration_error_message (newdecl, olddecl);
1948 if (errmsg)
1950 auto_diagnostic_group d;
1951 error_at (newdecl_loc, errmsg, newdecl);
1952 if (DECL_NAME (olddecl) != NULL_TREE)
1953 inform (olddecl_loc,
1954 (DECL_INITIAL (olddecl) && namespace_bindings_p ())
1955 ? G_("%q#D previously defined here")
1956 : G_("%q#D previously declared here"), olddecl);
1957 return error_mark_node;
1959 else if (TREE_CODE (olddecl) == FUNCTION_DECL
1960 && DECL_INITIAL (olddecl) != NULL_TREE
1961 && !prototype_p (TREE_TYPE (olddecl))
1962 && prototype_p (TREE_TYPE (newdecl)))
1964 /* Prototype decl follows defn w/o prototype. */
1965 auto_diagnostic_group d;
1966 if (warning_at (newdecl_loc, 0,
1967 "prototype specified for %q#D", newdecl))
1968 inform (olddecl_loc,
1969 "previous non-prototype definition here");
1971 else if (VAR_OR_FUNCTION_DECL_P (olddecl)
1972 && DECL_LANGUAGE (newdecl) != DECL_LANGUAGE (olddecl))
1974 /* [dcl.link]
1975 If two declarations of the same function or object
1976 specify different linkage-specifications ..., the program
1977 is ill-formed.... Except for functions with C++ linkage,
1978 a function declaration without a linkage specification
1979 shall not precede the first linkage specification for
1980 that function. A function can be declared without a
1981 linkage specification after an explicit linkage
1982 specification has been seen; the linkage explicitly
1983 specified in the earlier declaration is not affected by
1984 such a function declaration.
1986 DR 563 raises the question why the restrictions on
1987 functions should not also apply to objects. Older
1988 versions of G++ silently ignore the linkage-specification
1989 for this example:
1991 namespace N {
1992 extern int i;
1993 extern "C" int i;
1996 which is clearly wrong. Therefore, we now treat objects
1997 like functions. */
1998 if (current_lang_depth () == 0)
2000 /* There is no explicit linkage-specification, so we use
2001 the linkage from the previous declaration. */
2002 retrofit_lang_decl (newdecl);
2003 SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
2005 else
2007 auto_diagnostic_group d;
2008 error_at (newdecl_loc,
2009 "conflicting declaration of %q#D with %qL linkage",
2010 newdecl, DECL_LANGUAGE (newdecl));
2011 inform (olddecl_loc,
2012 "previous declaration with %qL linkage",
2013 DECL_LANGUAGE (olddecl));
2017 if (DECL_LANG_SPECIFIC (olddecl) && DECL_USE_TEMPLATE (olddecl))
2019 else if (TREE_CODE (olddecl) == FUNCTION_DECL)
2021 /* Note: free functions, as TEMPLATE_DECLs, are handled below. */
2022 if (DECL_FUNCTION_MEMBER_P (olddecl)
2023 && (/* grokfndecl passes member function templates too
2024 as FUNCTION_DECLs. */
2025 DECL_TEMPLATE_INFO (olddecl)
2026 /* C++11 8.3.6/6.
2027 Default arguments for a member function of a class
2028 template shall be specified on the initial declaration
2029 of the member function within the class template. */
2030 || CLASSTYPE_TEMPLATE_INFO (CP_DECL_CONTEXT (olddecl))))
2032 check_redeclaration_no_default_args (newdecl);
2034 if (DECL_TEMPLATE_INFO (olddecl)
2035 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (olddecl)))
2037 tree new_parms = DECL_TEMPLATE_INFO (newdecl)
2038 ? DECL_INNERMOST_TEMPLATE_PARMS (DECL_TI_TEMPLATE (newdecl))
2039 : INNERMOST_TEMPLATE_PARMS (current_template_parms);
2040 tree old_parms
2041 = DECL_INNERMOST_TEMPLATE_PARMS (DECL_TI_TEMPLATE (olddecl));
2042 merge_default_template_args (new_parms, old_parms,
2043 /*class_p=*/false);
2046 else
2048 tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl);
2049 tree t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
2050 int i = 1;
2052 for (; t1 && t1 != void_list_node;
2053 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2), i++)
2054 if (TREE_PURPOSE (t1) && TREE_PURPOSE (t2))
2056 if (simple_cst_equal (TREE_PURPOSE (t1),
2057 TREE_PURPOSE (t2)) == 1)
2059 auto_diagnostic_group d;
2060 if (permerror (newdecl_loc,
2061 "default argument given for parameter "
2062 "%d of %q#D", i, newdecl))
2063 inform (olddecl_loc,
2064 "previous specification in %q#D here",
2065 olddecl);
2067 else
2069 auto_diagnostic_group d;
2070 error_at (newdecl_loc,
2071 "default argument given for parameter %d "
2072 "of %q#D", i, newdecl);
2073 inform (olddecl_loc,
2074 "previous specification in %q#D here",
2075 olddecl);
2079 /* C++17 11.3.6/4: "If a friend declaration specifies a default
2080 argument expression, that declaration... shall be the only
2081 declaration of the function or function template in the
2082 translation unit." */
2083 check_no_redeclaration_friend_default_args (olddecl, newdecl);
2088 /* Do not merge an implicit typedef with an explicit one. In:
2090 class A;
2092 typedef class A A __attribute__ ((foo));
2094 the attribute should apply only to the typedef. */
2095 if (TREE_CODE (olddecl) == TYPE_DECL
2096 && (DECL_IMPLICIT_TYPEDEF_P (olddecl)
2097 || DECL_IMPLICIT_TYPEDEF_P (newdecl)))
2098 return NULL_TREE;
2100 if (DECL_TEMPLATE_PARM_P (olddecl) != DECL_TEMPLATE_PARM_P (newdecl))
2101 return NULL_TREE;
2103 if (!validate_constexpr_redeclaration (olddecl, newdecl))
2104 return error_mark_node;
2106 if (modules_p ()
2107 && TREE_CODE (CP_DECL_CONTEXT (olddecl)) == NAMESPACE_DECL
2108 && TREE_CODE (olddecl) != NAMESPACE_DECL
2109 && !hiding)
2111 if (!module_may_redeclare (olddecl))
2113 if (DECL_ARTIFICIAL (olddecl))
2114 error ("declaration %qD conflicts with builtin", newdecl);
2115 else
2117 error ("declaration %qD conflicts with import", newdecl);
2118 inform (olddecl_loc, "import declared %q#D here", olddecl);
2121 return error_mark_node;
2124 tree not_tmpl = STRIP_TEMPLATE (olddecl);
2125 if (DECL_LANG_SPECIFIC (not_tmpl) && DECL_MODULE_ATTACH_P (not_tmpl))
2127 if (DECL_MODULE_EXPORT_P (STRIP_TEMPLATE (newdecl))
2128 && !DECL_MODULE_EXPORT_P (not_tmpl))
2130 error ("conflicting exporting declaration %qD", newdecl);
2131 inform (olddecl_loc, "previous declaration %q#D here", olddecl);
2134 else if (DECL_MODULE_EXPORT_P (newdecl))
2135 DECL_MODULE_EXPORT_P (not_tmpl) = true;
2138 /* We have committed to returning OLDDECL at this point. */
2140 /* If new decl is `static' and an `extern' was seen previously,
2141 warn about it. */
2142 warn_extern_redeclared_static (newdecl, olddecl);
2144 /* True to merge attributes between the declarations, false to
2145 set OLDDECL's attributes to those of NEWDECL (for template
2146 explicit specializations that specify their own attributes
2147 independent of those specified for the primary template). */
2148 const bool merge_attr = (TREE_CODE (newdecl) != FUNCTION_DECL
2149 || !DECL_TEMPLATE_SPECIALIZATION (newdecl)
2150 || DECL_TEMPLATE_SPECIALIZATION (olddecl));
2152 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2154 if (merge_attr)
2156 if (diagnose_mismatched_attributes (olddecl, newdecl))
2157 inform (olddecl_loc, DECL_INITIAL (olddecl)
2158 ? G_("previous definition of %qD here")
2159 : G_("previous declaration of %qD here"), olddecl);
2161 /* [dcl.attr.noreturn]: The first declaration of a function shall
2162 specify the noreturn attribute if any declaration of that function
2163 specifies the noreturn attribute. */
2164 tree a;
2165 if (TREE_THIS_VOLATILE (newdecl)
2166 && !TREE_THIS_VOLATILE (olddecl)
2167 /* This applies to [[noreturn]] only, not its GNU variants. */
2168 && (a = lookup_attribute ("noreturn", DECL_ATTRIBUTES (newdecl)))
2169 && cxx11_attribute_p (a)
2170 && get_attribute_namespace (a) == NULL_TREE)
2172 error_at (newdecl_loc, "function %qD declared %<[[noreturn]]%> "
2173 "but its first declaration was not", newdecl);
2174 inform (olddecl_loc, "previous declaration of %qD", olddecl);
2178 /* Now that functions must hold information normally held
2179 by field decls, there is extra work to do so that
2180 declaration information does not get destroyed during
2181 definition. */
2182 if (DECL_VINDEX (olddecl))
2183 DECL_VINDEX (newdecl) = DECL_VINDEX (olddecl);
2184 if (DECL_CONTEXT (olddecl))
2185 DECL_CONTEXT (newdecl) = DECL_CONTEXT (olddecl);
2186 DECL_STATIC_CONSTRUCTOR (newdecl) |= DECL_STATIC_CONSTRUCTOR (olddecl);
2187 DECL_STATIC_DESTRUCTOR (newdecl) |= DECL_STATIC_DESTRUCTOR (olddecl);
2188 DECL_PURE_VIRTUAL_P (newdecl) |= DECL_PURE_VIRTUAL_P (olddecl);
2189 DECL_VIRTUAL_P (newdecl) |= DECL_VIRTUAL_P (olddecl);
2190 DECL_INVALID_OVERRIDER_P (newdecl) |= DECL_INVALID_OVERRIDER_P (olddecl);
2191 DECL_FINAL_P (newdecl) |= DECL_FINAL_P (olddecl);
2192 DECL_OVERRIDE_P (newdecl) |= DECL_OVERRIDE_P (olddecl);
2193 DECL_THIS_STATIC (newdecl) |= DECL_THIS_STATIC (olddecl);
2194 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (newdecl)
2195 |= DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (olddecl);
2196 if (DECL_OVERLOADED_OPERATOR_P (olddecl))
2197 DECL_OVERLOADED_OPERATOR_CODE_RAW (newdecl)
2198 = DECL_OVERLOADED_OPERATOR_CODE_RAW (olddecl);
2199 new_defines_function = DECL_INITIAL (newdecl) != NULL_TREE;
2201 /* Optionally warn about more than one declaration for the same
2202 name, but don't warn about a function declaration followed by a
2203 definition. */
2204 if (warn_redundant_decls && ! DECL_ARTIFICIAL (olddecl)
2205 && !(new_defines_function && DECL_INITIAL (olddecl) == NULL_TREE)
2206 /* Don't warn about extern decl followed by definition. */
2207 && !(DECL_EXTERNAL (olddecl) && ! DECL_EXTERNAL (newdecl))
2208 /* Don't warn if at least one is/was hidden. */
2209 && !(hiding || was_hidden)
2210 /* Don't warn about declaration followed by specialization. */
2211 && (! DECL_TEMPLATE_SPECIALIZATION (newdecl)
2212 || DECL_TEMPLATE_SPECIALIZATION (olddecl)))
2214 auto_diagnostic_group d;
2215 if (warning_at (newdecl_loc,
2216 OPT_Wredundant_decls,
2217 "redundant redeclaration of %qD in same scope",
2218 newdecl))
2219 inform (olddecl_loc,
2220 "previous declaration of %qD", olddecl);
2223 /* [dcl.fct.def.delete] A deleted definition of a function shall be the
2224 first declaration of the function or, for an explicit specialization
2225 of a function template, the first declaration of that
2226 specialization. */
2227 if (!(DECL_TEMPLATE_INSTANTIATION (olddecl)
2228 && DECL_TEMPLATE_SPECIALIZATION (newdecl)))
2230 if (DECL_DELETED_FN (newdecl))
2232 auto_diagnostic_group d;
2233 if (pedwarn (newdecl_loc, 0, "deleted definition of %qD "
2234 "is not first declaration", newdecl))
2235 inform (olddecl_loc,
2236 "previous declaration of %qD", olddecl);
2238 DECL_DELETED_FN (newdecl) |= DECL_DELETED_FN (olddecl);
2242 /* Deal with C++: must preserve virtual function table size. */
2243 if (TREE_CODE (olddecl) == TYPE_DECL)
2245 tree newtype = TREE_TYPE (newdecl);
2246 tree oldtype = TREE_TYPE (olddecl);
2248 if (newtype != error_mark_node && oldtype != error_mark_node
2249 && TYPE_LANG_SPECIFIC (newtype) && TYPE_LANG_SPECIFIC (oldtype))
2250 CLASSTYPE_FRIEND_CLASSES (newtype)
2251 = CLASSTYPE_FRIEND_CLASSES (oldtype);
2253 DECL_ORIGINAL_TYPE (newdecl) = DECL_ORIGINAL_TYPE (olddecl);
2256 /* Copy all the DECL_... slots specified in the new decl except for
2257 any that we copy here from the old type. */
2258 if (merge_attr)
2259 DECL_ATTRIBUTES (newdecl)
2260 = (*targetm.merge_decl_attributes) (olddecl, newdecl);
2261 else
2262 DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
2264 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
2266 tree old_result = DECL_TEMPLATE_RESULT (olddecl);
2267 tree new_result = DECL_TEMPLATE_RESULT (newdecl);
2268 TREE_TYPE (olddecl) = TREE_TYPE (old_result);
2270 /* The new decl should not already have gathered any
2271 specializations. */
2272 gcc_assert (!DECL_TEMPLATE_SPECIALIZATIONS (newdecl));
2274 DECL_ATTRIBUTES (old_result)
2275 = (*targetm.merge_decl_attributes) (old_result, new_result);
2277 if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2279 if (DECL_SOURCE_LOCATION (newdecl)
2280 != DECL_SOURCE_LOCATION (olddecl))
2282 /* Per C++11 8.3.6/4, default arguments cannot be added in
2283 later declarations of a function template. */
2284 check_redeclaration_no_default_args (newdecl);
2285 /* C++17 11.3.6/4: "If a friend declaration specifies a default
2286 argument expression, that declaration... shall be the only
2287 declaration of the function or function template in the
2288 translation unit." */
2289 check_no_redeclaration_friend_default_args
2290 (old_result, new_result);
2292 tree new_parms = DECL_INNERMOST_TEMPLATE_PARMS (newdecl);
2293 tree old_parms = DECL_INNERMOST_TEMPLATE_PARMS (olddecl);
2294 merge_default_template_args (new_parms, old_parms,
2295 /*class_p=*/false);
2297 if (!DECL_UNIQUE_FRIEND_P (old_result))
2298 DECL_UNIQUE_FRIEND_P (new_result) = false;
2300 check_default_args (newdecl);
2302 if (GNU_INLINE_P (old_result) != GNU_INLINE_P (new_result)
2303 && DECL_INITIAL (new_result))
2305 if (DECL_INITIAL (old_result))
2306 DECL_UNINLINABLE (old_result) = 1;
2307 else
2308 DECL_UNINLINABLE (old_result) = DECL_UNINLINABLE (new_result);
2309 DECL_EXTERNAL (old_result) = DECL_EXTERNAL (new_result);
2310 DECL_NOT_REALLY_EXTERN (old_result)
2311 = DECL_NOT_REALLY_EXTERN (new_result);
2312 DECL_INTERFACE_KNOWN (old_result)
2313 = DECL_INTERFACE_KNOWN (new_result);
2314 DECL_DECLARED_INLINE_P (old_result)
2315 = DECL_DECLARED_INLINE_P (new_result);
2316 DECL_DISREGARD_INLINE_LIMITS (old_result)
2317 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2320 else
2322 DECL_DECLARED_INLINE_P (old_result)
2323 |= DECL_DECLARED_INLINE_P (new_result);
2324 DECL_DISREGARD_INLINE_LIMITS (old_result)
2325 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2326 check_redeclaration_exception_specification (newdecl, olddecl);
2328 merge_attribute_bits (new_result, old_result);
2332 /* If the new declaration is a definition, update the file and
2333 line information on the declaration, and also make
2334 the old declaration the same definition. */
2335 if (DECL_INITIAL (new_result) != NULL_TREE)
2337 DECL_SOURCE_LOCATION (olddecl)
2338 = DECL_SOURCE_LOCATION (old_result)
2339 = DECL_SOURCE_LOCATION (newdecl);
2340 DECL_INITIAL (old_result) = DECL_INITIAL (new_result);
2341 if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2343 tree parm;
2344 DECL_ARGUMENTS (old_result)
2345 = DECL_ARGUMENTS (new_result);
2346 for (parm = DECL_ARGUMENTS (old_result); parm;
2347 parm = DECL_CHAIN (parm))
2348 DECL_CONTEXT (parm) = old_result;
2350 if (tree fc = DECL_FRIEND_CONTEXT (new_result))
2351 SET_DECL_FRIEND_CONTEXT (old_result, fc);
2355 return olddecl;
2358 if (types_match)
2360 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2361 check_redeclaration_exception_specification (newdecl, olddecl);
2363 /* Automatically handles default parameters. */
2364 tree oldtype = TREE_TYPE (olddecl);
2365 tree newtype;
2367 /* For typedefs use the old type, as the new type's DECL_NAME points
2368 at newdecl, which will be ggc_freed. */
2369 if (TREE_CODE (newdecl) == TYPE_DECL)
2371 /* But NEWTYPE might have an attribute, honor that. */
2372 tree tem = TREE_TYPE (newdecl);
2373 newtype = oldtype;
2375 if (TYPE_USER_ALIGN (tem))
2377 if (TYPE_ALIGN (tem) > TYPE_ALIGN (newtype))
2378 SET_TYPE_ALIGN (newtype, TYPE_ALIGN (tem));
2379 TYPE_USER_ALIGN (newtype) = true;
2382 /* And remove the new type from the variants list. */
2383 if (TYPE_NAME (TREE_TYPE (newdecl)) == newdecl)
2385 tree remove = TREE_TYPE (newdecl);
2386 if (TYPE_MAIN_VARIANT (remove) == remove)
2388 gcc_assert (TYPE_NEXT_VARIANT (remove) == NULL_TREE);
2389 /* If remove is the main variant, no need to remove that
2390 from the list. One of the DECL_ORIGINAL_TYPE
2391 variants, e.g. created for aligned attribute, might still
2392 refer to the newdecl TYPE_DECL though, so remove that one
2393 in that case. */
2394 if (tree orig = DECL_ORIGINAL_TYPE (newdecl))
2395 if (orig != remove)
2396 for (tree t = TYPE_MAIN_VARIANT (orig); t;
2397 t = TYPE_MAIN_VARIANT (t))
2398 if (TYPE_NAME (TYPE_NEXT_VARIANT (t)) == newdecl)
2400 TYPE_NEXT_VARIANT (t)
2401 = TYPE_NEXT_VARIANT (TYPE_NEXT_VARIANT (t));
2402 break;
2405 else
2406 for (tree t = TYPE_MAIN_VARIANT (remove); ;
2407 t = TYPE_NEXT_VARIANT (t))
2408 if (TYPE_NEXT_VARIANT (t) == remove)
2410 TYPE_NEXT_VARIANT (t) = TYPE_NEXT_VARIANT (remove);
2411 break;
2415 else if (merge_attr)
2416 newtype = merge_types (TREE_TYPE (newdecl), TREE_TYPE (olddecl));
2417 else
2418 newtype = TREE_TYPE (newdecl);
2420 if (VAR_P (newdecl))
2422 DECL_THIS_EXTERN (newdecl) |= DECL_THIS_EXTERN (olddecl);
2423 /* For already initialized vars, TREE_READONLY could have been
2424 cleared in cp_finish_decl, because the var needs runtime
2425 initialization or destruction. Make sure not to set
2426 TREE_READONLY on it again. */
2427 if (DECL_INITIALIZED_P (olddecl)
2428 && !DECL_EXTERNAL (olddecl)
2429 && !TREE_READONLY (olddecl))
2430 TREE_READONLY (newdecl) = 0;
2431 DECL_INITIALIZED_P (newdecl) |= DECL_INITIALIZED_P (olddecl);
2432 DECL_NONTRIVIALLY_INITIALIZED_P (newdecl)
2433 |= DECL_NONTRIVIALLY_INITIALIZED_P (olddecl);
2434 if (DECL_DEPENDENT_INIT_P (olddecl))
2435 SET_DECL_DEPENDENT_INIT_P (newdecl, true);
2436 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (newdecl)
2437 |= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (olddecl);
2438 DECL_DECLARED_CONSTEXPR_P (newdecl)
2439 |= DECL_DECLARED_CONSTEXPR_P (olddecl);
2440 DECL_DECLARED_CONSTINIT_P (newdecl)
2441 |= DECL_DECLARED_CONSTINIT_P (olddecl);
2443 /* Merge the threadprivate attribute from OLDDECL into NEWDECL. */
2444 if (DECL_LANG_SPECIFIC (olddecl)
2445 && CP_DECL_THREADPRIVATE_P (olddecl))
2447 /* Allocate a LANG_SPECIFIC structure for NEWDECL, if needed. */
2448 retrofit_lang_decl (newdecl);
2449 CP_DECL_THREADPRIVATE_P (newdecl) = 1;
2453 /* An explicit specialization of a function template or of a member
2454 function of a class template can be declared transaction_safe
2455 independently of whether the corresponding template entity is declared
2456 transaction_safe. */
2457 if (flag_tm && TREE_CODE (newdecl) == FUNCTION_DECL
2458 && DECL_TEMPLATE_INSTANTIATION (olddecl)
2459 && DECL_TEMPLATE_SPECIALIZATION (newdecl)
2460 && tx_safe_fn_type_p (newtype)
2461 && !tx_safe_fn_type_p (TREE_TYPE (newdecl)))
2462 newtype = tx_unsafe_fn_variant (newtype);
2464 TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = newtype;
2466 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2467 check_default_args (newdecl);
2469 /* Lay the type out, unless already done. */
2470 if (! same_type_p (newtype, oldtype)
2471 && TREE_TYPE (newdecl) != error_mark_node
2472 && !(processing_template_decl && uses_template_parms (newdecl)))
2473 layout_type (TREE_TYPE (newdecl));
2475 if ((VAR_P (newdecl)
2476 || TREE_CODE (newdecl) == PARM_DECL
2477 || TREE_CODE (newdecl) == RESULT_DECL
2478 || TREE_CODE (newdecl) == FIELD_DECL
2479 || TREE_CODE (newdecl) == TYPE_DECL)
2480 && !(processing_template_decl && uses_template_parms (newdecl)))
2481 layout_decl (newdecl, 0);
2483 /* Merge deprecatedness. */
2484 if (TREE_DEPRECATED (newdecl))
2485 TREE_DEPRECATED (olddecl) = 1;
2487 /* Merge unavailability. */
2488 if (TREE_UNAVAILABLE (newdecl))
2489 TREE_UNAVAILABLE (olddecl) = 1;
2491 /* Preserve function specific target and optimization options */
2492 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2494 if (DECL_FUNCTION_SPECIFIC_TARGET (olddecl)
2495 && !DECL_FUNCTION_SPECIFIC_TARGET (newdecl))
2496 DECL_FUNCTION_SPECIFIC_TARGET (newdecl)
2497 = DECL_FUNCTION_SPECIFIC_TARGET (olddecl);
2499 if (DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl)
2500 && !DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl))
2501 DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl)
2502 = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl);
2504 if (!DECL_UNIQUE_FRIEND_P (olddecl))
2505 DECL_UNIQUE_FRIEND_P (newdecl) = false;
2507 else
2509 /* Merge the const type qualifier. */
2510 if (TREE_READONLY (newdecl))
2511 TREE_READONLY (olddecl) = 1;
2512 /* Merge the volatile type qualifier. */
2513 if (TREE_THIS_VOLATILE (newdecl))
2514 TREE_THIS_VOLATILE (olddecl) = 1;
2517 /* Merge the initialization information. */
2518 if (DECL_INITIAL (newdecl) == NULL_TREE
2519 && DECL_INITIAL (olddecl) != NULL_TREE)
2521 DECL_INITIAL (newdecl) = DECL_INITIAL (olddecl);
2522 DECL_SOURCE_LOCATION (newdecl) = DECL_SOURCE_LOCATION (olddecl);
2523 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2525 DECL_SAVED_TREE (newdecl) = DECL_SAVED_TREE (olddecl);
2526 DECL_STRUCT_FUNCTION (newdecl) = DECL_STRUCT_FUNCTION (olddecl);
2530 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2532 DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (newdecl)
2533 |= DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (olddecl);
2534 DECL_NO_LIMIT_STACK (newdecl) |= DECL_NO_LIMIT_STACK (olddecl);
2535 if (DECL_IS_OPERATOR_NEW_P (olddecl))
2536 DECL_SET_IS_OPERATOR_NEW (newdecl, true);
2537 DECL_LOOPING_CONST_OR_PURE_P (newdecl)
2538 |= DECL_LOOPING_CONST_OR_PURE_P (olddecl);
2539 DECL_IS_REPLACEABLE_OPERATOR (newdecl)
2540 |= DECL_IS_REPLACEABLE_OPERATOR (olddecl);
2542 if (merge_attr)
2543 merge_attribute_bits (newdecl, olddecl);
2544 else
2546 /* Merge the noreturn bit. */
2547 TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2548 TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2549 TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2550 DECL_IS_MALLOC (olddecl) = DECL_IS_MALLOC (newdecl);
2551 DECL_PURE_P (olddecl) = DECL_PURE_P (newdecl);
2553 /* Keep the old RTL. */
2554 COPY_DECL_RTL (olddecl, newdecl);
2556 else if (VAR_P (newdecl)
2557 && (DECL_SIZE (olddecl) || !DECL_SIZE (newdecl)))
2559 /* Keep the old RTL. We cannot keep the old RTL if the old
2560 declaration was for an incomplete object and the new
2561 declaration is not since many attributes of the RTL will
2562 change. */
2563 COPY_DECL_RTL (olddecl, newdecl);
2566 /* If cannot merge, then use the new type and qualifiers,
2567 and don't preserve the old rtl. */
2568 else
2570 /* Clean out any memory we had of the old declaration. */
2571 tree oldstatic = value_member (olddecl, static_aggregates);
2572 if (oldstatic)
2573 TREE_VALUE (oldstatic) = error_mark_node;
2575 TREE_TYPE (olddecl) = TREE_TYPE (newdecl);
2576 TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2577 TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2578 TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2579 TREE_SIDE_EFFECTS (olddecl) = TREE_SIDE_EFFECTS (newdecl);
2582 /* Merge the storage class information. */
2583 merge_weak (newdecl, olddecl);
2585 DECL_DEFER_OUTPUT (newdecl) |= DECL_DEFER_OUTPUT (olddecl);
2586 TREE_PUBLIC (newdecl) = TREE_PUBLIC (olddecl);
2587 TREE_STATIC (olddecl) = TREE_STATIC (newdecl) |= TREE_STATIC (olddecl);
2588 if (! DECL_EXTERNAL (olddecl))
2589 DECL_EXTERNAL (newdecl) = 0;
2590 if (! DECL_COMDAT (olddecl))
2591 DECL_COMDAT (newdecl) = 0;
2593 if (VAR_OR_FUNCTION_DECL_P (newdecl) && DECL_LOCAL_DECL_P (newdecl))
2595 if (!DECL_LOCAL_DECL_P (olddecl))
2596 /* This can happen if olddecl was brought in from the
2597 enclosing namespace via a using-decl. The new decl is
2598 then not a block-scope extern at all. */
2599 DECL_LOCAL_DECL_P (newdecl) = false;
2600 else
2602 retrofit_lang_decl (newdecl);
2603 tree alias = DECL_LOCAL_DECL_ALIAS (newdecl)
2604 = DECL_LOCAL_DECL_ALIAS (olddecl);
2605 DECL_ATTRIBUTES (alias)
2606 = (*targetm.merge_decl_attributes) (alias, newdecl);
2607 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2608 merge_attribute_bits (newdecl, alias);
2612 new_template_info = NULL_TREE;
2613 if (DECL_LANG_SPECIFIC (newdecl) && DECL_LANG_SPECIFIC (olddecl))
2615 bool new_redefines_gnu_inline = false;
2617 if (new_defines_function
2618 && ((DECL_INTERFACE_KNOWN (olddecl)
2619 && TREE_CODE (olddecl) == FUNCTION_DECL)
2620 || (TREE_CODE (olddecl) == TEMPLATE_DECL
2621 && (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl))
2622 == FUNCTION_DECL))))
2623 new_redefines_gnu_inline = GNU_INLINE_P (STRIP_TEMPLATE (olddecl));
2625 if (!new_redefines_gnu_inline)
2627 DECL_INTERFACE_KNOWN (newdecl) |= DECL_INTERFACE_KNOWN (olddecl);
2628 DECL_NOT_REALLY_EXTERN (newdecl) |= DECL_NOT_REALLY_EXTERN (olddecl);
2629 DECL_COMDAT (newdecl) |= DECL_COMDAT (olddecl);
2632 if (TREE_CODE (newdecl) != TYPE_DECL)
2634 DECL_TEMPLATE_INSTANTIATED (newdecl)
2635 |= DECL_TEMPLATE_INSTANTIATED (olddecl);
2636 DECL_ODR_USED (newdecl) |= DECL_ODR_USED (olddecl);
2638 /* If the OLDDECL is an instantiation and/or specialization,
2639 then the NEWDECL must be too. But, it may not yet be marked
2640 as such if the caller has created NEWDECL, but has not yet
2641 figured out that it is a redeclaration. */
2642 if (!DECL_USE_TEMPLATE (newdecl))
2643 DECL_USE_TEMPLATE (newdecl) = DECL_USE_TEMPLATE (olddecl);
2645 if (!DECL_TEMPLATE_SPECIALIZATION (newdecl))
2646 DECL_INITIALIZED_IN_CLASS_P (newdecl)
2647 |= DECL_INITIALIZED_IN_CLASS_P (olddecl);
2650 /* Don't really know how much of the language-specific
2651 values we should copy from old to new. */
2652 DECL_IN_AGGR_P (newdecl) = DECL_IN_AGGR_P (olddecl);
2654 if (LANG_DECL_HAS_MIN (newdecl))
2656 DECL_ACCESS (newdecl) = DECL_ACCESS (olddecl);
2657 if (new_defines_function
2658 && DECL_TEMPLATE_INFO (olddecl)
2659 && DECL_UNIQUE_FRIEND_P (DECL_TEMPLATE_RESULT
2660 (DECL_TI_TEMPLATE (olddecl))))
2661 /* Don't copy template info from a non-template friend declaration
2662 in a class template (PR105761). */;
2663 else if (DECL_TEMPLATE_INFO (newdecl))
2665 new_template_info = DECL_TEMPLATE_INFO (newdecl);
2666 if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2667 && DECL_TEMPLATE_SPECIALIZATION (newdecl))
2668 /* Remember the presence of explicit specialization args. */
2669 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (olddecl))
2670 = TINFO_USED_TEMPLATE_ID (new_template_info);
2671 DECL_TEMPLATE_INFO (newdecl) = DECL_TEMPLATE_INFO (olddecl);
2673 else
2674 DECL_TEMPLATE_INFO (newdecl) = DECL_TEMPLATE_INFO (olddecl);
2677 if (DECL_DECLARES_FUNCTION_P (newdecl))
2679 /* Only functions have these fields. */
2680 DECL_NONCONVERTING_P (newdecl) = DECL_NONCONVERTING_P (olddecl);
2681 DECL_BEFRIENDING_CLASSES (newdecl)
2682 = chainon (DECL_BEFRIENDING_CLASSES (newdecl),
2683 DECL_BEFRIENDING_CLASSES (olddecl));
2684 /* DECL_THUNKS is only valid for virtual functions,
2685 otherwise it is a DECL_FRIEND_CONTEXT. */
2686 if (DECL_VIRTUAL_P (newdecl))
2687 SET_DECL_THUNKS (newdecl, DECL_THUNKS (olddecl));
2688 else if (tree fc = DECL_FRIEND_CONTEXT (newdecl))
2689 SET_DECL_FRIEND_CONTEXT (olddecl, fc);
2691 else if (VAR_P (newdecl))
2693 /* Only variables have this field. */
2694 if (VAR_HAD_UNKNOWN_BOUND (olddecl))
2695 SET_VAR_HAD_UNKNOWN_BOUND (newdecl);
2699 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2701 tree parm;
2703 /* Merge parameter attributes. */
2704 tree oldarg, newarg;
2705 for (oldarg = DECL_ARGUMENTS(olddecl), newarg = DECL_ARGUMENTS(newdecl);
2706 oldarg && newarg;
2707 oldarg = DECL_CHAIN(oldarg), newarg = DECL_CHAIN(newarg))
2709 DECL_ATTRIBUTES (newarg)
2710 = (*targetm.merge_decl_attributes) (oldarg, newarg);
2711 DECL_ATTRIBUTES (oldarg) = DECL_ATTRIBUTES (newarg);
2714 if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2715 && !DECL_TEMPLATE_INSTANTIATION (newdecl))
2717 /* If newdecl is not a specialization, then it is not a
2718 template-related function at all. And that means that we
2719 should have exited above, returning 0. */
2720 gcc_assert (DECL_TEMPLATE_SPECIALIZATION (newdecl));
2722 if (DECL_ODR_USED (olddecl))
2723 /* From [temp.expl.spec]:
2725 If a template, a member template or the member of a class
2726 template is explicitly specialized then that
2727 specialization shall be declared before the first use of
2728 that specialization that would cause an implicit
2729 instantiation to take place, in every translation unit in
2730 which such a use occurs. */
2731 error ("explicit specialization of %qD after first use",
2732 olddecl);
2734 SET_DECL_TEMPLATE_SPECIALIZATION (olddecl);
2735 DECL_COMDAT (newdecl) = (TREE_PUBLIC (newdecl)
2736 && DECL_DECLARED_INLINE_P (newdecl));
2738 /* Don't propagate visibility from the template to the
2739 specialization here. We'll do that in determine_visibility if
2740 appropriate. */
2741 DECL_VISIBILITY_SPECIFIED (olddecl) = 0;
2743 /* [temp.expl.spec/14] We don't inline explicit specialization
2744 just because the primary template says so. */
2745 gcc_assert (!merge_attr);
2747 DECL_DECLARED_INLINE_P (olddecl)
2748 = DECL_DECLARED_INLINE_P (newdecl);
2750 DECL_DISREGARD_INLINE_LIMITS (olddecl)
2751 = DECL_DISREGARD_INLINE_LIMITS (newdecl);
2753 DECL_UNINLINABLE (olddecl) = DECL_UNINLINABLE (newdecl);
2755 else if (new_defines_function && DECL_INITIAL (olddecl))
2757 /* Never inline re-defined extern inline functions.
2758 FIXME: this could be better handled by keeping both
2759 function as separate declarations. */
2760 DECL_UNINLINABLE (newdecl) = 1;
2762 else
2764 if (DECL_PENDING_INLINE_P (olddecl))
2766 DECL_PENDING_INLINE_P (newdecl) = 1;
2767 DECL_PENDING_INLINE_INFO (newdecl)
2768 = DECL_PENDING_INLINE_INFO (olddecl);
2770 else if (DECL_PENDING_INLINE_P (newdecl))
2772 else if (DECL_SAVED_AUTO_RETURN_TYPE (newdecl) == NULL)
2773 DECL_SAVED_AUTO_RETURN_TYPE (newdecl)
2774 = DECL_SAVED_AUTO_RETURN_TYPE (olddecl);
2776 DECL_DECLARED_INLINE_P (newdecl) |= DECL_DECLARED_INLINE_P (olddecl);
2778 DECL_UNINLINABLE (newdecl) = DECL_UNINLINABLE (olddecl)
2779 = (DECL_UNINLINABLE (newdecl) || DECL_UNINLINABLE (olddecl));
2781 DECL_DISREGARD_INLINE_LIMITS (newdecl)
2782 = DECL_DISREGARD_INLINE_LIMITS (olddecl)
2783 = (DECL_DISREGARD_INLINE_LIMITS (newdecl)
2784 || DECL_DISREGARD_INLINE_LIMITS (olddecl));
2787 /* Preserve abstractness on cloned [cd]tors. */
2788 DECL_ABSTRACT_P (newdecl) = DECL_ABSTRACT_P (olddecl);
2790 /* Update newdecl's parms to point at olddecl. */
2791 for (parm = DECL_ARGUMENTS (newdecl); parm;
2792 parm = DECL_CHAIN (parm))
2793 DECL_CONTEXT (parm) = olddecl;
2795 if (! types_match)
2797 SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
2798 COPY_DECL_ASSEMBLER_NAME (newdecl, olddecl);
2799 COPY_DECL_RTL (newdecl, olddecl);
2801 if (! types_match || new_defines_function)
2803 /* These need to be copied so that the names are available.
2804 Note that if the types do match, we'll preserve inline
2805 info and other bits, but if not, we won't. */
2806 DECL_ARGUMENTS (olddecl) = DECL_ARGUMENTS (newdecl);
2807 DECL_RESULT (olddecl) = DECL_RESULT (newdecl);
2809 /* If redeclaring a builtin function, it stays built in
2810 if newdecl is a gnu_inline definition, or if newdecl is just
2811 a declaration. */
2812 if (fndecl_built_in_p (olddecl)
2813 && (new_defines_function ? GNU_INLINE_P (newdecl) : types_match))
2815 copy_decl_built_in_function (newdecl, olddecl);
2816 /* If we're keeping the built-in definition, keep the rtl,
2817 regardless of declaration matches. */
2818 COPY_DECL_RTL (olddecl, newdecl);
2819 if (DECL_BUILT_IN_CLASS (newdecl) == BUILT_IN_NORMAL)
2821 enum built_in_function fncode = DECL_FUNCTION_CODE (newdecl);
2822 if (builtin_decl_explicit_p (fncode))
2824 /* A compatible prototype of these builtin functions
2825 is seen, assume the runtime implements it with
2826 the expected semantics. */
2827 switch (fncode)
2829 case BUILT_IN_STPCPY:
2830 set_builtin_decl_implicit_p (fncode, true);
2831 break;
2832 default:
2833 set_builtin_decl_declared_p (fncode, true);
2834 break;
2838 copy_attributes_to_builtin (newdecl);
2841 if (new_defines_function)
2842 /* If defining a function declared with other language
2843 linkage, use the previously declared language linkage. */
2844 SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
2845 else if (types_match)
2847 DECL_RESULT (newdecl) = DECL_RESULT (olddecl);
2848 /* Don't clear out the arguments if we're just redeclaring a
2849 function. */
2850 if (DECL_ARGUMENTS (olddecl))
2851 DECL_ARGUMENTS (newdecl) = DECL_ARGUMENTS (olddecl);
2854 else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
2855 NAMESPACE_LEVEL (newdecl) = NAMESPACE_LEVEL (olddecl);
2857 /* Now preserve various other info from the definition. */
2858 TREE_ADDRESSABLE (newdecl) = TREE_ADDRESSABLE (olddecl);
2859 TREE_ASM_WRITTEN (newdecl) = TREE_ASM_WRITTEN (olddecl);
2860 DECL_COMMON (newdecl) = DECL_COMMON (olddecl);
2861 COPY_DECL_ASSEMBLER_NAME (olddecl, newdecl);
2863 /* Warn about conflicting visibility specifications. */
2864 if (DECL_VISIBILITY_SPECIFIED (olddecl)
2865 && DECL_VISIBILITY_SPECIFIED (newdecl)
2866 && DECL_VISIBILITY (newdecl) != DECL_VISIBILITY (olddecl))
2868 auto_diagnostic_group d;
2869 if (warning_at (newdecl_loc, OPT_Wattributes,
2870 "%qD: visibility attribute ignored because it "
2871 "conflicts with previous declaration", newdecl))
2872 inform (olddecl_loc,
2873 "previous declaration of %qD", olddecl);
2875 /* Choose the declaration which specified visibility. */
2876 if (DECL_VISIBILITY_SPECIFIED (olddecl))
2878 DECL_VISIBILITY (newdecl) = DECL_VISIBILITY (olddecl);
2879 DECL_VISIBILITY_SPECIFIED (newdecl) = 1;
2881 /* Init priority used to be merged from newdecl to olddecl by the memcpy,
2882 so keep this behavior. */
2883 if (VAR_P (newdecl) && DECL_HAS_INIT_PRIORITY_P (newdecl))
2885 SET_DECL_INIT_PRIORITY (olddecl, DECL_INIT_PRIORITY (newdecl));
2886 DECL_HAS_INIT_PRIORITY_P (olddecl) = 1;
2888 /* Likewise for DECL_ALIGN, DECL_USER_ALIGN and DECL_PACKED. */
2889 if (DECL_ALIGN (olddecl) > DECL_ALIGN (newdecl))
2891 SET_DECL_ALIGN (newdecl, DECL_ALIGN (olddecl));
2892 DECL_USER_ALIGN (newdecl) |= DECL_USER_ALIGN (olddecl);
2894 else if (DECL_ALIGN (olddecl) == DECL_ALIGN (newdecl)
2895 && DECL_USER_ALIGN (olddecl) != DECL_USER_ALIGN (newdecl))
2896 DECL_USER_ALIGN (newdecl) = 1;
2898 DECL_USER_ALIGN (olddecl) = DECL_USER_ALIGN (newdecl);
2899 if (DECL_WARN_IF_NOT_ALIGN (olddecl)
2900 > DECL_WARN_IF_NOT_ALIGN (newdecl))
2901 SET_DECL_WARN_IF_NOT_ALIGN (newdecl,
2902 DECL_WARN_IF_NOT_ALIGN (olddecl));
2903 if (TREE_CODE (newdecl) == FIELD_DECL)
2904 DECL_PACKED (olddecl) = DECL_PACKED (newdecl);
2906 /* The DECL_LANG_SPECIFIC information in OLDDECL will be replaced
2907 with that from NEWDECL below. */
2908 if (DECL_LANG_SPECIFIC (olddecl))
2910 gcc_checking_assert (DECL_LANG_SPECIFIC (olddecl)
2911 != DECL_LANG_SPECIFIC (newdecl));
2912 ggc_free (DECL_LANG_SPECIFIC (olddecl));
2915 /* Merge the USED information. */
2916 if (TREE_USED (olddecl))
2917 TREE_USED (newdecl) = 1;
2918 else if (TREE_USED (newdecl))
2919 TREE_USED (olddecl) = 1;
2921 if (VAR_P (newdecl))
2923 if (DECL_READ_P (olddecl))
2924 DECL_READ_P (newdecl) = 1;
2925 else if (DECL_READ_P (newdecl))
2926 DECL_READ_P (olddecl) = 1;
2929 if (DECL_PRESERVE_P (olddecl))
2930 DECL_PRESERVE_P (newdecl) = 1;
2931 else if (DECL_PRESERVE_P (newdecl))
2932 DECL_PRESERVE_P (olddecl) = 1;
2934 /* Merge the DECL_FUNCTION_VERSIONED information. newdecl will be copied
2935 to olddecl and deleted. */
2936 if (TREE_CODE (newdecl) == FUNCTION_DECL
2937 && DECL_FUNCTION_VERSIONED (olddecl))
2939 /* Set the flag for newdecl so that it gets copied to olddecl. */
2940 DECL_FUNCTION_VERSIONED (newdecl) = 1;
2941 /* newdecl will be purged after copying to olddecl and is no longer
2942 a version. */
2943 cgraph_node::delete_function_version_by_decl (newdecl);
2946 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2948 int function_size;
2949 struct symtab_node *snode = symtab_node::get (olddecl);
2951 function_size = sizeof (struct tree_decl_common);
2953 memcpy ((char *) olddecl + sizeof (struct tree_common),
2954 (char *) newdecl + sizeof (struct tree_common),
2955 function_size - sizeof (struct tree_common));
2957 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2958 (char *) newdecl + sizeof (struct tree_decl_common),
2959 sizeof (struct tree_function_decl) - sizeof (struct tree_decl_common));
2961 /* Preserve symtab node mapping. */
2962 olddecl->decl_with_vis.symtab_node = snode;
2964 if (new_template_info)
2965 /* If newdecl is a template instantiation, it is possible that
2966 the following sequence of events has occurred:
2968 o A friend function was declared in a class template. The
2969 class template was instantiated.
2971 o The instantiation of the friend declaration was
2972 recorded on the instantiation list, and is newdecl.
2974 o Later, however, instantiate_class_template called pushdecl
2975 on the newdecl to perform name injection. But, pushdecl in
2976 turn called duplicate_decls when it discovered that another
2977 declaration of a global function with the same name already
2978 existed.
2980 o Here, in duplicate_decls, we decided to clobber newdecl.
2982 If we're going to do that, we'd better make sure that
2983 olddecl, and not newdecl, is on the list of
2984 instantiations so that if we try to do the instantiation
2985 again we won't get the clobbered declaration. */
2986 reregister_specialization (newdecl,
2987 new_template_info,
2988 olddecl);
2990 else
2992 size_t size = tree_code_size (TREE_CODE (newdecl));
2994 memcpy ((char *) olddecl + sizeof (struct tree_common),
2995 (char *) newdecl + sizeof (struct tree_common),
2996 sizeof (struct tree_decl_common) - sizeof (struct tree_common));
2998 switch (TREE_CODE (newdecl))
3000 case LABEL_DECL:
3001 case VAR_DECL:
3002 case RESULT_DECL:
3003 case PARM_DECL:
3004 case FIELD_DECL:
3005 case TYPE_DECL:
3006 case CONST_DECL:
3008 struct symtab_node *snode = NULL;
3010 if (VAR_P (newdecl)
3011 && (TREE_STATIC (olddecl) || TREE_PUBLIC (olddecl)
3012 || DECL_EXTERNAL (olddecl)))
3013 snode = symtab_node::get (olddecl);
3014 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3015 (char *) newdecl + sizeof (struct tree_decl_common),
3016 size - sizeof (struct tree_decl_common)
3017 + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
3018 if (VAR_P (newdecl))
3019 olddecl->decl_with_vis.symtab_node = snode;
3021 break;
3022 default:
3023 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3024 (char *) newdecl + sizeof (struct tree_decl_common),
3025 sizeof (struct tree_decl_non_common) - sizeof (struct tree_decl_common)
3026 + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
3027 break;
3031 if (VAR_OR_FUNCTION_DECL_P (newdecl))
3033 if (DECL_EXTERNAL (olddecl)
3034 || TREE_PUBLIC (olddecl)
3035 || TREE_STATIC (olddecl))
3037 /* Merge the section attribute.
3038 We want to issue an error if the sections conflict but that must be
3039 done later in decl_attributes since we are called before attributes
3040 are assigned. */
3041 if (DECL_SECTION_NAME (newdecl) != NULL)
3042 set_decl_section_name (olddecl, newdecl);
3044 if (DECL_ONE_ONLY (newdecl))
3046 struct symtab_node *oldsym, *newsym;
3047 if (TREE_CODE (olddecl) == FUNCTION_DECL)
3048 oldsym = cgraph_node::get_create (olddecl);
3049 else
3050 oldsym = varpool_node::get_create (olddecl);
3051 newsym = symtab_node::get (newdecl);
3052 oldsym->set_comdat_group (newsym->get_comdat_group ());
3056 if (VAR_P (newdecl)
3057 && CP_DECL_THREAD_LOCAL_P (newdecl))
3059 CP_DECL_THREAD_LOCAL_P (olddecl) = true;
3060 if (!processing_template_decl)
3061 set_decl_tls_model (olddecl, DECL_TLS_MODEL (newdecl));
3065 DECL_UID (olddecl) = olddecl_uid;
3067 /* NEWDECL contains the merged attribute lists.
3068 Update OLDDECL to be the same. */
3069 DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
3071 /* If OLDDECL had its DECL_RTL instantiated, re-invoke make_decl_rtl
3072 so that encode_section_info has a chance to look at the new decl
3073 flags and attributes. */
3074 if (DECL_RTL_SET_P (olddecl)
3075 && (TREE_CODE (olddecl) == FUNCTION_DECL
3076 || (VAR_P (olddecl)
3077 && TREE_STATIC (olddecl))))
3078 make_decl_rtl (olddecl);
3080 /* The NEWDECL will no longer be needed. Because every out-of-class
3081 declaration of a member results in a call to duplicate_decls,
3082 freeing these nodes represents in a significant savings.
3084 Before releasing the node, be sore to remove function from symbol
3085 table that might have been inserted there to record comdat group.
3086 Be sure to however do not free DECL_STRUCT_FUNCTION because this
3087 structure is shared in between newdecl and oldecl. */
3088 if (TREE_CODE (newdecl) == FUNCTION_DECL)
3089 DECL_STRUCT_FUNCTION (newdecl) = NULL;
3090 if (VAR_OR_FUNCTION_DECL_P (newdecl))
3092 struct symtab_node *snode = symtab_node::get (newdecl);
3093 if (snode)
3094 snode->remove ();
3097 if (TREE_CODE (olddecl) == FUNCTION_DECL)
3099 tree clone;
3100 FOR_EACH_CLONE (clone, olddecl)
3102 DECL_ATTRIBUTES (clone) = DECL_ATTRIBUTES (olddecl);
3103 DECL_PRESERVE_P (clone) |= DECL_PRESERVE_P (olddecl);
3107 /* Remove the associated constraints for newdecl, if any, before
3108 reclaiming memory. */
3109 if (flag_concepts)
3110 remove_constraints (newdecl);
3112 ggc_free (newdecl);
3114 return olddecl;
3117 /* Return zero if the declaration NEWDECL is valid
3118 when the declaration OLDDECL (assumed to be for the same name)
3119 has already been seen.
3120 Otherwise return an error message format string with a %s
3121 where the identifier should go. */
3123 static const char *
3124 redeclaration_error_message (tree newdecl, tree olddecl)
3126 if (TREE_CODE (newdecl) == TYPE_DECL)
3128 /* Because C++ can put things into name space for free,
3129 constructs like "typedef struct foo { ... } foo"
3130 would look like an erroneous redeclaration. */
3131 if (same_type_p (TREE_TYPE (newdecl), TREE_TYPE (olddecl)))
3132 return NULL;
3133 else
3134 return G_("redefinition of %q#D");
3136 else if (TREE_CODE (newdecl) == FUNCTION_DECL)
3138 /* If this is a pure function, its olddecl will actually be
3139 the original initialization to `0' (which we force to call
3140 abort()). Don't complain about redefinition in this case. */
3141 if (DECL_LANG_SPECIFIC (olddecl) && DECL_PURE_VIRTUAL_P (olddecl)
3142 && DECL_INITIAL (olddecl) == NULL_TREE)
3143 return NULL;
3145 /* If both functions come from different namespaces, this is not
3146 a redeclaration - this is a conflict with a used function. */
3147 if (DECL_NAMESPACE_SCOPE_P (olddecl)
3148 && DECL_CONTEXT (olddecl) != DECL_CONTEXT (newdecl)
3149 && ! decls_match (olddecl, newdecl))
3150 return G_("%qD conflicts with used function");
3152 /* We'll complain about linkage mismatches in
3153 warn_extern_redeclared_static. */
3155 /* Defining the same name twice is no good. */
3156 if (decl_defined_p (olddecl)
3157 && decl_defined_p (newdecl))
3159 if (DECL_NAME (olddecl) == NULL_TREE)
3160 return G_("%q#D not declared in class");
3161 else if (!GNU_INLINE_P (olddecl)
3162 || GNU_INLINE_P (newdecl))
3163 return G_("redefinition of %q#D");
3166 if (DECL_DECLARED_INLINE_P (olddecl) && DECL_DECLARED_INLINE_P (newdecl))
3168 bool olda = GNU_INLINE_P (olddecl);
3169 bool newa = GNU_INLINE_P (newdecl);
3171 if (olda != newa)
3173 if (newa)
3174 return G_("%q+D redeclared inline with "
3175 "%<gnu_inline%> attribute");
3176 else
3177 return G_("%q+D redeclared inline without "
3178 "%<gnu_inline%> attribute");
3182 if (deduction_guide_p (olddecl)
3183 && deduction_guide_p (newdecl))
3184 return G_("deduction guide %q+D redeclared");
3186 /* [class.compare.default]: A definition of a comparison operator as
3187 defaulted that appears in a class shall be the first declaration of
3188 that function. */
3189 special_function_kind sfk = special_function_p (olddecl);
3190 if (sfk == sfk_comparison && DECL_DEFAULTED_FN (newdecl))
3191 return G_("comparison operator %q+D defaulted after "
3192 "its first declaration");
3194 check_abi_tag_redeclaration
3195 (olddecl, lookup_attribute ("abi_tag", DECL_ATTRIBUTES (olddecl)),
3196 lookup_attribute ("abi_tag", DECL_ATTRIBUTES (newdecl)));
3198 return NULL;
3200 else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
3202 tree nt, ot;
3204 if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == CONCEPT_DECL)
3205 return G_("redefinition of %q#D");
3207 if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) != FUNCTION_DECL)
3208 return redeclaration_error_message (DECL_TEMPLATE_RESULT (newdecl),
3209 DECL_TEMPLATE_RESULT (olddecl));
3211 if (DECL_TEMPLATE_RESULT (newdecl) == DECL_TEMPLATE_RESULT (olddecl))
3212 return NULL;
3214 nt = DECL_TEMPLATE_RESULT (newdecl);
3215 if (DECL_TEMPLATE_INFO (nt))
3216 nt = DECL_TEMPLATE_RESULT (template_for_substitution (nt));
3217 ot = DECL_TEMPLATE_RESULT (olddecl);
3218 if (DECL_TEMPLATE_INFO (ot))
3219 ot = DECL_TEMPLATE_RESULT (template_for_substitution (ot));
3220 if (DECL_INITIAL (nt) && DECL_INITIAL (ot)
3221 && (!GNU_INLINE_P (ot) || GNU_INLINE_P (nt)))
3222 return G_("redefinition of %q#D");
3224 if (DECL_DECLARED_INLINE_P (ot) && DECL_DECLARED_INLINE_P (nt))
3226 bool olda = GNU_INLINE_P (ot);
3227 bool newa = GNU_INLINE_P (nt);
3229 if (olda != newa)
3231 if (newa)
3232 return G_("%q+D redeclared inline with "
3233 "%<gnu_inline%> attribute");
3234 else
3235 return G_("%q+D redeclared inline without "
3236 "%<gnu_inline%> attribute");
3240 if (deduction_guide_p (olddecl)
3241 && deduction_guide_p (newdecl))
3242 return G_("deduction guide %q+D redeclared");
3244 /* Core issue #226 (C++11):
3246 If a friend function template declaration specifies a
3247 default template-argument, that declaration shall be a
3248 definition and shall be the only declaration of the
3249 function template in the translation unit. */
3250 if ((cxx_dialect != cxx98)
3251 && TREE_CODE (ot) == FUNCTION_DECL && DECL_UNIQUE_FRIEND_P (ot)
3252 && !check_default_tmpl_args (nt, DECL_TEMPLATE_PARMS (newdecl),
3253 /*is_primary=*/true,
3254 /*is_partial=*/false,
3255 /*is_friend_decl=*/2))
3256 return G_("redeclaration of friend %q#D "
3257 "may not have default template arguments");
3259 return NULL;
3261 else if (VAR_P (newdecl)
3262 && (CP_DECL_THREAD_LOCAL_P (newdecl)
3263 != CP_DECL_THREAD_LOCAL_P (olddecl))
3264 && (! DECL_LANG_SPECIFIC (olddecl)
3265 || ! CP_DECL_THREADPRIVATE_P (olddecl)
3266 || CP_DECL_THREAD_LOCAL_P (newdecl)))
3268 /* Only variables can be thread-local, and all declarations must
3269 agree on this property. */
3270 if (CP_DECL_THREAD_LOCAL_P (newdecl))
3271 return G_("thread-local declaration of %q#D follows "
3272 "non-thread-local declaration");
3273 else
3274 return G_("non-thread-local declaration of %q#D follows "
3275 "thread-local declaration");
3277 else if (toplevel_bindings_p () || DECL_NAMESPACE_SCOPE_P (newdecl))
3279 /* The objects have been declared at namespace scope. If either
3280 is a member of an anonymous union, then this is an invalid
3281 redeclaration. For example:
3283 int i;
3284 union { int i; };
3286 is invalid. */
3287 if ((VAR_P (newdecl) && DECL_ANON_UNION_VAR_P (newdecl))
3288 || (VAR_P (olddecl) && DECL_ANON_UNION_VAR_P (olddecl)))
3289 return G_("redeclaration of %q#D");
3290 /* If at least one declaration is a reference, there is no
3291 conflict. For example:
3293 int i = 3;
3294 extern int i;
3296 is valid. */
3297 if (DECL_EXTERNAL (newdecl) || DECL_EXTERNAL (olddecl))
3298 return NULL;
3300 /* Static data member declared outside a class definition
3301 if the variable is defined within the class with constexpr
3302 specifier is declaration rather than definition (and
3303 deprecated). */
3304 if (cxx_dialect >= cxx17
3305 && VAR_P (olddecl)
3306 && DECL_CLASS_SCOPE_P (olddecl)
3307 && DECL_DECLARED_CONSTEXPR_P (olddecl)
3308 && !DECL_INITIAL (newdecl))
3310 DECL_EXTERNAL (newdecl) = 1;
3311 /* For now, only warn with explicit -Wdeprecated. */
3312 if (OPTION_SET_P (warn_deprecated))
3314 auto_diagnostic_group d;
3315 if (warning_at (DECL_SOURCE_LOCATION (newdecl), OPT_Wdeprecated,
3316 "redundant redeclaration of %<constexpr%> "
3317 "static data member %qD", newdecl))
3318 inform (DECL_SOURCE_LOCATION (olddecl),
3319 "previous declaration of %qD", olddecl);
3321 return NULL;
3324 /* Reject two definitions. */
3325 return G_("redefinition of %q#D");
3327 else
3329 /* Objects declared with block scope: */
3330 /* Reject two definitions, and reject a definition
3331 together with an external reference. */
3332 if (!(DECL_EXTERNAL (newdecl) && DECL_EXTERNAL (olddecl)))
3333 return G_("redeclaration of %q#D");
3334 return NULL;
3339 /* Hash and equality functions for the named_label table. */
3341 hashval_t
3342 named_label_hash::hash (const value_type entry)
3344 return IDENTIFIER_HASH_VALUE (entry->name);
3347 bool
3348 named_label_hash::equal (const value_type entry, compare_type name)
3350 return name == entry->name;
3353 /* Look for a label named ID in the current function. If one cannot
3354 be found, create one. Return the named_label_entry, or NULL on
3355 failure. */
3357 static named_label_entry *
3358 lookup_label_1 (tree id, bool making_local_p)
3360 auto_cond_timevar tv (TV_NAME_LOOKUP);
3362 /* You can't use labels at global scope. */
3363 if (current_function_decl == NULL_TREE)
3365 error ("label %qE referenced outside of any function", id);
3366 return NULL;
3369 if (!named_labels)
3370 named_labels = hash_table<named_label_hash>::create_ggc (13);
3372 hashval_t hash = IDENTIFIER_HASH_VALUE (id);
3373 named_label_entry **slot
3374 = named_labels->find_slot_with_hash (id, hash, INSERT);
3375 named_label_entry *old = *slot;
3377 if (old && old->label_decl)
3379 if (!making_local_p)
3380 return old;
3382 if (old->binding_level == current_binding_level)
3384 error ("local label %qE conflicts with existing label", id);
3385 inform (DECL_SOURCE_LOCATION (old->label_decl), "previous label");
3386 return NULL;
3390 /* We are making a new decl, create or reuse the named_label_entry */
3391 named_label_entry *ent = NULL;
3392 if (old && !old->label_decl)
3393 ent = old;
3394 else
3396 ent = ggc_cleared_alloc<named_label_entry> ();
3397 ent->name = id;
3398 ent->outer = old;
3399 *slot = ent;
3402 /* Now create the LABEL_DECL. */
3403 tree decl = build_decl (input_location, LABEL_DECL, id, void_type_node);
3405 DECL_CONTEXT (decl) = current_function_decl;
3406 SET_DECL_MODE (decl, VOIDmode);
3407 if (making_local_p)
3409 C_DECLARED_LABEL_FLAG (decl) = true;
3410 DECL_CHAIN (decl) = current_binding_level->names;
3411 current_binding_level->names = decl;
3414 ent->label_decl = decl;
3416 return ent;
3419 /* Wrapper for lookup_label_1. */
3421 tree
3422 lookup_label (tree id)
3424 named_label_entry *ent = lookup_label_1 (id, false);
3425 return ent ? ent->label_decl : NULL_TREE;
3428 tree
3429 declare_local_label (tree id)
3431 named_label_entry *ent = lookup_label_1 (id, true);
3432 return ent ? ent->label_decl : NULL_TREE;
3435 /* Returns nonzero if it is ill-formed to jump past the declaration of
3436 DECL. Returns 2 if it's also a real problem. */
3438 static int
3439 decl_jump_unsafe (tree decl)
3441 /* [stmt.dcl]/3: A program that jumps from a point where a local variable
3442 with automatic storage duration is not in scope to a point where it is
3443 in scope is ill-formed unless the variable has scalar type, class type
3444 with a trivial default constructor and a trivial destructor, a
3445 cv-qualified version of one of these types, or an array of one of the
3446 preceding types and is declared without an initializer (8.5). */
3447 tree type = TREE_TYPE (decl);
3449 if (!VAR_P (decl) || TREE_STATIC (decl)
3450 || type == error_mark_node)
3451 return 0;
3453 if (DECL_NONTRIVIALLY_INITIALIZED_P (decl)
3454 || variably_modified_type_p (type, NULL_TREE))
3455 return 2;
3457 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
3458 return 1;
3460 return 0;
3463 /* A subroutine of check_previous_goto_1 and check_goto to identify a branch
3464 to the user. */
3466 static bool
3467 identify_goto (tree decl, location_t loc, const location_t *locus,
3468 diagnostic_t diag_kind)
3470 bool complained
3471 = emit_diagnostic (diag_kind, loc, 0,
3472 decl ? N_("jump to label %qD")
3473 : N_("jump to case label"), decl);
3474 if (complained && locus)
3475 inform (*locus, " from here");
3476 return complained;
3479 /* Check that a single previously seen jump to a newly defined label
3480 is OK. DECL is the LABEL_DECL or 0; LEVEL is the binding_level for
3481 the jump context; NAMES are the names in scope in LEVEL at the jump
3482 context; LOCUS is the source position of the jump or 0. Returns
3483 true if all is well. */
3485 static bool
3486 check_previous_goto_1 (tree decl, cp_binding_level* level, tree names,
3487 bool exited_omp, const location_t *locus)
3489 cp_binding_level *b;
3490 bool complained = false;
3491 int identified = 0;
3492 bool saw_eh = false, saw_omp = false, saw_tm = false, saw_cxif = false;
3493 bool saw_ceif = false;
3495 if (exited_omp)
3497 complained = identify_goto (decl, input_location, locus, DK_ERROR);
3498 if (complained)
3499 inform (input_location, " exits OpenMP structured block");
3500 saw_omp = true;
3501 identified = 2;
3504 for (b = current_binding_level; b ; b = b->level_chain)
3506 tree new_decls, old_decls = (b == level ? names : NULL_TREE);
3508 for (new_decls = b->names; new_decls != old_decls;
3509 new_decls = (DECL_P (new_decls) ? DECL_CHAIN (new_decls)
3510 : TREE_CHAIN (new_decls)))
3512 int problem = decl_jump_unsafe (new_decls);
3513 if (! problem)
3514 continue;
3516 if (!identified)
3518 complained = identify_goto (decl, input_location, locus,
3519 problem > 1
3520 ? DK_ERROR : DK_PERMERROR);
3521 identified = 1;
3523 if (complained)
3525 if (problem > 1)
3526 inform (DECL_SOURCE_LOCATION (new_decls),
3527 " crosses initialization of %q#D", new_decls);
3528 else
3529 inform (DECL_SOURCE_LOCATION (new_decls),
3530 " enters scope of %q#D, which has "
3531 "non-trivial destructor", new_decls);
3535 if (b == level)
3536 break;
3538 const char *inf = NULL;
3539 location_t loc = input_location;
3540 switch (b->kind)
3542 case sk_try:
3543 if (!saw_eh)
3544 inf = G_(" enters %<try%> block");
3545 saw_eh = true;
3546 break;
3548 case sk_catch:
3549 if (!saw_eh)
3550 inf = G_(" enters %<catch%> block");
3551 saw_eh = true;
3552 break;
3554 case sk_omp:
3555 if (!saw_omp)
3556 inf = G_(" enters OpenMP structured block");
3557 saw_omp = true;
3558 break;
3560 case sk_transaction:
3561 if (!saw_tm)
3562 inf = G_(" enters synchronized or atomic statement");
3563 saw_tm = true;
3564 break;
3566 case sk_block:
3567 if (!saw_cxif && level_for_constexpr_if (b->level_chain))
3569 inf = G_(" enters %<constexpr if%> statement");
3570 loc = EXPR_LOCATION (b->level_chain->this_entity);
3571 saw_cxif = true;
3573 else if (!saw_ceif && level_for_consteval_if (b->level_chain))
3575 inf = G_(" enters %<consteval if%> statement");
3576 loc = EXPR_LOCATION (b->level_chain->this_entity);
3577 saw_ceif = true;
3579 break;
3581 default:
3582 break;
3585 if (inf)
3587 if (identified < 2)
3588 complained = identify_goto (decl, input_location, locus, DK_ERROR);
3589 identified = 2;
3590 if (complained)
3591 inform (loc, inf);
3595 return !identified;
3598 static void
3599 check_previous_goto (tree decl, struct named_label_use_entry *use)
3601 check_previous_goto_1 (decl, use->binding_level,
3602 use->names_in_scope, use->in_omp_scope,
3603 &use->o_goto_locus);
3606 static bool
3607 check_switch_goto (cp_binding_level* level)
3609 return check_previous_goto_1 (NULL_TREE, level, level->names, false, NULL);
3612 /* Check that a new jump to a label DECL is OK. Called by
3613 finish_goto_stmt. */
3615 void
3616 check_goto (tree decl)
3618 /* We can't know where a computed goto is jumping.
3619 So we assume that it's OK. */
3620 if (TREE_CODE (decl) != LABEL_DECL)
3621 return;
3623 hashval_t hash = IDENTIFIER_HASH_VALUE (DECL_NAME (decl));
3624 named_label_entry **slot
3625 = named_labels->find_slot_with_hash (DECL_NAME (decl), hash, NO_INSERT);
3626 named_label_entry *ent = *slot;
3628 /* If the label hasn't been defined yet, defer checking. */
3629 if (! DECL_INITIAL (decl))
3631 /* Don't bother creating another use if the last goto had the
3632 same data, and will therefore create the same set of errors. */
3633 if (ent->uses
3634 && ent->uses->names_in_scope == current_binding_level->names)
3635 return;
3637 named_label_use_entry *new_use
3638 = ggc_alloc<named_label_use_entry> ();
3639 new_use->binding_level = current_binding_level;
3640 new_use->names_in_scope = current_binding_level->names;
3641 new_use->o_goto_locus = input_location;
3642 new_use->in_omp_scope = false;
3644 new_use->next = ent->uses;
3645 ent->uses = new_use;
3646 return;
3649 bool saw_catch = false, complained = false;
3650 int identified = 0;
3651 tree bad;
3652 unsigned ix;
3654 if (ent->in_try_scope || ent->in_catch_scope || ent->in_transaction_scope
3655 || ent->in_constexpr_if || ent->in_consteval_if
3656 || ent->in_omp_scope || !vec_safe_is_empty (ent->bad_decls))
3658 diagnostic_t diag_kind = DK_PERMERROR;
3659 if (ent->in_try_scope || ent->in_catch_scope || ent->in_constexpr_if
3660 || ent->in_consteval_if || ent->in_transaction_scope
3661 || ent->in_omp_scope)
3662 diag_kind = DK_ERROR;
3663 complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3664 &input_location, diag_kind);
3665 identified = 1 + (diag_kind == DK_ERROR);
3668 FOR_EACH_VEC_SAFE_ELT (ent->bad_decls, ix, bad)
3670 int u = decl_jump_unsafe (bad);
3672 if (u > 1 && DECL_ARTIFICIAL (bad))
3674 /* Can't skip init of __exception_info. */
3675 if (identified == 1)
3677 complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3678 &input_location, DK_ERROR);
3679 identified = 2;
3681 if (complained)
3682 inform (DECL_SOURCE_LOCATION (bad), " enters %<catch%> block");
3683 saw_catch = true;
3685 else if (complained)
3687 if (u > 1)
3688 inform (DECL_SOURCE_LOCATION (bad),
3689 " skips initialization of %q#D", bad);
3690 else
3691 inform (DECL_SOURCE_LOCATION (bad),
3692 " enters scope of %q#D which has "
3693 "non-trivial destructor", bad);
3697 if (complained)
3699 if (ent->in_try_scope)
3700 inform (input_location, " enters %<try%> block");
3701 else if (ent->in_catch_scope && !saw_catch)
3702 inform (input_location, " enters %<catch%> block");
3703 else if (ent->in_transaction_scope)
3704 inform (input_location, " enters synchronized or atomic statement");
3705 else if (ent->in_constexpr_if)
3706 inform (input_location, " enters %<constexpr if%> statement");
3707 else if (ent->in_consteval_if)
3708 inform (input_location, " enters %<consteval if%> statement");
3711 if (ent->in_omp_scope)
3713 if (complained)
3714 inform (input_location, " enters OpenMP structured block");
3716 else if (flag_openmp)
3717 for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3719 if (b == ent->binding_level)
3720 break;
3721 if (b->kind == sk_omp)
3723 if (identified < 2)
3725 complained = identify_goto (decl,
3726 DECL_SOURCE_LOCATION (decl),
3727 &input_location, DK_ERROR);
3728 identified = 2;
3730 if (complained)
3731 inform (input_location, " exits OpenMP structured block");
3732 break;
3737 /* Check that a return is ok wrt OpenMP structured blocks.
3738 Called by finish_return_stmt. Returns true if all is well. */
3740 bool
3741 check_omp_return (void)
3743 for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3744 if (b->kind == sk_omp)
3746 error ("invalid exit from OpenMP structured block");
3747 return false;
3749 else if (b->kind == sk_function_parms)
3750 break;
3751 return true;
3754 /* Define a label, specifying the location in the source file.
3755 Return the LABEL_DECL node for the label. */
3757 tree
3758 define_label (location_t location, tree name)
3760 auto_cond_timevar tv (TV_NAME_LOOKUP);
3762 /* After labels, make any new cleanups in the function go into their
3763 own new (temporary) binding contour. */
3764 for (cp_binding_level *p = current_binding_level;
3765 p->kind != sk_function_parms;
3766 p = p->level_chain)
3767 p->more_cleanups_ok = 0;
3769 named_label_entry *ent = lookup_label_1 (name, false);
3770 tree decl = ent->label_decl;
3772 if (DECL_INITIAL (decl) != NULL_TREE)
3774 error ("duplicate label %qD", decl);
3775 return error_mark_node;
3777 else
3779 /* Mark label as having been defined. */
3780 DECL_INITIAL (decl) = error_mark_node;
3781 /* Say where in the source. */
3782 DECL_SOURCE_LOCATION (decl) = location;
3784 ent->binding_level = current_binding_level;
3785 ent->names_in_scope = current_binding_level->names;
3787 for (named_label_use_entry *use = ent->uses; use; use = use->next)
3788 check_previous_goto (decl, use);
3789 ent->uses = NULL;
3792 return decl;
3795 struct cp_switch
3797 cp_binding_level *level;
3798 struct cp_switch *next;
3799 /* The SWITCH_STMT being built. */
3800 tree switch_stmt;
3801 /* A splay-tree mapping the low element of a case range to the high
3802 element, or NULL_TREE if there is no high element. Used to
3803 determine whether or not a new case label duplicates an old case
3804 label. We need a tree, rather than simply a hash table, because
3805 of the GNU case range extension. */
3806 splay_tree cases;
3807 /* Remember whether a default: case label has been seen. */
3808 bool has_default_p;
3809 /* Remember whether a BREAK_STMT has been seen in this SWITCH_STMT. */
3810 bool break_stmt_seen_p;
3811 /* Set if inside of {FOR,DO,WHILE}_BODY nested inside of a switch,
3812 where BREAK_STMT doesn't belong to the SWITCH_STMT. */
3813 bool in_loop_body_p;
3816 /* A stack of the currently active switch statements. The innermost
3817 switch statement is on the top of the stack. There is no need to
3818 mark the stack for garbage collection because it is only active
3819 during the processing of the body of a function, and we never
3820 collect at that point. */
3822 static struct cp_switch *switch_stack;
3824 /* Called right after a switch-statement condition is parsed.
3825 SWITCH_STMT is the switch statement being parsed. */
3827 void
3828 push_switch (tree switch_stmt)
3830 struct cp_switch *p = XNEW (struct cp_switch);
3831 p->level = current_binding_level;
3832 p->next = switch_stack;
3833 p->switch_stmt = switch_stmt;
3834 p->cases = splay_tree_new (case_compare, NULL, NULL);
3835 p->has_default_p = false;
3836 p->break_stmt_seen_p = false;
3837 p->in_loop_body_p = false;
3838 switch_stack = p;
3841 void
3842 pop_switch (void)
3844 struct cp_switch *cs = switch_stack;
3846 /* Emit warnings as needed. */
3847 location_t switch_location = cp_expr_loc_or_input_loc (cs->switch_stmt);
3848 tree cond = SWITCH_STMT_COND (cs->switch_stmt);
3849 const bool bool_cond_p
3850 = (SWITCH_STMT_TYPE (cs->switch_stmt)
3851 && TREE_CODE (SWITCH_STMT_TYPE (cs->switch_stmt)) == BOOLEAN_TYPE);
3852 if (!processing_template_decl)
3853 c_do_switch_warnings (cs->cases, switch_location,
3854 SWITCH_STMT_TYPE (cs->switch_stmt), cond,
3855 bool_cond_p);
3857 /* For the benefit of block_may_fallthru remember if the switch body
3858 case labels cover all possible values and if there are break; stmts. */
3859 if (cs->has_default_p
3860 || (!processing_template_decl
3861 && c_switch_covers_all_cases_p (cs->cases,
3862 SWITCH_STMT_TYPE (cs->switch_stmt))))
3863 SWITCH_STMT_ALL_CASES_P (cs->switch_stmt) = 1;
3864 if (!cs->break_stmt_seen_p)
3865 SWITCH_STMT_NO_BREAK_P (cs->switch_stmt) = 1;
3866 /* Now that we're done with the switch warnings, set the switch type
3867 to the type of the condition if the index type was of scoped enum type.
3868 (Such types don't participate in the integer promotions.) We do this
3869 because of bit-fields whose declared type is a scoped enum type:
3870 gimplification will use the lowered index type, but convert the
3871 case values to SWITCH_STMT_TYPE, which would have been the declared type
3872 and verify_gimple_switch doesn't accept that. */
3873 if (is_bitfield_expr_with_lowered_type (cond))
3874 SWITCH_STMT_TYPE (cs->switch_stmt) = TREE_TYPE (cond);
3875 gcc_assert (!cs->in_loop_body_p);
3876 splay_tree_delete (cs->cases);
3877 switch_stack = switch_stack->next;
3878 free (cs);
3881 /* Note that a BREAK_STMT is about to be added. If it is inside of
3882 a SWITCH_STMT and not inside of a loop body inside of it, note
3883 in switch_stack we've seen a BREAK_STMT. */
3885 void
3886 note_break_stmt (void)
3888 if (switch_stack && !switch_stack->in_loop_body_p)
3889 switch_stack->break_stmt_seen_p = true;
3892 /* Note the start of processing of an iteration statement's body.
3893 The note_break_stmt function will do nothing while processing it.
3894 Return a flag that should be passed to note_iteration_stmt_body_end. */
3896 bool
3897 note_iteration_stmt_body_start (void)
3899 if (!switch_stack)
3900 return false;
3901 bool ret = switch_stack->in_loop_body_p;
3902 switch_stack->in_loop_body_p = true;
3903 return ret;
3906 /* Note the end of processing of an iteration statement's body. */
3908 void
3909 note_iteration_stmt_body_end (bool prev)
3911 if (switch_stack)
3912 switch_stack->in_loop_body_p = prev;
3915 /* Convert a case constant VALUE in a switch to the type TYPE of the switch
3916 condition. Note that if TYPE and VALUE are already integral we don't
3917 really do the conversion because the language-independent
3918 warning/optimization code will work better that way. */
3920 static tree
3921 case_conversion (tree type, tree value)
3923 if (value == NULL_TREE)
3924 return value;
3926 value = mark_rvalue_use (value);
3928 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3929 type = type_promotes_to (type);
3931 tree ovalue = value;
3932 /* The constant-expression VALUE shall be a converted constant expression
3933 of the adjusted type of the switch condition, which doesn't allow
3934 narrowing conversions. */
3935 value = build_converted_constant_expr (type, value, tf_warning_or_error);
3937 if (cxx_dialect >= cxx11
3938 && (SCOPED_ENUM_P (type)
3939 || !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ovalue))))
3940 /* Use the converted value. */;
3941 else
3942 /* The already integral case. */
3943 value = ovalue;
3945 return cxx_constant_value (value);
3948 /* Note that we've seen a definition of a case label, and complain if this
3949 is a bad place for one. */
3951 tree
3952 finish_case_label (location_t loc, tree low_value, tree high_value)
3954 tree cond, r;
3955 cp_binding_level *p;
3956 tree type;
3958 if (low_value == NULL_TREE && high_value == NULL_TREE)
3959 switch_stack->has_default_p = true;
3961 if (processing_template_decl)
3963 tree label;
3965 /* For templates, just add the case label; we'll do semantic
3966 analysis at instantiation-time. */
3967 label = build_decl (loc, LABEL_DECL, NULL_TREE, void_type_node);
3968 return add_stmt (build_case_label (low_value, high_value, label));
3971 /* Find the condition on which this switch statement depends. */
3972 cond = SWITCH_STMT_COND (switch_stack->switch_stmt);
3973 if (cond && TREE_CODE (cond) == TREE_LIST)
3974 cond = TREE_VALUE (cond);
3976 if (!check_switch_goto (switch_stack->level))
3977 return error_mark_node;
3979 type = SWITCH_STMT_TYPE (switch_stack->switch_stmt);
3980 if (type == error_mark_node)
3981 return error_mark_node;
3983 low_value = case_conversion (type, low_value);
3984 high_value = case_conversion (type, high_value);
3986 r = c_add_case_label (loc, switch_stack->cases, cond, low_value, high_value);
3988 /* After labels, make any new cleanups in the function go into their
3989 own new (temporary) binding contour. */
3990 for (p = current_binding_level;
3991 p->kind != sk_function_parms;
3992 p = p->level_chain)
3993 p->more_cleanups_ok = 0;
3995 return r;
3998 struct typename_info {
3999 tree scope;
4000 tree name;
4001 tree template_id;
4002 bool enum_p;
4003 bool class_p;
4006 struct typename_hasher : ggc_ptr_hash<tree_node>
4008 typedef typename_info *compare_type;
4010 /* Hash a TYPENAME_TYPE. */
4012 static hashval_t
4013 hash (tree t)
4015 hashval_t hash;
4017 hash = (htab_hash_pointer (TYPE_CONTEXT (t))
4018 ^ htab_hash_pointer (TYPE_IDENTIFIER (t)));
4020 return hash;
4023 /* Compare two TYPENAME_TYPEs. */
4025 static bool
4026 equal (tree t1, const typename_info *t2)
4028 return (TYPE_IDENTIFIER (t1) == t2->name
4029 && TYPE_CONTEXT (t1) == t2->scope
4030 && TYPENAME_TYPE_FULLNAME (t1) == t2->template_id
4031 && TYPENAME_IS_ENUM_P (t1) == t2->enum_p
4032 && TYPENAME_IS_CLASS_P (t1) == t2->class_p);
4036 /* Build a TYPENAME_TYPE. If the type is `typename T::t', CONTEXT is
4037 the type of `T', NAME is the IDENTIFIER_NODE for `t'.
4039 Returns the new TYPENAME_TYPE. */
4041 static GTY (()) hash_table<typename_hasher> *typename_htab;
4043 tree
4044 build_typename_type (tree context, tree name, tree fullname,
4045 enum tag_types tag_type)
4047 typename_info ti;
4049 if (typename_htab == NULL)
4050 typename_htab = hash_table<typename_hasher>::create_ggc (61);
4052 ti.scope = FROB_CONTEXT (context);
4053 ti.name = name;
4054 ti.template_id = fullname;
4055 ti.enum_p = tag_type == enum_type;
4056 ti.class_p = (tag_type == class_type
4057 || tag_type == record_type
4058 || tag_type == union_type);
4059 hashval_t hash = (htab_hash_pointer (ti.scope)
4060 ^ htab_hash_pointer (ti.name));
4062 /* See if we already have this type. */
4063 tree *e = typename_htab->find_slot_with_hash (&ti, hash, INSERT);
4064 tree t = *e;
4065 if (*e)
4066 t = *e;
4067 else
4069 /* Build the TYPENAME_TYPE. */
4070 t = cxx_make_type (TYPENAME_TYPE);
4071 TYPE_CONTEXT (t) = ti.scope;
4072 TYPENAME_TYPE_FULLNAME (t) = ti.template_id;
4073 TYPENAME_IS_ENUM_P (t) = ti.enum_p;
4074 TYPENAME_IS_CLASS_P (t) = ti.class_p;
4076 /* Build the corresponding TYPE_DECL. */
4077 tree d = build_decl (input_location, TYPE_DECL, name, t);
4078 TYPE_NAME (t) = d;
4079 TYPE_STUB_DECL (t) = d;
4080 DECL_CONTEXT (d) = ti.scope;
4081 DECL_ARTIFICIAL (d) = 1;
4083 /* Store it in the hash table. */
4084 *e = t;
4086 /* TYPENAME_TYPEs must always be compared structurally, because
4087 they may or may not resolve down to another type depending on
4088 the currently open classes. */
4089 SET_TYPE_STRUCTURAL_EQUALITY (t);
4092 return t;
4095 /* Resolve `typename CONTEXT::NAME'. TAG_TYPE indicates the tag
4096 provided to name the type. Returns an appropriate type, unless an
4097 error occurs, in which case error_mark_node is returned. If we
4098 locate a non-artificial TYPE_DECL and TF_KEEP_TYPE_DECL is set, we
4099 return that, rather than the _TYPE it corresponds to, in other
4100 cases we look through the type decl. If TF_ERROR is set, complain
4101 about errors, otherwise be quiet. */
4103 tree
4104 make_typename_type (tree context, tree name, enum tag_types tag_type,
4105 tsubst_flags_t complain)
4107 tree fullname;
4108 tree t;
4109 bool want_template;
4111 if (name == error_mark_node
4112 || context == NULL_TREE
4113 || context == error_mark_node)
4114 return error_mark_node;
4116 if (TYPE_P (name))
4118 if (!(TYPE_LANG_SPECIFIC (name)
4119 && (CLASSTYPE_IS_TEMPLATE (name)
4120 || CLASSTYPE_USE_TEMPLATE (name))))
4121 name = TYPE_IDENTIFIER (name);
4122 else
4123 /* Create a TEMPLATE_ID_EXPR for the type. */
4124 name = build_nt (TEMPLATE_ID_EXPR,
4125 CLASSTYPE_TI_TEMPLATE (name),
4126 CLASSTYPE_TI_ARGS (name));
4128 else if (TREE_CODE (name) == TYPE_DECL)
4129 name = DECL_NAME (name);
4131 fullname = name;
4133 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
4135 name = TREE_OPERAND (name, 0);
4136 if (DECL_TYPE_TEMPLATE_P (name))
4137 name = TREE_OPERAND (fullname, 0) = DECL_NAME (name);
4138 if (TREE_CODE (name) != IDENTIFIER_NODE)
4140 if (complain & tf_error)
4141 error ("%qD is not a type", name);
4142 return error_mark_node;
4145 if (TREE_CODE (name) == TEMPLATE_DECL)
4147 if (complain & tf_error)
4148 error ("%qD used without template arguments", name);
4149 return error_mark_node;
4151 else if (is_overloaded_fn (name))
4153 if (complain & tf_error)
4154 error ("%qD is a function, not a type", name);
4155 return error_mark_node;
4157 gcc_assert (identifier_p (name));
4158 gcc_assert (TYPE_P (context));
4160 if (TREE_CODE (context) == TYPE_PACK_EXPANSION)
4161 /* This can happen for C++17 variadic using (c++/88986). */;
4162 else if (!MAYBE_CLASS_TYPE_P (context))
4164 if (complain & tf_error)
4165 error ("%q#T is not a class", context);
4166 return error_mark_node;
4169 /* When the CONTEXT is a dependent type, NAME could refer to a
4170 dependent base class of CONTEXT. But look inside it anyway
4171 if CONTEXT is a currently open scope, in case it refers to a
4172 member of the current instantiation or a non-dependent base;
4173 lookup will stop when we hit a dependent base. */
4174 if (!dependent_scope_p (context))
4175 /* We should only set WANT_TYPE when we're a nested typename type.
4176 Then we can give better diagnostics if we find a non-type. */
4177 t = lookup_field (context, name, 2, /*want_type=*/true);
4178 else
4179 t = NULL_TREE;
4181 if ((!t || TREE_CODE (t) == TREE_LIST) && dependent_type_p (context))
4182 return build_typename_type (context, name, fullname, tag_type);
4184 want_template = TREE_CODE (fullname) == TEMPLATE_ID_EXPR;
4186 if (!t)
4188 if (complain & tf_error)
4190 if (!COMPLETE_TYPE_P (context))
4191 cxx_incomplete_type_error (NULL_TREE, context);
4192 else
4193 error (want_template ? G_("no class template named %q#T in %q#T")
4194 : G_("no type named %q#T in %q#T"), name, context);
4196 return error_mark_node;
4199 /* Pull out the template from an injected-class-name (or multiple). */
4200 if (want_template)
4201 t = maybe_get_template_decl_from_type_decl (t);
4203 if (TREE_CODE (t) == TREE_LIST)
4205 if (complain & tf_error)
4207 error ("lookup of %qT in %qT is ambiguous", name, context);
4208 print_candidates (t);
4210 return error_mark_node;
4213 if (want_template && !DECL_TYPE_TEMPLATE_P (t))
4215 if (complain & tf_error)
4216 error ("%<typename %T::%D%> names %q#T, which is not a class template",
4217 context, name, t);
4218 return error_mark_node;
4220 if (!want_template && TREE_CODE (t) != TYPE_DECL)
4222 if ((complain & tf_tst_ok) && cxx_dialect >= cxx17
4223 && DECL_TYPE_TEMPLATE_P (t))
4224 /* The caller permits this typename-specifier to name a template
4225 (because it appears in a CTAD-enabled context). */;
4226 else
4228 if (complain & tf_error)
4229 error ("%<typename %T::%D%> names %q#T, which is not a type",
4230 context, name, t);
4231 return error_mark_node;
4235 if (!check_accessibility_of_qualified_id (t, /*object_type=*/NULL_TREE,
4236 context, complain))
4237 return error_mark_node;
4239 if (!want_template && DECL_TYPE_TEMPLATE_P (t))
4240 return make_template_placeholder (t);
4242 if (want_template)
4244 t = lookup_template_class (t, TREE_OPERAND (fullname, 1),
4245 NULL_TREE, context,
4246 /*entering_scope=*/0,
4247 complain | tf_user);
4248 if (t == error_mark_node)
4249 return error_mark_node;
4250 t = TYPE_NAME (t);
4253 if (DECL_ARTIFICIAL (t) || !(complain & tf_keep_type_decl))
4254 t = TREE_TYPE (t);
4256 maybe_record_typedef_use (t);
4258 return t;
4261 /* Resolve `CONTEXT::template NAME'. Returns a TEMPLATE_DECL if the name
4262 can be resolved or an UNBOUND_CLASS_TEMPLATE, unless an error occurs,
4263 in which case error_mark_node is returned.
4265 If PARM_LIST is non-NULL, also make sure that the template parameter
4266 list of TEMPLATE_DECL matches.
4268 If COMPLAIN zero, don't complain about any errors that occur. */
4270 tree
4271 make_unbound_class_template (tree context, tree name, tree parm_list,
4272 tsubst_flags_t complain)
4274 if (TYPE_P (name))
4275 name = TYPE_IDENTIFIER (name);
4276 else if (DECL_P (name))
4277 name = DECL_NAME (name);
4278 gcc_assert (identifier_p (name));
4280 if (!dependent_type_p (context)
4281 || currently_open_class (context))
4283 tree tmpl = NULL_TREE;
4285 if (MAYBE_CLASS_TYPE_P (context))
4286 tmpl = lookup_field (context, name, 0, false);
4288 if (tmpl && TREE_CODE (tmpl) == TYPE_DECL)
4289 tmpl = maybe_get_template_decl_from_type_decl (tmpl);
4291 if (!tmpl || !DECL_TYPE_TEMPLATE_P (tmpl))
4293 if (complain & tf_error)
4294 error ("no class template named %q#T in %q#T", name, context);
4295 return error_mark_node;
4298 if (parm_list
4299 && !comp_template_parms (DECL_TEMPLATE_PARMS (tmpl), parm_list))
4301 if (complain & tf_error)
4303 error ("template parameters do not match template %qD", tmpl);
4304 inform (DECL_SOURCE_LOCATION (tmpl),
4305 "%qD declared here", tmpl);
4307 return error_mark_node;
4310 if (!perform_or_defer_access_check (TYPE_BINFO (context), tmpl, tmpl,
4311 complain))
4312 return error_mark_node;
4314 return tmpl;
4317 return make_unbound_class_template_raw (context, name, parm_list);
4320 /* Build an UNBOUND_CLASS_TEMPLATE. */
4322 tree
4323 make_unbound_class_template_raw (tree context, tree name, tree parm_list)
4325 /* Build the UNBOUND_CLASS_TEMPLATE. */
4326 tree t = cxx_make_type (UNBOUND_CLASS_TEMPLATE);
4327 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
4328 TREE_TYPE (t) = NULL_TREE;
4329 SET_TYPE_STRUCTURAL_EQUALITY (t);
4331 /* Build the corresponding TEMPLATE_DECL. */
4332 tree d = build_decl (input_location, TEMPLATE_DECL, name, t);
4333 TYPE_NAME (t) = d;
4334 TYPE_STUB_DECL (t) = d;
4335 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
4336 DECL_ARTIFICIAL (d) = 1;
4337 DECL_TEMPLATE_PARMS (d) = parm_list;
4339 return t;
4344 /* Push the declarations of builtin types into the global namespace.
4345 RID_INDEX is the index of the builtin type in the array
4346 RID_POINTERS. NAME is the name used when looking up the builtin
4347 type. TYPE is the _TYPE node for the builtin type.
4349 The calls to set_global_binding below should be
4350 eliminated. Built-in types should not be looked up name; their
4351 names are keywords that the parser can recognize. However, there
4352 is code in c-common.cc that uses identifier_global_value to look up
4353 built-in types by name. */
4355 void
4356 record_builtin_type (enum rid rid_index,
4357 const char* name,
4358 tree type)
4360 tree decl = NULL_TREE;
4362 if (name)
4364 tree tname = get_identifier (name);
4365 tree tdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, tname, type);
4366 DECL_ARTIFICIAL (tdecl) = 1;
4367 set_global_binding (tdecl);
4368 decl = tdecl;
4371 if ((int) rid_index < (int) RID_MAX)
4372 if (tree rname = ridpointers[(int) rid_index])
4373 if (!decl || DECL_NAME (decl) != rname)
4375 tree rdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, rname, type);
4376 DECL_ARTIFICIAL (rdecl) = 1;
4377 set_global_binding (rdecl);
4378 if (!decl)
4379 decl = rdecl;
4382 if (decl)
4384 if (!TYPE_NAME (type))
4385 TYPE_NAME (type) = decl;
4386 debug_hooks->type_decl (decl, 0);
4390 /* Push a type into the namespace so that the back ends ignore it. */
4392 static void
4393 record_unknown_type (tree type, const char* name)
4395 tree decl = pushdecl (build_decl (UNKNOWN_LOCATION,
4396 TYPE_DECL, get_identifier (name), type));
4397 /* Make sure the "unknown type" typedecl gets ignored for debug info. */
4398 DECL_IGNORED_P (decl) = 1;
4399 TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
4400 TYPE_SIZE (type) = TYPE_SIZE (void_type_node);
4401 SET_TYPE_ALIGN (type, 1);
4402 TYPE_USER_ALIGN (type) = 0;
4403 SET_TYPE_MODE (type, TYPE_MODE (void_type_node));
4406 /* Create all the predefined identifiers. */
4408 static void
4409 initialize_predefined_identifiers (void)
4411 struct predefined_identifier
4413 const char *name; /* Name. */
4414 tree *node; /* Node to store it in. */
4415 cp_identifier_kind kind; /* Kind of identifier. */
4418 /* A table of identifiers to create at startup. */
4419 static const predefined_identifier predefined_identifiers[] = {
4420 {"C++", &lang_name_cplusplus, cik_normal},
4421 {"C", &lang_name_c, cik_normal},
4422 /* Some of these names have a trailing space so that it is
4423 impossible for them to conflict with names written by users. */
4424 {"__ct ", &ctor_identifier, cik_ctor},
4425 {"__ct_base ", &base_ctor_identifier, cik_ctor},
4426 {"__ct_comp ", &complete_ctor_identifier, cik_ctor},
4427 {"__dt ", &dtor_identifier, cik_dtor},
4428 {"__dt_base ", &base_dtor_identifier, cik_dtor},
4429 {"__dt_comp ", &complete_dtor_identifier, cik_dtor},
4430 {"__dt_del ", &deleting_dtor_identifier, cik_dtor},
4431 {"__conv_op ", &conv_op_identifier, cik_conv_op},
4432 {"__in_chrg", &in_charge_identifier, cik_normal},
4433 {"__as_base ", &as_base_identifier, cik_normal},
4434 {"this", &this_identifier, cik_normal},
4435 {"__delta", &delta_identifier, cik_normal},
4436 {"__pfn", &pfn_identifier, cik_normal},
4437 {"_vptr", &vptr_identifier, cik_normal},
4438 {"__vtt_parm", &vtt_parm_identifier, cik_normal},
4439 {"::", &global_identifier, cik_normal},
4440 /* The demangler expects anonymous namespaces to be called
4441 something starting with '_GLOBAL__N_'. It no longer needs
4442 to be unique to the TU. */
4443 {"_GLOBAL__N_1", &anon_identifier, cik_normal},
4444 {"auto", &auto_identifier, cik_normal},
4445 {"decltype(auto)", &decltype_auto_identifier, cik_normal},
4446 {"initializer_list", &init_list_identifier, cik_normal},
4447 {"__for_range ", &for_range__identifier, cik_normal},
4448 {"__for_begin ", &for_begin__identifier, cik_normal},
4449 {"__for_end ", &for_end__identifier, cik_normal},
4450 {"__for_range", &for_range_identifier, cik_normal},
4451 {"__for_begin", &for_begin_identifier, cik_normal},
4452 {"__for_end", &for_end_identifier, cik_normal},
4453 {"abi_tag", &abi_tag_identifier, cik_normal},
4454 {"aligned", &aligned_identifier, cik_normal},
4455 {"begin", &begin_identifier, cik_normal},
4456 {"end", &end_identifier, cik_normal},
4457 {"get", &get__identifier, cik_normal},
4458 {"gnu", &gnu_identifier, cik_normal},
4459 {"tuple_element", &tuple_element_identifier, cik_normal},
4460 {"tuple_size", &tuple_size_identifier, cik_normal},
4461 {"type", &type_identifier, cik_normal},
4462 {"value", &value_identifier, cik_normal},
4463 {"_FUN", &fun_identifier, cik_normal},
4464 {"__closure", &closure_identifier, cik_normal},
4465 {"heap uninit", &heap_uninit_identifier, cik_normal},
4466 {"heap ", &heap_identifier, cik_normal},
4467 {"heap deleted", &heap_deleted_identifier, cik_normal},
4468 {"heap [] uninit", &heap_vec_uninit_identifier, cik_normal},
4469 {"heap []", &heap_vec_identifier, cik_normal},
4470 {"omp", &omp_identifier, cik_normal},
4471 {NULL, NULL, cik_normal}
4474 for (const predefined_identifier *pid = predefined_identifiers;
4475 pid->name; ++pid)
4477 *pid->node = get_identifier (pid->name);
4478 /* Some of these identifiers already have a special kind. */
4479 if (pid->kind != cik_normal)
4480 set_identifier_kind (*pid->node, pid->kind);
4484 /* Create the predefined scalar types of C,
4485 and some nodes representing standard constants (0, 1, (void *)0).
4486 Initialize the global binding level.
4487 Make definitions for built-in primitive functions. */
4489 void
4490 cxx_init_decl_processing (void)
4492 tree void_ftype;
4493 tree void_ftype_ptr;
4495 /* Create all the identifiers we need. */
4496 initialize_predefined_identifiers ();
4498 /* Create the global variables. */
4499 push_to_top_level ();
4501 current_function_decl = NULL_TREE;
4502 current_binding_level = NULL;
4503 /* Enter the global namespace. */
4504 gcc_assert (global_namespace == NULL_TREE);
4505 global_namespace = build_lang_decl (NAMESPACE_DECL, global_identifier,
4506 void_type_node);
4507 TREE_PUBLIC (global_namespace) = true;
4508 DECL_MODULE_EXPORT_P (global_namespace) = true;
4509 DECL_CONTEXT (global_namespace)
4510 = build_translation_unit_decl (get_identifier (main_input_filename));
4511 /* Remember whether we want the empty class passing ABI change warning
4512 in this TU. */
4513 TRANSLATION_UNIT_WARN_EMPTY_P (DECL_CONTEXT (global_namespace))
4514 = warn_abi && abi_version_crosses (12);
4515 debug_hooks->register_main_translation_unit
4516 (DECL_CONTEXT (global_namespace));
4517 begin_scope (sk_namespace, global_namespace);
4518 current_namespace = global_namespace;
4520 if (flag_visibility_ms_compat)
4521 default_visibility = VISIBILITY_HIDDEN;
4523 /* Initially, C. */
4524 current_lang_name = lang_name_c;
4526 /* Create the `std' namespace. */
4527 push_namespace (get_identifier ("std"));
4528 std_node = current_namespace;
4529 pop_namespace ();
4531 flag_noexcept_type = (cxx_dialect >= cxx17);
4533 c_common_nodes_and_builtins ();
4535 tree bool_ftype = build_function_type_list (boolean_type_node, NULL_TREE);
4536 tree decl
4537 = add_builtin_function ("__builtin_is_constant_evaluated",
4538 bool_ftype, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
4539 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4540 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4542 tree cptr_ftype = build_function_type_list (const_ptr_type_node, NULL_TREE);
4543 decl = add_builtin_function ("__builtin_source_location",
4544 cptr_ftype, CP_BUILT_IN_SOURCE_LOCATION,
4545 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4546 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4548 tree bool_vaftype = build_varargs_function_type_list (boolean_type_node,
4549 NULL_TREE);
4550 decl
4551 = add_builtin_function ("__builtin_is_corresponding_member",
4552 bool_vaftype,
4553 CP_BUILT_IN_IS_CORRESPONDING_MEMBER,
4554 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4555 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4557 decl
4558 = add_builtin_function ("__builtin_is_pointer_interconvertible_with_class",
4559 bool_vaftype,
4560 CP_BUILT_IN_IS_POINTER_INTERCONVERTIBLE_WITH_CLASS,
4561 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4562 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4564 integer_two_node = build_int_cst (NULL_TREE, 2);
4566 /* Guess at the initial static decls size. */
4567 vec_alloc (static_decls, 500);
4569 /* ... and keyed classes. */
4570 vec_alloc (keyed_classes, 100);
4572 record_builtin_type (RID_BOOL, "bool", boolean_type_node);
4573 truthvalue_type_node = boolean_type_node;
4574 truthvalue_false_node = boolean_false_node;
4575 truthvalue_true_node = boolean_true_node;
4577 empty_except_spec = build_tree_list (NULL_TREE, NULL_TREE);
4578 noexcept_true_spec = build_tree_list (boolean_true_node, NULL_TREE);
4579 noexcept_false_spec = build_tree_list (boolean_false_node, NULL_TREE);
4580 noexcept_deferred_spec = build_tree_list (make_node (DEFERRED_NOEXCEPT),
4581 NULL_TREE);
4583 #if 0
4584 record_builtin_type (RID_MAX, NULL, string_type_node);
4585 #endif
4587 delta_type_node = ptrdiff_type_node;
4588 vtable_index_type = ptrdiff_type_node;
4590 vtt_parm_type = build_pointer_type (const_ptr_type_node);
4591 void_ftype = build_function_type_list (void_type_node, NULL_TREE);
4592 void_ftype_ptr = build_function_type_list (void_type_node,
4593 ptr_type_node, NULL_TREE);
4594 void_ftype_ptr
4595 = build_exception_variant (void_ftype_ptr, empty_except_spec);
4597 /* Create the conversion operator marker. This operator's DECL_NAME
4598 is in the identifier table, so we can use identifier equality to
4599 find it. */
4600 conv_op_marker = build_lang_decl (FUNCTION_DECL, conv_op_identifier,
4601 void_ftype);
4603 /* C++ extensions */
4605 unknown_type_node = make_node (LANG_TYPE);
4606 record_unknown_type (unknown_type_node, "unknown type");
4608 /* Indirecting an UNKNOWN_TYPE node yields an UNKNOWN_TYPE node. */
4609 TREE_TYPE (unknown_type_node) = unknown_type_node;
4611 /* Looking up TYPE_POINTER_TO and TYPE_REFERENCE_TO yield the same
4612 result. */
4613 TYPE_POINTER_TO (unknown_type_node) = unknown_type_node;
4614 TYPE_REFERENCE_TO (unknown_type_node) = unknown_type_node;
4616 init_list_type_node = make_node (LANG_TYPE);
4617 record_unknown_type (init_list_type_node, "init list");
4619 /* Used when parsing to distinguish parameter-lists () and (void). */
4620 explicit_void_list_node = build_void_list_node ();
4623 /* Make sure we get a unique function type, so we can give
4624 its pointer type a name. (This wins for gdb.) */
4625 tree vfunc_type = make_node (FUNCTION_TYPE);
4626 TREE_TYPE (vfunc_type) = integer_type_node;
4627 TYPE_ARG_TYPES (vfunc_type) = NULL_TREE;
4628 layout_type (vfunc_type);
4630 vtable_entry_type = build_pointer_type (vfunc_type);
4632 record_builtin_type (RID_MAX, "__vtbl_ptr_type", vtable_entry_type);
4634 vtbl_type_node
4635 = build_cplus_array_type (vtable_entry_type, NULL_TREE);
4636 layout_type (vtbl_type_node);
4637 vtbl_type_node = cp_build_qualified_type (vtbl_type_node, TYPE_QUAL_CONST);
4638 record_builtin_type (RID_MAX, NULL, vtbl_type_node);
4639 vtbl_ptr_type_node = build_pointer_type (vtable_entry_type);
4640 layout_type (vtbl_ptr_type_node);
4641 record_builtin_type (RID_MAX, NULL, vtbl_ptr_type_node);
4643 push_namespace (get_identifier ("__cxxabiv1"));
4644 abi_node = current_namespace;
4645 pop_namespace ();
4647 any_targ_node = make_node (LANG_TYPE);
4648 record_unknown_type (any_targ_node, "any type");
4650 /* Now, C++. */
4651 current_lang_name = lang_name_cplusplus;
4653 if (aligned_new_threshold > 1
4654 && !pow2p_hwi (aligned_new_threshold))
4656 error ("%<-faligned-new=%d%> is not a power of two",
4657 aligned_new_threshold);
4658 aligned_new_threshold = 1;
4660 if (aligned_new_threshold == -1)
4661 aligned_new_threshold = (cxx_dialect >= cxx17) ? 1 : 0;
4662 if (aligned_new_threshold == 1)
4663 aligned_new_threshold = malloc_alignment () / BITS_PER_UNIT;
4666 tree newattrs, extvisattr;
4667 tree newtype, deltype;
4668 tree ptr_ftype_sizetype;
4669 tree new_eh_spec;
4671 ptr_ftype_sizetype
4672 = build_function_type_list (ptr_type_node, size_type_node, NULL_TREE);
4673 if (cxx_dialect == cxx98)
4675 tree bad_alloc_id;
4676 tree bad_alloc_type_node;
4677 tree bad_alloc_decl;
4679 push_nested_namespace (std_node);
4680 bad_alloc_id = get_identifier ("bad_alloc");
4681 bad_alloc_type_node = make_class_type (RECORD_TYPE);
4682 TYPE_CONTEXT (bad_alloc_type_node) = current_namespace;
4683 bad_alloc_decl
4684 = create_implicit_typedef (bad_alloc_id, bad_alloc_type_node);
4685 DECL_CONTEXT (bad_alloc_decl) = current_namespace;
4686 pop_nested_namespace (std_node);
4688 new_eh_spec
4689 = add_exception_specifier (NULL_TREE, bad_alloc_type_node, -1);
4691 else
4692 new_eh_spec = noexcept_false_spec;
4694 /* Ensure attribs.cc is initialized. */
4695 init_attributes ();
4697 extvisattr = build_tree_list (get_identifier ("externally_visible"),
4698 NULL_TREE);
4699 newattrs = tree_cons (get_identifier ("alloc_size"),
4700 build_tree_list (NULL_TREE, integer_one_node),
4701 extvisattr);
4702 newtype = cp_build_type_attribute_variant (ptr_ftype_sizetype, newattrs);
4703 newtype = build_exception_variant (newtype, new_eh_spec);
4704 deltype = cp_build_type_attribute_variant (void_ftype_ptr, extvisattr);
4705 deltype = build_exception_variant (deltype, empty_except_spec);
4706 tree opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
4707 DECL_IS_MALLOC (opnew) = 1;
4708 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4709 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4710 opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
4711 DECL_IS_MALLOC (opnew) = 1;
4712 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4713 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4714 tree opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4715 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4716 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4717 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4718 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4719 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4720 if (flag_sized_deallocation)
4722 /* Also push the sized deallocation variants:
4723 void operator delete(void*, std::size_t) throw();
4724 void operator delete[](void*, std::size_t) throw(); */
4725 tree void_ftype_ptr_size
4726 = build_function_type_list (void_type_node, ptr_type_node,
4727 size_type_node, NULL_TREE);
4728 deltype = cp_build_type_attribute_variant (void_ftype_ptr_size,
4729 extvisattr);
4730 deltype = build_exception_variant (deltype, empty_except_spec);
4731 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4732 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4733 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4734 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4735 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4736 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4739 if (aligned_new_threshold)
4741 push_nested_namespace (std_node);
4742 tree align_id = get_identifier ("align_val_t");
4743 align_type_node = start_enum (align_id, NULL_TREE, size_type_node,
4744 NULL_TREE, /*scoped*/true, NULL);
4745 pop_nested_namespace (std_node);
4747 /* operator new (size_t, align_val_t); */
4748 newtype = build_function_type_list (ptr_type_node, size_type_node,
4749 align_type_node, NULL_TREE);
4750 newtype = cp_build_type_attribute_variant (newtype, newattrs);
4751 newtype = build_exception_variant (newtype, new_eh_spec);
4752 opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
4753 DECL_IS_MALLOC (opnew) = 1;
4754 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4755 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4756 opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
4757 DECL_IS_MALLOC (opnew) = 1;
4758 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4759 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4761 /* operator delete (void *, align_val_t); */
4762 deltype = build_function_type_list (void_type_node, ptr_type_node,
4763 align_type_node, NULL_TREE);
4764 deltype = cp_build_type_attribute_variant (deltype, extvisattr);
4765 deltype = build_exception_variant (deltype, empty_except_spec);
4766 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4767 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4768 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4769 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4770 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4771 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4773 if (flag_sized_deallocation)
4775 /* operator delete (void *, size_t, align_val_t); */
4776 deltype = build_function_type_list (void_type_node, ptr_type_node,
4777 size_type_node, align_type_node,
4778 NULL_TREE);
4779 deltype = cp_build_type_attribute_variant (deltype, extvisattr);
4780 deltype = build_exception_variant (deltype, empty_except_spec);
4781 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4782 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4783 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4784 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4785 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4786 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4790 nullptr_type_node = make_node (NULLPTR_TYPE);
4791 TYPE_SIZE (nullptr_type_node) = bitsize_int (GET_MODE_BITSIZE (ptr_mode));
4792 TYPE_SIZE_UNIT (nullptr_type_node) = size_int (GET_MODE_SIZE (ptr_mode));
4793 TYPE_UNSIGNED (nullptr_type_node) = 1;
4794 TYPE_PRECISION (nullptr_type_node) = GET_MODE_BITSIZE (ptr_mode);
4795 if (abi_version_at_least (9))
4796 SET_TYPE_ALIGN (nullptr_type_node, GET_MODE_ALIGNMENT (ptr_mode));
4797 SET_TYPE_MODE (nullptr_type_node, ptr_mode);
4798 record_builtin_type (RID_MAX, "decltype(nullptr)", nullptr_type_node);
4799 nullptr_node = build_int_cst (nullptr_type_node, 0);
4802 if (! supports_one_only ())
4803 flag_weak = 0;
4805 abort_fndecl
4806 = build_library_fn_ptr ("__cxa_pure_virtual", void_ftype,
4807 ECF_NORETURN | ECF_NOTHROW | ECF_COLD);
4808 if (flag_weak)
4809 /* If no definition is available, resolve references to NULL. */
4810 declare_weak (abort_fndecl);
4812 /* Perform other language dependent initializations. */
4813 init_class_processing ();
4814 init_rtti_processing ();
4815 init_template_processing ();
4817 if (flag_exceptions)
4818 init_exception_processing ();
4820 if (modules_p ())
4821 init_modules (parse_in);
4823 make_fname_decl = cp_make_fname_decl;
4824 start_fname_decls ();
4826 /* Show we use EH for cleanups. */
4827 if (flag_exceptions)
4828 using_eh_for_cleanups ();
4830 /* Check that the hardware interference sizes are at least
4831 alignof(max_align_t), as required by the standard. */
4832 const int max_align = max_align_t_align () / BITS_PER_UNIT;
4833 if (OPTION_SET_P (param_destruct_interfere_size))
4835 if (param_destruct_interfere_size < max_align)
4836 error ("%<--param destructive-interference-size=%d%> is less than "
4837 "%d", param_destruct_interfere_size, max_align);
4838 else if (param_destruct_interfere_size < param_l1_cache_line_size)
4839 warning (OPT_Winterference_size,
4840 "%<--param destructive-interference-size=%d%> "
4841 "is less than %<--param l1-cache-line-size=%d%>",
4842 param_destruct_interfere_size, param_l1_cache_line_size);
4844 else if (param_destruct_interfere_size)
4845 /* Assume the internal value is OK. */;
4846 else if (param_l1_cache_line_size >= max_align)
4847 param_destruct_interfere_size = param_l1_cache_line_size;
4848 /* else leave it unset. */
4850 if (OPTION_SET_P (param_construct_interfere_size))
4852 if (param_construct_interfere_size < max_align)
4853 error ("%<--param constructive-interference-size=%d%> is less than "
4854 "%d", param_construct_interfere_size, max_align);
4855 else if (param_construct_interfere_size > param_l1_cache_line_size
4856 && param_l1_cache_line_size >= max_align)
4857 warning (OPT_Winterference_size,
4858 "%<--param constructive-interference-size=%d%> "
4859 "is greater than %<--param l1-cache-line-size=%d%>",
4860 param_construct_interfere_size, param_l1_cache_line_size);
4862 else if (param_construct_interfere_size)
4863 /* Assume the internal value is OK. */;
4864 else if (param_l1_cache_line_size >= max_align)
4865 param_construct_interfere_size = param_l1_cache_line_size;
4868 /* Enter an abi node in global-module context. returns a cookie to
4869 give to pop_abi_namespace. */
4871 unsigned
4872 push_abi_namespace (tree node)
4874 push_nested_namespace (node);
4875 push_visibility ("default", 2);
4876 unsigned flags = module_kind;
4877 module_kind = 0;
4878 return flags;
4881 /* Pop an abi namespace, FLAGS is the cookie push_abi_namespace gave
4882 you. */
4884 void
4885 pop_abi_namespace (unsigned flags, tree node)
4887 module_kind = flags;
4888 pop_visibility (2);
4889 pop_nested_namespace (node);
4892 /* Create the VAR_DECL for __FUNCTION__ etc. ID is the name to give
4893 the decl, LOC is the location to give the decl, NAME is the
4894 initialization string and TYPE_DEP indicates whether NAME depended
4895 on the type of the function. We make use of that to detect
4896 __PRETTY_FUNCTION__ inside a template fn. This is being done lazily
4897 at the point of first use, so we mustn't push the decl now. */
4899 static tree
4900 cp_make_fname_decl (location_t loc, tree id, int type_dep)
4902 tree domain = NULL_TREE;
4903 tree init = NULL_TREE;
4905 if (!(type_dep && in_template_function ()))
4907 const char *name = NULL;
4908 bool release_name = false;
4910 if (current_function_decl == NULL_TREE)
4911 name = "top level";
4912 else if (type_dep == 0)
4914 /* __FUNCTION__ */
4915 name = fname_as_string (type_dep);
4916 release_name = true;
4918 else
4920 /* __PRETTY_FUNCTION__ */
4921 gcc_checking_assert (type_dep == 1);
4922 name = cxx_printable_name (current_function_decl, 2);
4925 size_t length = strlen (name);
4926 domain = build_index_type (size_int (length));
4927 init = build_string (length + 1, name);
4928 if (release_name)
4929 free (const_cast<char *> (name));
4932 tree type = cp_build_qualified_type (char_type_node, TYPE_QUAL_CONST);
4933 type = build_cplus_array_type (type, domain);
4935 if (init)
4936 TREE_TYPE (init) = type;
4937 else
4938 init = error_mark_node;
4940 tree decl = build_decl (loc, VAR_DECL, id, type);
4942 TREE_READONLY (decl) = 1;
4943 DECL_ARTIFICIAL (decl) = 1;
4944 DECL_DECLARED_CONSTEXPR_P (decl) = 1;
4945 TREE_STATIC (decl) = 1;
4947 TREE_USED (decl) = 1;
4949 SET_DECL_VALUE_EXPR (decl, init);
4950 DECL_HAS_VALUE_EXPR_P (decl) = 1;
4951 /* For decl_constant_var_p. */
4952 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
4954 if (current_function_decl)
4956 DECL_CONTEXT (decl) = current_function_decl;
4957 decl = pushdecl_outermost_localscope (decl);
4958 if (decl != error_mark_node)
4959 add_decl_expr (decl);
4961 else
4963 DECL_THIS_STATIC (decl) = true;
4964 decl = pushdecl_top_level_and_finish (decl, NULL_TREE);
4967 return decl;
4970 /* Install DECL as a builtin function at current global scope. Return
4971 the new decl (if we found an existing version). Also installs it
4972 into ::std, if it's not '_*'. */
4974 tree
4975 cxx_builtin_function (tree decl)
4977 retrofit_lang_decl (decl);
4979 DECL_ARTIFICIAL (decl) = 1;
4980 SET_DECL_LANGUAGE (decl, lang_c);
4981 /* Runtime library routines are, by definition, available in an
4982 external shared object. */
4983 DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
4984 DECL_VISIBILITY_SPECIFIED (decl) = 1;
4986 tree id = DECL_NAME (decl);
4987 const char *name = IDENTIFIER_POINTER (id);
4988 bool hiding = false;
4989 if (name[0] != '_' || name[1] != '_')
4990 /* In the user's namespace, it must be declared before use. */
4991 hiding = true;
4992 else if (IDENTIFIER_LENGTH (id) > strlen ("___chk")
4993 && !startswith (name + 2, "builtin_")
4994 && 0 == memcmp (name + IDENTIFIER_LENGTH (id) - strlen ("_chk"),
4995 "_chk", strlen ("_chk") + 1))
4996 /* Treat __*_chk fortification functions as anticipated as well,
4997 unless they are __builtin_*_chk. */
4998 hiding = true;
5000 /* All builtins that don't begin with an '_' should additionally
5001 go in the 'std' namespace. */
5002 if (name[0] != '_')
5004 tree std_decl = copy_decl (decl);
5006 push_nested_namespace (std_node);
5007 DECL_CONTEXT (std_decl) = FROB_CONTEXT (std_node);
5008 pushdecl (std_decl, hiding);
5009 pop_nested_namespace (std_node);
5012 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5013 decl = pushdecl (decl, hiding);
5015 return decl;
5018 /* Like cxx_builtin_function, but guarantee the function is added to the global
5019 scope. This is to allow function specific options to add new machine
5020 dependent builtins when the target ISA changes via attribute((target(...)))
5021 which saves space on program startup if the program does not use non-generic
5022 ISAs. */
5024 tree
5025 cxx_builtin_function_ext_scope (tree decl)
5027 push_nested_namespace (global_namespace);
5028 decl = cxx_builtin_function (decl);
5029 pop_nested_namespace (global_namespace);
5031 return decl;
5034 /* Implement LANG_HOOKS_SIMULATE_BUILTIN_FUNCTION_DECL. */
5036 tree
5037 cxx_simulate_builtin_function_decl (tree decl)
5039 retrofit_lang_decl (decl);
5041 DECL_ARTIFICIAL (decl) = 1;
5042 SET_DECL_LANGUAGE (decl, lang_cplusplus);
5043 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5044 return pushdecl (decl);
5047 /* Generate a FUNCTION_DECL with the typical flags for a runtime library
5048 function. Not called directly. */
5050 static tree
5051 build_library_fn (tree name, enum tree_code operator_code, tree type,
5052 int ecf_flags)
5054 tree fn = build_lang_decl (FUNCTION_DECL, name, type);
5055 DECL_EXTERNAL (fn) = 1;
5056 TREE_PUBLIC (fn) = 1;
5057 DECL_ARTIFICIAL (fn) = 1;
5058 DECL_OVERLOADED_OPERATOR_CODE_RAW (fn)
5059 = OVL_OP_INFO (false, operator_code)->ovl_op_code;
5060 SET_DECL_LANGUAGE (fn, lang_c);
5061 /* Runtime library routines are, by definition, available in an
5062 external shared object. */
5063 DECL_VISIBILITY (fn) = VISIBILITY_DEFAULT;
5064 DECL_VISIBILITY_SPECIFIED (fn) = 1;
5065 set_call_expr_flags (fn, ecf_flags);
5066 return fn;
5069 /* Returns the _DECL for a library function with C++ linkage. */
5071 static tree
5072 build_cp_library_fn (tree name, enum tree_code operator_code, tree type,
5073 int ecf_flags)
5075 tree fn = build_library_fn (name, operator_code, type, ecf_flags);
5076 DECL_CONTEXT (fn) = FROB_CONTEXT (current_namespace);
5077 SET_DECL_LANGUAGE (fn, lang_cplusplus);
5078 return fn;
5081 /* Like build_library_fn, but takes a C string instead of an
5082 IDENTIFIER_NODE. */
5084 tree
5085 build_library_fn_ptr (const char* name, tree type, int ecf_flags)
5087 return build_library_fn (get_identifier (name), ERROR_MARK, type, ecf_flags);
5090 /* Like build_cp_library_fn, but takes a C string instead of an
5091 IDENTIFIER_NODE. */
5093 tree
5094 build_cp_library_fn_ptr (const char* name, tree type, int ecf_flags)
5096 return build_cp_library_fn (get_identifier (name), ERROR_MARK, type,
5097 ecf_flags);
5100 /* Like build_library_fn, but also pushes the function so that we will
5101 be able to find it via get_global_binding. Also, the function
5102 may throw exceptions listed in RAISES. */
5104 tree
5105 push_library_fn (tree name, tree type, tree raises, int ecf_flags)
5107 if (raises)
5108 type = build_exception_variant (type, raises);
5110 tree fn = build_library_fn (name, ERROR_MARK, type, ecf_flags);
5111 return pushdecl_top_level (fn);
5114 /* Like build_cp_library_fn, but also pushes the function so that it
5115 will be found by normal lookup. */
5117 static tree
5118 push_cp_library_fn (enum tree_code operator_code, tree type,
5119 int ecf_flags)
5121 tree fn = build_cp_library_fn (ovl_op_identifier (false, operator_code),
5122 operator_code, type, ecf_flags);
5123 pushdecl (fn);
5124 if (flag_tm)
5125 apply_tm_attr (fn, get_identifier ("transaction_safe"));
5126 return fn;
5129 /* Like push_library_fn, but also note that this function throws
5130 and does not return. Used for __throw_foo and the like. */
5132 tree
5133 push_throw_library_fn (tree name, tree type)
5135 tree fn = push_library_fn (name, type, NULL_TREE, ECF_NORETURN | ECF_COLD);
5136 return fn;
5139 /* When we call finish_struct for an anonymous union, we create
5140 default copy constructors and such. But, an anonymous union
5141 shouldn't have such things; this function undoes the damage to the
5142 anonymous union type T.
5144 (The reason that we create the synthesized methods is that we don't
5145 distinguish `union { int i; }' from `typedef union { int i; } U'.
5146 The first is an anonymous union; the second is just an ordinary
5147 union type.) */
5149 void
5150 fixup_anonymous_aggr (tree t)
5152 /* Wipe out memory of synthesized methods. */
5153 TYPE_HAS_USER_CONSTRUCTOR (t) = 0;
5154 TYPE_HAS_DEFAULT_CONSTRUCTOR (t) = 0;
5155 TYPE_HAS_COPY_CTOR (t) = 0;
5156 TYPE_HAS_CONST_COPY_CTOR (t) = 0;
5157 TYPE_HAS_COPY_ASSIGN (t) = 0;
5158 TYPE_HAS_CONST_COPY_ASSIGN (t) = 0;
5160 /* Splice the implicitly generated functions out of TYPE_FIELDS and diagnose
5161 invalid members. */
5162 for (tree probe, *prev_p = &TYPE_FIELDS (t); (probe = *prev_p);)
5164 if (TREE_CODE (probe) == FUNCTION_DECL && DECL_ARTIFICIAL (probe))
5165 *prev_p = DECL_CHAIN (probe);
5166 else
5167 prev_p = &DECL_CHAIN (probe);
5169 if (DECL_ARTIFICIAL (probe)
5170 && (!DECL_IMPLICIT_TYPEDEF_P (probe)
5171 || TYPE_ANON_P (TREE_TYPE (probe))))
5172 continue;
5174 if (TREE_CODE (probe) != FIELD_DECL
5175 || (TREE_PRIVATE (probe) || TREE_PROTECTED (probe)))
5177 /* We already complained about static data members in
5178 finish_static_data_member_decl. */
5179 if (!VAR_P (probe))
5181 auto_diagnostic_group d;
5182 if (permerror (DECL_SOURCE_LOCATION (probe),
5183 TREE_CODE (t) == UNION_TYPE
5184 ? "%q#D invalid; an anonymous union may "
5185 "only have public non-static data members"
5186 : "%q#D invalid; an anonymous struct may "
5187 "only have public non-static data members", probe))
5189 static bool hint;
5190 if (flag_permissive && !hint)
5192 hint = true;
5193 inform (DECL_SOURCE_LOCATION (probe),
5194 "this flexibility is deprecated and will be "
5195 "removed");
5202 /* Splice all functions out of CLASSTYPE_MEMBER_VEC. */
5203 vec<tree,va_gc>* vec = CLASSTYPE_MEMBER_VEC (t);
5204 unsigned store = 0;
5205 for (tree elt : vec)
5206 if (!is_overloaded_fn (elt))
5207 (*vec)[store++] = elt;
5208 vec_safe_truncate (vec, store);
5210 /* Wipe RTTI info. */
5211 CLASSTYPE_TYPEINFO_VAR (t) = NULL_TREE;
5213 /* Anonymous aggregates cannot have fields with ctors, dtors or complex
5214 assignment operators (because they cannot have these methods themselves).
5215 For anonymous unions this is already checked because they are not allowed
5216 in any union, otherwise we have to check it. */
5217 if (TREE_CODE (t) != UNION_TYPE)
5219 tree field, type;
5221 if (BINFO_N_BASE_BINFOS (TYPE_BINFO (t)))
5223 error_at (location_of (t), "anonymous struct with base classes");
5224 /* Avoid ICE after error on anon-struct9.C. */
5225 TYPE_NEEDS_CONSTRUCTING (t) = false;
5228 for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
5229 if (TREE_CODE (field) == FIELD_DECL)
5231 type = TREE_TYPE (field);
5232 if (CLASS_TYPE_P (type))
5234 if (TYPE_NEEDS_CONSTRUCTING (type))
5235 error ("member %q+#D with constructor not allowed "
5236 "in anonymous aggregate", field);
5237 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
5238 error ("member %q+#D with destructor not allowed "
5239 "in anonymous aggregate", field);
5240 if (TYPE_HAS_COMPLEX_COPY_ASSIGN (type))
5241 error ("member %q+#D with copy assignment operator "
5242 "not allowed in anonymous aggregate", field);
5248 /* Warn for an attribute located at LOCATION that appertains to the
5249 class type CLASS_TYPE that has not been properly placed after its
5250 class-key, in it class-specifier. */
5252 void
5253 warn_misplaced_attr_for_class_type (location_t location,
5254 tree class_type)
5256 gcc_assert (OVERLOAD_TYPE_P (class_type));
5258 auto_diagnostic_group d;
5259 if (warning_at (location, OPT_Wattributes,
5260 "attribute ignored in declaration "
5261 "of %q#T", class_type))
5262 inform (location,
5263 "attribute for %q#T must follow the %qs keyword",
5264 class_type, class_key_or_enum_as_string (class_type));
5267 /* Returns the cv-qualifiers that apply to the type specified
5268 by the DECLSPECS. */
5270 static int
5271 get_type_quals (const cp_decl_specifier_seq *declspecs)
5273 int type_quals = TYPE_UNQUALIFIED;
5275 if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5276 type_quals |= TYPE_QUAL_CONST;
5277 if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5278 type_quals |= TYPE_QUAL_VOLATILE;
5279 if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5280 type_quals |= TYPE_QUAL_RESTRICT;
5282 return type_quals;
5285 /* Make sure that a declaration with no declarator is well-formed, i.e.
5286 just declares a tagged type or anonymous union.
5288 Returns the type declared; or NULL_TREE if none. */
5290 tree
5291 check_tag_decl (cp_decl_specifier_seq *declspecs,
5292 bool explicit_type_instantiation_p)
5294 int saw_friend = decl_spec_seq_has_spec_p (declspecs, ds_friend);
5295 int saw_typedef = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
5296 /* If a class, struct, or enum type is declared by the DECLSPECS
5297 (i.e, if a class-specifier, enum-specifier, or non-typename
5298 elaborated-type-specifier appears in the DECLSPECS),
5299 DECLARED_TYPE is set to the corresponding type. */
5300 tree declared_type = NULL_TREE;
5301 bool error_p = false;
5303 if (declspecs->multiple_types_p)
5304 error_at (smallest_type_location (declspecs),
5305 "multiple types in one declaration");
5306 else if (declspecs->redefined_builtin_type)
5308 location_t loc = declspecs->locations[ds_redefined_builtin_type_spec];
5309 if (!in_system_header_at (loc))
5310 permerror (loc, "redeclaration of C++ built-in type %qT",
5311 declspecs->redefined_builtin_type);
5312 return NULL_TREE;
5315 if (declspecs->type
5316 && TYPE_P (declspecs->type)
5317 && ((TREE_CODE (declspecs->type) != TYPENAME_TYPE
5318 && MAYBE_CLASS_TYPE_P (declspecs->type))
5319 || TREE_CODE (declspecs->type) == ENUMERAL_TYPE))
5320 declared_type = declspecs->type;
5321 else if (declspecs->type == error_mark_node)
5322 error_p = true;
5324 if (type_uses_auto (declared_type))
5326 error_at (declspecs->locations[ds_type_spec],
5327 "%<auto%> can only be specified for variables "
5328 "or function declarations");
5329 return error_mark_node;
5332 if (declared_type && !OVERLOAD_TYPE_P (declared_type))
5333 declared_type = NULL_TREE;
5335 if (!declared_type && !saw_friend && !error_p)
5336 permerror (input_location, "declaration does not declare anything");
5337 /* Check for an anonymous union. */
5338 else if (declared_type && RECORD_OR_UNION_CODE_P (TREE_CODE (declared_type))
5339 && TYPE_UNNAMED_P (declared_type))
5341 /* 7/3 In a simple-declaration, the optional init-declarator-list
5342 can be omitted only when declaring a class (clause 9) or
5343 enumeration (7.2), that is, when the decl-specifier-seq contains
5344 either a class-specifier, an elaborated-type-specifier with
5345 a class-key (9.1), or an enum-specifier. In these cases and
5346 whenever a class-specifier or enum-specifier is present in the
5347 decl-specifier-seq, the identifiers in these specifiers are among
5348 the names being declared by the declaration (as class-name,
5349 enum-names, or enumerators, depending on the syntax). In such
5350 cases, and except for the declaration of an unnamed bit-field (9.6),
5351 the decl-specifier-seq shall introduce one or more names into the
5352 program, or shall redeclare a name introduced by a previous
5353 declaration. [Example:
5354 enum { }; // ill-formed
5355 typedef class { }; // ill-formed
5356 --end example] */
5357 if (saw_typedef)
5359 error_at (declspecs->locations[ds_typedef],
5360 "missing type-name in typedef-declaration");
5361 return NULL_TREE;
5363 /* Anonymous unions are objects, so they can have specifiers. */;
5364 SET_ANON_AGGR_TYPE_P (declared_type);
5366 if (TREE_CODE (declared_type) != UNION_TYPE)
5367 pedwarn (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (declared_type)),
5368 OPT_Wpedantic, "ISO C++ prohibits anonymous structs");
5371 else
5373 if (decl_spec_seq_has_spec_p (declspecs, ds_inline))
5374 error_at (declspecs->locations[ds_inline],
5375 "%<inline%> can only be specified for functions");
5376 else if (decl_spec_seq_has_spec_p (declspecs, ds_virtual))
5377 error_at (declspecs->locations[ds_virtual],
5378 "%<virtual%> can only be specified for functions");
5379 else if (saw_friend
5380 && (!current_class_type
5381 || current_scope () != current_class_type))
5382 error_at (declspecs->locations[ds_friend],
5383 "%<friend%> can only be specified inside a class");
5384 else if (decl_spec_seq_has_spec_p (declspecs, ds_explicit))
5385 error_at (declspecs->locations[ds_explicit],
5386 "%<explicit%> can only be specified for constructors");
5387 else if (declspecs->storage_class)
5388 error_at (declspecs->locations[ds_storage_class],
5389 "a storage class can only be specified for objects "
5390 "and functions");
5391 else if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5392 error_at (declspecs->locations[ds_const],
5393 "%<const%> can only be specified for objects and "
5394 "functions");
5395 else if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5396 error_at (declspecs->locations[ds_volatile],
5397 "%<volatile%> can only be specified for objects and "
5398 "functions");
5399 else if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5400 error_at (declspecs->locations[ds_restrict],
5401 "%<__restrict%> can only be specified for objects and "
5402 "functions");
5403 else if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
5404 error_at (declspecs->locations[ds_thread],
5405 "%<__thread%> can only be specified for objects "
5406 "and functions");
5407 else if (saw_typedef)
5408 warning_at (declspecs->locations[ds_typedef], 0,
5409 "%<typedef%> was ignored in this declaration");
5410 else if (decl_spec_seq_has_spec_p (declspecs, ds_constexpr))
5411 error_at (declspecs->locations[ds_constexpr],
5412 "%qs cannot be used for type declarations", "constexpr");
5413 else if (decl_spec_seq_has_spec_p (declspecs, ds_constinit))
5414 error_at (declspecs->locations[ds_constinit],
5415 "%qs cannot be used for type declarations", "constinit");
5416 else if (decl_spec_seq_has_spec_p (declspecs, ds_consteval))
5417 error_at (declspecs->locations[ds_consteval],
5418 "%qs cannot be used for type declarations", "consteval");
5421 if (declspecs->attributes && warn_attributes && declared_type)
5423 location_t loc;
5424 if (!CLASS_TYPE_P (declared_type)
5425 || !CLASSTYPE_TEMPLATE_INSTANTIATION (declared_type))
5426 /* For a non-template class, use the name location. */
5427 loc = location_of (declared_type);
5428 else
5429 /* For a template class (an explicit instantiation), use the
5430 current location. */
5431 loc = input_location;
5433 if (explicit_type_instantiation_p)
5434 /* [dcl.attr.grammar]/4:
5436 No attribute-specifier-seq shall appertain to an explicit
5437 instantiation. */
5439 if (warning_at (loc, OPT_Wattributes,
5440 "attribute ignored in explicit instantiation %q#T",
5441 declared_type))
5442 inform (loc,
5443 "no attribute can be applied to "
5444 "an explicit instantiation");
5446 else
5447 warn_misplaced_attr_for_class_type (loc, declared_type);
5450 return declared_type;
5453 /* Called when a declaration is seen that contains no names to declare.
5454 If its type is a reference to a structure, union or enum inherited
5455 from a containing scope, shadow that tag name for the current scope
5456 with a forward reference.
5457 If its type defines a new named structure or union
5458 or defines an enum, it is valid but we need not do anything here.
5459 Otherwise, it is an error.
5461 C++: may have to grok the declspecs to learn about static,
5462 complain for anonymous unions.
5464 Returns the TYPE declared -- or NULL_TREE if none. */
5466 tree
5467 shadow_tag (cp_decl_specifier_seq *declspecs)
5469 tree t = check_tag_decl (declspecs,
5470 /*explicit_type_instantiation_p=*/false);
5472 if (!t)
5473 return NULL_TREE;
5475 t = maybe_process_partial_specialization (t);
5476 if (t == error_mark_node)
5477 return NULL_TREE;
5479 /* This is where the variables in an anonymous union are
5480 declared. An anonymous union declaration looks like:
5481 union { ... } ;
5482 because there is no declarator after the union, the parser
5483 sends that declaration here. */
5484 if (ANON_AGGR_TYPE_P (t))
5486 fixup_anonymous_aggr (t);
5488 if (TYPE_FIELDS (t))
5490 tree decl = grokdeclarator (/*declarator=*/NULL,
5491 declspecs, NORMAL, 0, NULL);
5492 finish_anon_union (decl);
5496 return t;
5499 /* Decode a "typename", such as "int **", returning a ..._TYPE node. */
5501 tree
5502 groktypename (cp_decl_specifier_seq *type_specifiers,
5503 const cp_declarator *declarator,
5504 bool is_template_arg)
5506 tree attrs;
5507 tree type;
5508 enum decl_context context
5509 = is_template_arg ? TEMPLATE_TYPE_ARG : TYPENAME;
5510 attrs = type_specifiers->attributes;
5511 type_specifiers->attributes = NULL_TREE;
5512 type = grokdeclarator (declarator, type_specifiers, context, 0, &attrs);
5513 if (attrs && type != error_mark_node)
5515 if (CLASS_TYPE_P (type))
5516 warning (OPT_Wattributes, "ignoring attributes applied to class type %qT "
5517 "outside of definition", type);
5518 else if (MAYBE_CLASS_TYPE_P (type))
5519 /* A template type parameter or other dependent type. */
5520 warning (OPT_Wattributes, "ignoring attributes applied to dependent "
5521 "type %qT without an associated declaration", type);
5522 else
5523 cplus_decl_attributes (&type, attrs, 0);
5525 return type;
5528 /* Process a DECLARATOR for a function-scope or namespace-scope
5529 variable or function declaration.
5530 (Function definitions go through start_function; class member
5531 declarations appearing in the body of the class go through
5532 grokfield.) The DECL corresponding to the DECLARATOR is returned.
5533 If an error occurs, the error_mark_node is returned instead.
5535 DECLSPECS are the decl-specifiers for the declaration. INITIALIZED is
5536 SD_INITIALIZED if an explicit initializer is present, or SD_DEFAULTED
5537 for an explicitly defaulted function, or SD_DELETED for an explicitly
5538 deleted function, but 0 (SD_UNINITIALIZED) if this is a variable
5539 implicitly initialized via a default constructor. It can also be
5540 SD_DECOMPOSITION which behaves much like SD_INITIALIZED, but we also
5541 mark the new decl as DECL_DECOMPOSITION_P.
5543 ATTRIBUTES and PREFIX_ATTRIBUTES are GNU attributes associated with this
5544 declaration.
5546 The scope represented by the context of the returned DECL is pushed
5547 (if it is not the global namespace) and is assigned to
5548 *PUSHED_SCOPE_P. The caller is then responsible for calling
5549 pop_scope on *PUSHED_SCOPE_P if it is set. */
5551 tree
5552 start_decl (const cp_declarator *declarator,
5553 cp_decl_specifier_seq *declspecs,
5554 int initialized,
5555 tree attributes,
5556 tree prefix_attributes,
5557 tree *pushed_scope_p)
5559 tree decl;
5560 tree context;
5561 bool was_public;
5562 int flags;
5563 bool alias;
5564 tree initial;
5566 *pushed_scope_p = NULL_TREE;
5568 if (prefix_attributes != error_mark_node)
5569 attributes = attr_chainon (attributes, prefix_attributes);
5571 decl = grokdeclarator (declarator, declspecs, NORMAL, initialized,
5572 &attributes);
5574 if (decl == NULL_TREE || VOID_TYPE_P (decl)
5575 || decl == error_mark_node
5576 || prefix_attributes == error_mark_node)
5577 return error_mark_node;
5579 context = CP_DECL_CONTEXT (decl);
5580 if (context != global_namespace)
5581 *pushed_scope_p = push_scope (context);
5583 if (initialized && TREE_CODE (decl) == TYPE_DECL)
5585 error_at (DECL_SOURCE_LOCATION (decl),
5586 "typedef %qD is initialized (use %qs instead)",
5587 decl, "decltype");
5588 return error_mark_node;
5591 /* Save the DECL_INITIAL value in case it gets clobbered to assist
5592 with attribute validation. */
5593 initial = DECL_INITIAL (decl);
5595 if (initialized)
5597 if (! toplevel_bindings_p ()
5598 && DECL_EXTERNAL (decl))
5599 warning (0, "declaration of %q#D has %<extern%> and is initialized",
5600 decl);
5601 DECL_EXTERNAL (decl) = 0;
5602 if (toplevel_bindings_p ())
5603 TREE_STATIC (decl) = 1;
5604 /* Tell 'cplus_decl_attributes' this is an initialized decl,
5605 even though we might not yet have the initializer expression. */
5606 if (!DECL_INITIAL (decl))
5607 DECL_INITIAL (decl) = error_mark_node;
5609 alias = lookup_attribute ("alias", DECL_ATTRIBUTES (decl)) != 0;
5611 if (alias && TREE_CODE (decl) == FUNCTION_DECL)
5612 record_key_method_defined (decl);
5614 /* If this is a typedef that names the class for linkage purposes
5615 (7.1.3p8), apply any attributes directly to the type. */
5616 if (TREE_CODE (decl) == TYPE_DECL
5617 && OVERLOAD_TYPE_P (TREE_TYPE (decl))
5618 && decl == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (decl))))
5619 flags = ATTR_FLAG_TYPE_IN_PLACE;
5620 else
5621 flags = 0;
5623 /* Set attributes here so if duplicate decl, will have proper attributes. */
5624 cplus_decl_attributes (&decl, attributes, flags);
5626 /* Restore the original DECL_INITIAL that we may have clobbered earlier to
5627 assist with attribute validation. */
5628 DECL_INITIAL (decl) = initial;
5630 /* Dllimported symbols cannot be defined. Static data members (which
5631 can be initialized in-class and dllimported) go through grokfield,
5632 not here, so we don't need to exclude those decls when checking for
5633 a definition. */
5634 if (initialized && DECL_DLLIMPORT_P (decl))
5636 error_at (DECL_SOURCE_LOCATION (decl),
5637 "definition of %q#D is marked %<dllimport%>", decl);
5638 DECL_DLLIMPORT_P (decl) = 0;
5641 /* If #pragma weak was used, mark the decl weak now. */
5642 if (!processing_template_decl && !DECL_DECOMPOSITION_P (decl))
5643 maybe_apply_pragma_weak (decl);
5645 if (TREE_CODE (decl) == FUNCTION_DECL
5646 && DECL_DECLARED_INLINE_P (decl)
5647 && DECL_UNINLINABLE (decl)
5648 && lookup_attribute ("noinline", DECL_ATTRIBUTES (decl)))
5649 warning_at (DECL_SOURCE_LOCATION (decl), 0,
5650 "inline function %qD given attribute %qs", decl, "noinline");
5652 if (TYPE_P (context) && COMPLETE_TYPE_P (complete_type (context)))
5654 bool this_tmpl = (current_template_depth
5655 > template_class_depth (context));
5656 if (VAR_P (decl))
5658 tree field = lookup_field (context, DECL_NAME (decl), 0, false);
5659 if (field == NULL_TREE
5660 || !(VAR_P (field) || variable_template_p (field)))
5661 error ("%q+#D is not a static data member of %q#T", decl, context);
5662 else if (variable_template_p (field)
5663 && (DECL_LANG_SPECIFIC (decl)
5664 && DECL_TEMPLATE_SPECIALIZATION (decl)))
5665 /* OK, specialization was already checked. */;
5666 else if (variable_template_p (field) && !this_tmpl)
5668 error_at (DECL_SOURCE_LOCATION (decl),
5669 "non-member-template declaration of %qD", decl);
5670 inform (DECL_SOURCE_LOCATION (field), "does not match "
5671 "member template declaration here");
5672 return error_mark_node;
5674 else
5676 if (variable_template_p (field))
5677 field = DECL_TEMPLATE_RESULT (field);
5679 if (DECL_CONTEXT (field) != context)
5681 if (!same_type_p (DECL_CONTEXT (field), context))
5682 permerror (input_location, "ISO C++ does not permit %<%T::%D%> "
5683 "to be defined as %<%T::%D%>",
5684 DECL_CONTEXT (field), DECL_NAME (decl),
5685 context, DECL_NAME (decl));
5686 DECL_CONTEXT (decl) = DECL_CONTEXT (field);
5688 /* Static data member are tricky; an in-class initialization
5689 still doesn't provide a definition, so the in-class
5690 declaration will have DECL_EXTERNAL set, but will have an
5691 initialization. Thus, duplicate_decls won't warn
5692 about this situation, and so we check here. */
5693 if (initialized && DECL_INITIALIZED_IN_CLASS_P (field))
5694 error ("duplicate initialization of %qD", decl);
5695 field = duplicate_decls (decl, field);
5696 if (field == error_mark_node)
5697 return error_mark_node;
5698 else if (field)
5699 decl = field;
5702 else
5704 tree field = check_classfn (context, decl,
5705 this_tmpl
5706 ? current_template_parms
5707 : NULL_TREE);
5708 if (field && field != error_mark_node
5709 && duplicate_decls (decl, field))
5710 decl = field;
5713 /* cp_finish_decl sets DECL_EXTERNAL if DECL_IN_AGGR_P is set. */
5714 DECL_IN_AGGR_P (decl) = 0;
5715 /* Do not mark DECL as an explicit specialization if it was not
5716 already marked as an instantiation; a declaration should
5717 never be marked as a specialization unless we know what
5718 template is being specialized. */
5719 if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
5721 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
5722 if (TREE_CODE (decl) == FUNCTION_DECL)
5723 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
5724 && DECL_DECLARED_INLINE_P (decl));
5725 else
5726 DECL_COMDAT (decl) = false;
5728 /* [temp.expl.spec] An explicit specialization of a static data
5729 member of a template is a definition if the declaration
5730 includes an initializer; otherwise, it is a declaration.
5732 We check for processing_specialization so this only applies
5733 to the new specialization syntax. */
5734 if (!initialized && processing_specialization)
5735 DECL_EXTERNAL (decl) = 1;
5738 if (DECL_EXTERNAL (decl) && ! DECL_TEMPLATE_SPECIALIZATION (decl)
5739 /* Aliases are definitions. */
5740 && !alias)
5741 permerror (declarator->id_loc,
5742 "declaration of %q#D outside of class is not definition",
5743 decl);
5746 /* Create a DECL_LANG_SPECIFIC so that DECL_DECOMPOSITION_P works. */
5747 if (initialized == SD_DECOMPOSITION)
5748 fit_decomposition_lang_decl (decl, NULL_TREE);
5750 was_public = TREE_PUBLIC (decl);
5752 if ((DECL_EXTERNAL (decl) || TREE_CODE (decl) == FUNCTION_DECL)
5753 && current_function_decl)
5755 /* A function-scope decl of some namespace-scope decl. */
5756 DECL_LOCAL_DECL_P (decl) = true;
5757 if (named_module_purview_p ())
5758 error_at (declarator->id_loc,
5759 "block-scope extern declaration %q#D not permitted"
5760 " in module purview", decl);
5763 /* Enter this declaration into the symbol table. Don't push the plain
5764 VAR_DECL for a variable template. */
5765 if (!template_parm_scope_p ()
5766 || !VAR_P (decl))
5767 decl = maybe_push_decl (decl);
5769 if (processing_template_decl)
5770 decl = push_template_decl (decl);
5772 if (decl == error_mark_node)
5773 return error_mark_node;
5775 if (VAR_P (decl)
5776 && DECL_NAMESPACE_SCOPE_P (decl) && !TREE_PUBLIC (decl) && !was_public
5777 && !DECL_THIS_STATIC (decl) && !DECL_ARTIFICIAL (decl)
5778 /* But not templated variables. */
5779 && !(DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)))
5781 /* This is a const variable with implicit 'static'. Set
5782 DECL_THIS_STATIC so we can tell it from variables that are
5783 !TREE_PUBLIC because of the anonymous namespace. */
5784 gcc_assert (CP_TYPE_CONST_P (TREE_TYPE (decl)) || errorcount);
5785 DECL_THIS_STATIC (decl) = 1;
5788 if (current_function_decl && VAR_P (decl)
5789 && DECL_DECLARED_CONSTEXPR_P (current_function_decl)
5790 && cxx_dialect < cxx23)
5792 bool ok = false;
5793 if (CP_DECL_THREAD_LOCAL_P (decl) && !DECL_REALLY_EXTERN (decl))
5794 error_at (DECL_SOURCE_LOCATION (decl),
5795 "%qD defined %<thread_local%> in %qs function only "
5796 "available with %<-std=c++2b%> or %<-std=gnu++2b%>", decl,
5797 DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
5798 ? "consteval" : "constexpr");
5799 else if (TREE_STATIC (decl))
5800 error_at (DECL_SOURCE_LOCATION (decl),
5801 "%qD defined %<static%> in %qs function only available "
5802 "with %<-std=c++2b%> or %<-std=gnu++2b%>", decl,
5803 DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
5804 ? "consteval" : "constexpr");
5805 else
5806 ok = true;
5807 if (!ok)
5808 cp_function_chain->invalid_constexpr = true;
5811 if (!processing_template_decl && VAR_P (decl))
5812 start_decl_1 (decl, initialized);
5814 return decl;
5817 /* Process the declaration of a variable DECL. INITIALIZED is true
5818 iff DECL is explicitly initialized. (INITIALIZED is false if the
5819 variable is initialized via an implicitly-called constructor.)
5820 This function must be called for ordinary variables (including, for
5821 example, implicit instantiations of templates), but must not be
5822 called for template declarations. */
5824 void
5825 start_decl_1 (tree decl, bool initialized)
5827 gcc_checking_assert (!processing_template_decl);
5829 if (error_operand_p (decl))
5830 return;
5832 gcc_checking_assert (VAR_P (decl));
5834 tree type = TREE_TYPE (decl);
5835 bool complete_p = COMPLETE_TYPE_P (type);
5836 bool aggregate_definition_p
5837 = MAYBE_CLASS_TYPE_P (type) && !DECL_EXTERNAL (decl);
5839 /* If an explicit initializer is present, or if this is a definition
5840 of an aggregate, then we need a complete type at this point.
5841 (Scalars are always complete types, so there is nothing to
5842 check.) This code just sets COMPLETE_P; errors (if necessary)
5843 are issued below. */
5844 if ((initialized || aggregate_definition_p)
5845 && !complete_p
5846 && COMPLETE_TYPE_P (complete_type (type)))
5848 complete_p = true;
5849 /* We will not yet have set TREE_READONLY on DECL if the type
5850 was "const", but incomplete, before this point. But, now, we
5851 have a complete type, so we can try again. */
5852 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
5855 if (initialized)
5856 /* Is it valid for this decl to have an initializer at all? */
5858 /* Don't allow initializations for incomplete types except for
5859 arrays which might be completed by the initialization. */
5860 if (complete_p)
5861 ; /* A complete type is ok. */
5862 else if (type_uses_auto (type))
5863 ; /* An auto type is ok. */
5864 else if (TREE_CODE (type) != ARRAY_TYPE)
5866 error ("variable %q#D has initializer but incomplete type", decl);
5867 type = TREE_TYPE (decl) = error_mark_node;
5869 else if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (type))))
5871 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
5872 error ("elements of array %q#D have incomplete type", decl);
5873 /* else we already gave an error in start_decl. */
5876 else if (aggregate_definition_p && !complete_p)
5878 if (type_uses_auto (type))
5879 gcc_assert (CLASS_PLACEHOLDER_TEMPLATE (type));
5880 else
5882 error ("aggregate %q#D has incomplete type and cannot be defined",
5883 decl);
5884 /* Change the type so that assemble_variable will give
5885 DECL an rtl we can live with: (mem (const_int 0)). */
5886 type = TREE_TYPE (decl) = error_mark_node;
5890 /* Create a new scope to hold this declaration if necessary.
5891 Whether or not a new scope is necessary cannot be determined
5892 until after the type has been completed; if the type is a
5893 specialization of a class template it is not until after
5894 instantiation has occurred that TYPE_HAS_NONTRIVIAL_DESTRUCTOR
5895 will be set correctly. */
5896 maybe_push_cleanup_level (type);
5899 /* Given a parenthesized list of values INIT, create a CONSTRUCTOR to handle
5900 C++20 P0960. TYPE is the type of the object we're initializing. */
5902 tree
5903 do_aggregate_paren_init (tree init, tree type)
5905 tree val = TREE_VALUE (init);
5907 if (TREE_CHAIN (init) == NULL_TREE)
5909 /* If the list has a single element and it's a string literal,
5910 then it's the initializer for the array as a whole. */
5911 if (TREE_CODE (type) == ARRAY_TYPE
5912 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
5913 && TREE_CODE (tree_strip_any_location_wrapper (val))
5914 == STRING_CST)
5915 return val;
5916 /* Handle non-standard extensions like compound literals. This also
5917 prevents triggering aggregate parenthesized-initialization in
5918 compiler-generated code for =default. */
5919 else if (same_type_ignoring_top_level_qualifiers_p (type,
5920 TREE_TYPE (val)))
5921 return val;
5924 init = build_constructor_from_list (init_list_type_node, init);
5925 CONSTRUCTOR_IS_DIRECT_INIT (init) = true;
5926 CONSTRUCTOR_IS_PAREN_INIT (init) = true;
5927 return init;
5930 /* Handle initialization of references. DECL, TYPE, and INIT have the
5931 same meaning as in cp_finish_decl. *CLEANUP must be NULL on entry,
5932 but will be set to a new CLEANUP_STMT if a temporary is created
5933 that must be destroyed subsequently.
5935 Returns an initializer expression to use to initialize DECL, or
5936 NULL if the initialization can be performed statically.
5938 Quotes on semantics can be found in ARM 8.4.3. */
5940 static tree
5941 grok_reference_init (tree decl, tree type, tree init, int flags)
5943 if (init == NULL_TREE)
5945 if ((DECL_LANG_SPECIFIC (decl) == 0
5946 || DECL_IN_AGGR_P (decl) == 0)
5947 && ! DECL_THIS_EXTERN (decl))
5948 error_at (DECL_SOURCE_LOCATION (decl),
5949 "%qD declared as reference but not initialized", decl);
5950 return NULL_TREE;
5953 tree ttype = TREE_TYPE (type);
5954 if (TREE_CODE (init) == TREE_LIST)
5956 /* This handles (C++20 only) code like
5958 const A& r(1, 2, 3);
5960 where we treat the parenthesized list as a CONSTRUCTOR. */
5961 if (TREE_TYPE (init) == NULL_TREE
5962 && CP_AGGREGATE_TYPE_P (ttype)
5963 && !DECL_DECOMPOSITION_P (decl)
5964 && (cxx_dialect >= cxx20))
5966 /* We don't know yet if we should treat const A& r(1) as
5967 const A& r{1}. */
5968 if (list_length (init) == 1)
5970 flags |= LOOKUP_AGGREGATE_PAREN_INIT;
5971 init = build_x_compound_expr_from_list (init, ELK_INIT,
5972 tf_warning_or_error);
5974 /* If the list had more than one element, the code is ill-formed
5975 pre-C++20, so we can build a constructor right away. */
5976 else
5977 init = do_aggregate_paren_init (init, ttype);
5979 else
5980 init = build_x_compound_expr_from_list (init, ELK_INIT,
5981 tf_warning_or_error);
5984 if (TREE_CODE (ttype) != ARRAY_TYPE
5985 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
5986 /* Note: default conversion is only called in very special cases. */
5987 init = decay_conversion (init, tf_warning_or_error);
5989 /* check_initializer handles this for non-reference variables, but for
5990 references we need to do it here or the initializer will get the
5991 incomplete array type and confuse later calls to
5992 cp_complete_array_type. */
5993 if (TREE_CODE (ttype) == ARRAY_TYPE
5994 && TYPE_DOMAIN (ttype) == NULL_TREE
5995 && (BRACE_ENCLOSED_INITIALIZER_P (init)
5996 || TREE_CODE (init) == STRING_CST))
5998 cp_complete_array_type (&ttype, init, false);
5999 if (ttype != TREE_TYPE (type))
6000 type = cp_build_reference_type (ttype, TYPE_REF_IS_RVALUE (type));
6003 /* Convert INIT to the reference type TYPE. This may involve the
6004 creation of a temporary, whose lifetime must be the same as that
6005 of the reference. If so, a DECL_EXPR for the temporary will be
6006 added just after the DECL_EXPR for DECL. That's why we don't set
6007 DECL_INITIAL for local references (instead assigning to them
6008 explicitly); we need to allow the temporary to be initialized
6009 first. */
6010 return initialize_reference (type, init, flags,
6011 tf_warning_or_error);
6014 /* Designated initializers in arrays are not supported in GNU C++.
6015 The parser cannot detect this error since it does not know whether
6016 a given brace-enclosed initializer is for a class type or for an
6017 array. This function checks that CE does not use a designated
6018 initializer. If it does, an error is issued. Returns true if CE
6019 is valid, i.e., does not have a designated initializer. */
6021 bool
6022 check_array_designated_initializer (constructor_elt *ce,
6023 unsigned HOST_WIDE_INT index)
6025 /* Designated initializers for array elements are not supported. */
6026 if (ce->index)
6028 /* The parser only allows identifiers as designated
6029 initializers. */
6030 if (ce->index == error_mark_node)
6032 error ("name used in a GNU-style designated "
6033 "initializer for an array");
6034 return false;
6036 else if (identifier_p (ce->index))
6038 error ("name %qD used in a GNU-style designated "
6039 "initializer for an array", ce->index);
6040 return false;
6043 tree ce_index = build_expr_type_conversion (WANT_INT | WANT_ENUM,
6044 ce->index, true);
6045 if (ce_index
6046 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ce_index))
6047 && (TREE_CODE (ce_index = fold_non_dependent_expr (ce_index))
6048 == INTEGER_CST))
6050 /* A C99 designator is OK if it matches the current index. */
6051 if (wi::to_wide (ce_index) == index)
6053 ce->index = ce_index;
6054 return true;
6056 else
6057 sorry ("non-trivial designated initializers not supported");
6059 else
6060 error_at (cp_expr_loc_or_input_loc (ce->index),
6061 "C99 designator %qE is not an integral constant-expression",
6062 ce->index);
6064 return false;
6067 return true;
6070 /* When parsing `int a[] = {1, 2};' we don't know the size of the
6071 array until we finish parsing the initializer. If that's the
6072 situation we're in, update DECL accordingly. */
6074 static void
6075 maybe_deduce_size_from_array_init (tree decl, tree init)
6077 tree type = TREE_TYPE (decl);
6079 if (TREE_CODE (type) == ARRAY_TYPE
6080 && TYPE_DOMAIN (type) == NULL_TREE
6081 && TREE_CODE (decl) != TYPE_DECL)
6083 /* do_default is really a C-ism to deal with tentative definitions.
6084 But let's leave it here to ease the eventual merge. */
6085 int do_default = !DECL_EXTERNAL (decl);
6086 tree initializer = init ? init : DECL_INITIAL (decl);
6087 int failure = 0;
6089 /* Check that there are no designated initializers in INIT, as
6090 those are not supported in GNU C++, and as the middle-end
6091 will crash if presented with a non-numeric designated
6092 initializer. */
6093 if (initializer && BRACE_ENCLOSED_INITIALIZER_P (initializer))
6095 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initializer);
6096 constructor_elt *ce;
6097 HOST_WIDE_INT i;
6098 FOR_EACH_VEC_SAFE_ELT (v, i, ce)
6100 if (instantiation_dependent_expression_p (ce->index))
6101 return;
6102 if (!check_array_designated_initializer (ce, i))
6103 failure = 1;
6104 /* If an un-designated initializer is type-dependent, we can't
6105 check brace elision yet. */
6106 if (ce->index == NULL_TREE
6107 && type_dependent_expression_p (ce->value))
6108 return;
6112 if (failure)
6113 TREE_TYPE (decl) = error_mark_node;
6114 else
6116 failure = cp_complete_array_type (&TREE_TYPE (decl), initializer,
6117 do_default);
6118 if (failure == 1)
6120 error_at (cp_expr_loc_or_loc (initializer,
6121 DECL_SOURCE_LOCATION (decl)),
6122 "initializer fails to determine size of %qD", decl);
6124 else if (failure == 2)
6126 if (do_default)
6128 error_at (DECL_SOURCE_LOCATION (decl),
6129 "array size missing in %qD", decl);
6131 /* If a `static' var's size isn't known, make it extern as
6132 well as static, so it does not get allocated. If it's not
6133 `static', then don't mark it extern; finish_incomplete_decl
6134 will give it a default size and it will get allocated. */
6135 else if (!pedantic && TREE_STATIC (decl) && !TREE_PUBLIC (decl))
6136 DECL_EXTERNAL (decl) = 1;
6138 else if (failure == 3)
6140 error_at (DECL_SOURCE_LOCATION (decl),
6141 "zero-size array %qD", decl);
6145 cp_apply_type_quals_to_decl (cp_type_quals (TREE_TYPE (decl)), decl);
6147 relayout_decl (decl);
6151 /* Set DECL_SIZE, DECL_ALIGN, etc. for DECL (a VAR_DECL), and issue
6152 any appropriate error messages regarding the layout. */
6154 static void
6155 layout_var_decl (tree decl)
6157 tree type;
6159 type = TREE_TYPE (decl);
6160 if (type == error_mark_node)
6161 return;
6163 /* If we haven't already laid out this declaration, do so now.
6164 Note that we must not call complete type for an external object
6165 because it's type might involve templates that we are not
6166 supposed to instantiate yet. (And it's perfectly valid to say
6167 `extern X x' for some incomplete type `X'.) */
6168 if (!DECL_EXTERNAL (decl))
6169 complete_type (type);
6170 if (!DECL_SIZE (decl)
6171 && TREE_TYPE (decl) != error_mark_node
6172 && complete_or_array_type_p (type))
6173 layout_decl (decl, 0);
6175 if (!DECL_EXTERNAL (decl) && DECL_SIZE (decl) == NULL_TREE)
6177 /* An automatic variable with an incomplete type: that is an error.
6178 Don't talk about array types here, since we took care of that
6179 message in grokdeclarator. */
6180 error_at (DECL_SOURCE_LOCATION (decl),
6181 "storage size of %qD isn%'t known", decl);
6182 TREE_TYPE (decl) = error_mark_node;
6184 #if 0
6185 /* Keep this code around in case we later want to control debug info
6186 based on whether a type is "used". (jason 1999-11-11) */
6188 else if (!DECL_EXTERNAL (decl) && MAYBE_CLASS_TYPE_P (ttype))
6189 /* Let debugger know it should output info for this type. */
6190 note_debug_info_needed (ttype);
6192 if (TREE_STATIC (decl) && DECL_CLASS_SCOPE_P (decl))
6193 note_debug_info_needed (DECL_CONTEXT (decl));
6194 #endif
6196 if ((DECL_EXTERNAL (decl) || TREE_STATIC (decl))
6197 && DECL_SIZE (decl) != NULL_TREE
6198 && ! TREE_CONSTANT (DECL_SIZE (decl)))
6200 if (TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST
6201 && !DECL_LOCAL_DECL_P (decl))
6202 constant_expression_warning (DECL_SIZE (decl));
6203 else
6205 error_at (DECL_SOURCE_LOCATION (decl),
6206 "storage size of %qD isn%'t constant", decl);
6207 TREE_TYPE (decl) = error_mark_node;
6208 type = error_mark_node;
6212 /* If the final element initializes a flexible array field, add the size of
6213 that initializer to DECL's size. */
6214 if (type != error_mark_node
6215 && DECL_INITIAL (decl)
6216 && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
6217 && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl)))
6218 && DECL_SIZE (decl) != NULL_TREE
6219 && TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST
6220 && TYPE_SIZE (type) != NULL_TREE
6221 && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST
6222 && tree_int_cst_equal (DECL_SIZE (decl), TYPE_SIZE (type)))
6224 constructor_elt &elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ();
6225 if (elt.index)
6227 tree itype = TREE_TYPE (elt.index);
6228 tree vtype = TREE_TYPE (elt.value);
6229 if (TREE_CODE (itype) == ARRAY_TYPE
6230 && TYPE_DOMAIN (itype) == NULL
6231 && TREE_CODE (vtype) == ARRAY_TYPE
6232 && COMPLETE_TYPE_P (vtype))
6234 DECL_SIZE (decl)
6235 = size_binop (PLUS_EXPR, DECL_SIZE (decl), TYPE_SIZE (vtype));
6236 DECL_SIZE_UNIT (decl)
6237 = size_binop (PLUS_EXPR, DECL_SIZE_UNIT (decl),
6238 TYPE_SIZE_UNIT (vtype));
6244 /* If a local static variable is declared in an inline function, or if
6245 we have a weak definition, we must endeavor to create only one
6246 instance of the variable at link-time. */
6248 void
6249 maybe_commonize_var (tree decl)
6251 /* Don't mess with __FUNCTION__ and similar. */
6252 if (DECL_ARTIFICIAL (decl))
6253 return;
6255 /* Static data in a function with comdat linkage also has comdat
6256 linkage. */
6257 if ((TREE_STATIC (decl)
6258 && DECL_FUNCTION_SCOPE_P (decl)
6259 && vague_linkage_p (DECL_CONTEXT (decl)))
6260 || (TREE_PUBLIC (decl) && DECL_INLINE_VAR_P (decl)))
6262 if (flag_weak)
6264 /* With weak symbols, we simply make the variable COMDAT;
6265 that will cause copies in multiple translations units to
6266 be merged. */
6267 comdat_linkage (decl);
6269 else
6271 if (DECL_INITIAL (decl) == NULL_TREE
6272 || DECL_INITIAL (decl) == error_mark_node)
6274 /* Without weak symbols, we can use COMMON to merge
6275 uninitialized variables. */
6276 TREE_PUBLIC (decl) = 1;
6277 DECL_COMMON (decl) = 1;
6279 else
6281 /* While for initialized variables, we must use internal
6282 linkage -- which means that multiple copies will not
6283 be merged. */
6284 TREE_PUBLIC (decl) = 0;
6285 DECL_COMMON (decl) = 0;
6286 DECL_INTERFACE_KNOWN (decl) = 1;
6287 const char *msg;
6288 if (DECL_INLINE_VAR_P (decl))
6289 msg = G_("sorry: semantics of inline variable "
6290 "%q#D are wrong (you%'ll wind up with "
6291 "multiple copies)");
6292 else
6293 msg = G_("sorry: semantics of inline function "
6294 "static data %q#D are wrong (you%'ll wind "
6295 "up with multiple copies)");
6296 if (warning_at (DECL_SOURCE_LOCATION (decl), 0,
6297 msg, decl))
6298 inform (DECL_SOURCE_LOCATION (decl),
6299 "you can work around this by removing the initializer");
6305 /* Issue an error message if DECL is an uninitialized const variable.
6306 CONSTEXPR_CONTEXT_P is true when the function is called in a constexpr
6307 context from potential_constant_expression. Returns true if all is well,
6308 false otherwise. */
6310 bool
6311 check_for_uninitialized_const_var (tree decl, bool constexpr_context_p,
6312 tsubst_flags_t complain)
6314 tree type = strip_array_types (TREE_TYPE (decl));
6316 /* ``Unless explicitly declared extern, a const object does not have
6317 external linkage and must be initialized. ($8.4; $12.1)'' ARM
6318 7.1.6 */
6319 if (VAR_P (decl)
6320 && !TYPE_REF_P (type)
6321 && (CP_TYPE_CONST_P (type)
6322 /* C++20 permits trivial default initialization in constexpr
6323 context (P1331R2). */
6324 || (cxx_dialect < cxx20
6325 && (constexpr_context_p
6326 || var_in_constexpr_fn (decl))))
6327 && !DECL_NONTRIVIALLY_INITIALIZED_P (decl))
6329 tree field = default_init_uninitialized_part (type);
6330 if (!field)
6331 return true;
6333 bool show_notes = true;
6335 if (!constexpr_context_p || cxx_dialect >= cxx20)
6337 if (CP_TYPE_CONST_P (type))
6339 if (complain & tf_error)
6340 show_notes = permerror (DECL_SOURCE_LOCATION (decl),
6341 "uninitialized %<const %D%>", decl);
6343 else
6345 if (!is_instantiation_of_constexpr (current_function_decl)
6346 && (complain & tf_error))
6347 error_at (DECL_SOURCE_LOCATION (decl),
6348 "uninitialized variable %qD in %<constexpr%> "
6349 "function", decl);
6350 else
6351 show_notes = false;
6352 cp_function_chain->invalid_constexpr = true;
6355 else if (complain & tf_error)
6356 error_at (DECL_SOURCE_LOCATION (decl),
6357 "uninitialized variable %qD in %<constexpr%> context",
6358 decl);
6360 if (show_notes && CLASS_TYPE_P (type) && (complain & tf_error))
6362 tree defaulted_ctor;
6364 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)),
6365 "%q#T has no user-provided default constructor", type);
6366 defaulted_ctor = in_class_defaulted_default_constructor (type);
6367 if (defaulted_ctor)
6368 inform (DECL_SOURCE_LOCATION (defaulted_ctor),
6369 "constructor is not user-provided because it is "
6370 "explicitly defaulted in the class body");
6371 inform (DECL_SOURCE_LOCATION (field),
6372 "and the implicitly-defined constructor does not "
6373 "initialize %q#D", field);
6376 return false;
6379 return true;
6382 /* Structure holding the current initializer being processed by reshape_init.
6383 CUR is a pointer to the current element being processed, END is a pointer
6384 after the last element present in the initializer. */
6385 struct reshape_iter
6387 constructor_elt *cur;
6388 constructor_elt *end;
6391 static tree reshape_init_r (tree, reshape_iter *, tree, tsubst_flags_t);
6393 /* FIELD is an element of TYPE_FIELDS or NULL. In the former case, the value
6394 returned is the next FIELD_DECL (possibly FIELD itself) that can be
6395 initialized as if for an aggregate class. If there are no more such fields,
6396 the return value will be NULL. */
6398 tree
6399 next_aggregate_field (tree field)
6401 while (field
6402 && (TREE_CODE (field) != FIELD_DECL
6403 || DECL_UNNAMED_BIT_FIELD (field)
6404 || (DECL_ARTIFICIAL (field)
6405 /* In C++17, aggregates can have bases. */
6406 && !(cxx_dialect >= cxx17 && DECL_FIELD_IS_BASE (field)))))
6407 field = DECL_CHAIN (field);
6409 return field;
6412 /* FIELD is an element of TYPE_FIELDS or NULL. In the former case, the value
6413 returned is the next FIELD_DECL (possibly FIELD itself) that corresponds
6414 to a subobject. If there are no more such fields, the return value will be
6415 NULL. */
6417 tree
6418 next_subobject_field (tree field)
6420 while (field
6421 && (TREE_CODE (field) != FIELD_DECL
6422 || DECL_UNNAMED_BIT_FIELD (field)
6423 || (DECL_ARTIFICIAL (field)
6424 && !DECL_FIELD_IS_BASE (field)
6425 && !DECL_VIRTUAL_P (field))))
6426 field = DECL_CHAIN (field);
6428 return field;
6431 /* Return true for [dcl.init.list] direct-list-initialization from
6432 single element of enumeration with a fixed underlying type. */
6434 bool
6435 is_direct_enum_init (tree type, tree init)
6437 if (cxx_dialect >= cxx17
6438 && TREE_CODE (type) == ENUMERAL_TYPE
6439 && ENUM_FIXED_UNDERLYING_TYPE_P (type)
6440 && TREE_CODE (init) == CONSTRUCTOR
6441 && CONSTRUCTOR_IS_DIRECT_INIT (init)
6442 && CONSTRUCTOR_NELTS (init) == 1
6443 /* DR 2374: The single element needs to be implicitly
6444 convertible to the underlying type of the enum. */
6445 && can_convert_arg (ENUM_UNDERLYING_TYPE (type),
6446 TREE_TYPE (CONSTRUCTOR_ELT (init, 0)->value),
6447 CONSTRUCTOR_ELT (init, 0)->value,
6448 LOOKUP_IMPLICIT, tf_none))
6449 return true;
6450 return false;
6453 /* Subroutine of reshape_init_array and reshape_init_vector, which does
6454 the actual work. ELT_TYPE is the element type of the array. MAX_INDEX is an
6455 INTEGER_CST representing the size of the array minus one (the maximum index),
6456 or NULL_TREE if the array was declared without specifying the size. D is
6457 the iterator within the constructor. */
6459 static tree
6460 reshape_init_array_1 (tree elt_type, tree max_index, reshape_iter *d,
6461 tree first_initializer_p, tsubst_flags_t complain)
6463 tree new_init;
6464 bool sized_array_p = (max_index && TREE_CONSTANT (max_index));
6465 unsigned HOST_WIDE_INT max_index_cst = 0;
6466 unsigned HOST_WIDE_INT index;
6468 /* The initializer for an array is always a CONSTRUCTOR. If this is the
6469 outermost CONSTRUCTOR and the element type is non-aggregate, we don't need
6470 to build a new one. But don't reuse if not complaining; if this is
6471 tentative, we might also reshape to another type (95319). */
6472 bool reuse = (first_initializer_p
6473 && (complain & tf_error)
6474 && !CP_AGGREGATE_TYPE_P (elt_type)
6475 && !TREE_SIDE_EFFECTS (first_initializer_p));
6476 if (reuse)
6477 new_init = first_initializer_p;
6478 else
6479 new_init = build_constructor (init_list_type_node, NULL);
6481 if (sized_array_p)
6483 /* Minus 1 is used for zero sized arrays. */
6484 if (integer_all_onesp (max_index))
6485 return new_init;
6487 if (tree_fits_uhwi_p (max_index))
6488 max_index_cst = tree_to_uhwi (max_index);
6489 /* sizetype is sign extended, not zero extended. */
6490 else
6491 max_index_cst = tree_to_uhwi (fold_convert (size_type_node, max_index));
6494 /* Loop until there are no more initializers. */
6495 for (index = 0;
6496 d->cur != d->end && (!sized_array_p || index <= max_index_cst);
6497 ++index)
6499 tree elt_init;
6500 constructor_elt *old_cur = d->cur;
6502 check_array_designated_initializer (d->cur, index);
6503 elt_init = reshape_init_r (elt_type, d,
6504 /*first_initializer_p=*/NULL_TREE,
6505 complain);
6506 if (elt_init == error_mark_node)
6507 return error_mark_node;
6508 tree idx = size_int (index);
6509 if (reuse)
6511 old_cur->index = idx;
6512 old_cur->value = elt_init;
6514 else
6515 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
6516 idx, elt_init);
6517 if (!TREE_CONSTANT (elt_init))
6518 TREE_CONSTANT (new_init) = false;
6520 /* This can happen with an invalid initializer (c++/54501). */
6521 if (d->cur == old_cur && !sized_array_p)
6522 break;
6525 return new_init;
6528 /* Subroutine of reshape_init_r, processes the initializers for arrays.
6529 Parameters are the same of reshape_init_r. */
6531 static tree
6532 reshape_init_array (tree type, reshape_iter *d, tree first_initializer_p,
6533 tsubst_flags_t complain)
6535 tree max_index = NULL_TREE;
6537 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
6539 if (TYPE_DOMAIN (type))
6540 max_index = array_type_nelts (type);
6542 return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6543 first_initializer_p, complain);
6546 /* Subroutine of reshape_init_r, processes the initializers for vectors.
6547 Parameters are the same of reshape_init_r. */
6549 static tree
6550 reshape_init_vector (tree type, reshape_iter *d, tsubst_flags_t complain)
6552 tree max_index = NULL_TREE;
6554 gcc_assert (VECTOR_TYPE_P (type));
6556 if (COMPOUND_LITERAL_P (d->cur->value))
6558 tree value = d->cur->value;
6559 if (!same_type_p (TREE_TYPE (value), type))
6561 if (complain & tf_error)
6562 error ("invalid type %qT as initializer for a vector of type %qT",
6563 TREE_TYPE (d->cur->value), type);
6564 value = error_mark_node;
6566 ++d->cur;
6567 return value;
6570 /* For a vector, we initialize it as an array of the appropriate size. */
6571 if (VECTOR_TYPE_P (type))
6572 max_index = size_int (TYPE_VECTOR_SUBPARTS (type) - 1);
6574 return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6575 NULL_TREE, complain);
6578 /* Subroutine of reshape_init*: We're initializing an element with TYPE from
6579 INIT, in isolation from any designator or other initializers. */
6581 static tree
6582 reshape_single_init (tree type, tree init, tsubst_flags_t complain)
6584 /* We could also implement this by wrapping init in a new CONSTRUCTOR and
6585 calling reshape_init, but this way can just live on the stack. */
6586 constructor_elt elt = { /*index=*/NULL_TREE, init };
6587 reshape_iter iter = { &elt, &elt + 1 };
6588 return reshape_init_r (type, &iter,
6589 /*first_initializer_p=*/NULL_TREE,
6590 complain);
6593 /* Subroutine of reshape_init_r, processes the initializers for classes
6594 or union. Parameters are the same of reshape_init_r. */
6596 static tree
6597 reshape_init_class (tree type, reshape_iter *d, bool first_initializer_p,
6598 tsubst_flags_t complain)
6600 tree field;
6601 tree new_init;
6603 gcc_assert (CLASS_TYPE_P (type));
6605 /* The initializer for a class is always a CONSTRUCTOR. */
6606 new_init = build_constructor (init_list_type_node, NULL);
6608 int binfo_idx = -1;
6609 tree binfo = TYPE_BINFO (type);
6610 tree base_binfo = NULL_TREE;
6611 if (cxx_dialect >= cxx17 && uses_template_parms (type))
6613 /* We get here from maybe_aggr_guide for C++20 class template argument
6614 deduction. In this case we need to look through the binfo because a
6615 template doesn't have base fields. */
6616 binfo_idx = 0;
6617 BINFO_BASE_ITERATE (binfo, binfo_idx, base_binfo);
6619 if (base_binfo)
6620 field = base_binfo;
6621 else
6622 field = next_aggregate_field (TYPE_FIELDS (type));
6624 if (!field)
6626 /* [dcl.init.aggr]
6628 An initializer for an aggregate member that is an
6629 empty class shall have the form of an empty
6630 initializer-list {}. */
6631 if (!first_initializer_p)
6633 if (complain & tf_error)
6634 error ("initializer for %qT must be brace-enclosed", type);
6635 return error_mark_node;
6637 return new_init;
6640 /* For C++20 CTAD, handle pack expansions in the base list. */
6641 tree last_was_pack_expansion = NULL_TREE;
6643 /* Loop through the initializable fields, gathering initializers. */
6644 while (d->cur != d->end)
6646 tree field_init;
6647 constructor_elt *old_cur = d->cur;
6648 bool direct_desig = false;
6650 /* Handle C++20 designated initializers. */
6651 if (d->cur->index)
6653 if (d->cur->index == error_mark_node)
6654 return error_mark_node;
6656 if (TREE_CODE (d->cur->index) == FIELD_DECL)
6658 /* We already reshaped this; we should have returned early from
6659 reshape_init. */
6660 gcc_checking_assert (false);
6661 if (field != d->cur->index)
6663 if (tree id = DECL_NAME (d->cur->index))
6664 gcc_checking_assert (d->cur->index
6665 == get_class_binding (type, id));
6666 field = d->cur->index;
6669 else if (TREE_CODE (d->cur->index) == IDENTIFIER_NODE)
6671 field = get_class_binding (type, d->cur->index);
6672 direct_desig = true;
6674 else
6676 if (complain & tf_error)
6677 error ("%<[%E] =%> used in a GNU-style designated initializer"
6678 " for class %qT", d->cur->index, type);
6679 return error_mark_node;
6682 if (!field && ANON_AGGR_TYPE_P (type))
6683 /* Apparently the designator isn't for a member of this anonymous
6684 struct, so head back to the enclosing class. */
6685 break;
6687 if (!field || TREE_CODE (field) != FIELD_DECL)
6689 if (complain & tf_error)
6690 error ("%qT has no non-static data member named %qD", type,
6691 d->cur->index);
6692 return error_mark_node;
6695 /* If the element is an anonymous union object and the initializer
6696 list is a designated-initializer-list, the anonymous union object
6697 is initialized by the designated-initializer-list { D }, where D
6698 is the designated-initializer-clause naming a member of the
6699 anonymous union object. */
6700 tree ictx = DECL_CONTEXT (field);
6701 if (!same_type_ignoring_top_level_qualifiers_p (ictx, type))
6703 /* Find the anon aggr that is a direct member of TYPE. */
6704 while (ANON_AGGR_TYPE_P (ictx))
6706 tree cctx = TYPE_CONTEXT (ictx);
6707 if (same_type_ignoring_top_level_qualifiers_p (cctx, type))
6708 goto found;
6709 ictx = cctx;
6712 /* Not found, e.g. FIELD is a member of a base class. */
6713 if (complain & tf_error)
6714 error ("%qD is not a direct member of %qT", field, type);
6715 return error_mark_node;
6717 found:
6718 /* Now find the TYPE member with that anon aggr type. */
6719 tree aafield = TYPE_FIELDS (type);
6720 for (; aafield; aafield = TREE_CHAIN (aafield))
6721 if (TREE_TYPE (aafield) == ictx)
6722 break;
6723 gcc_assert (aafield);
6724 field = aafield;
6725 direct_desig = false;
6729 /* If we processed all the member of the class, we are done. */
6730 if (!field)
6731 break;
6733 last_was_pack_expansion = (PACK_EXPANSION_P (TREE_TYPE (field))
6734 ? field : NULL_TREE);
6735 if (last_was_pack_expansion)
6736 /* Each non-trailing aggregate element that is a pack expansion is
6737 assumed to correspond to no elements of the initializer list. */
6738 goto continue_;
6740 if (direct_desig)
6742 /* The designated field F is initialized from this one element.
6744 Note that we don't want to do this if we found the designator
6745 inside an anon aggr above; we use the normal code to implement:
6747 "If the element is an anonymous union member and the initializer
6748 list is a brace-enclosed designated- initializer-list, the element
6749 is initialized by the designated-initializer-list { D }, where D
6750 is the designated- initializer-clause naming a member of the
6751 anonymous union member." */
6752 field_init = reshape_single_init (TREE_TYPE (field),
6753 d->cur->value, complain);
6754 d->cur++;
6756 else
6757 field_init = reshape_init_r (TREE_TYPE (field), d,
6758 /*first_initializer_p=*/NULL_TREE,
6759 complain);
6761 if (field_init == error_mark_node)
6762 return error_mark_node;
6764 if (d->cur == old_cur && d->cur->index)
6766 /* This can happen with an invalid initializer for a flexible
6767 array member (c++/54441). */
6768 if (complain & tf_error)
6769 error ("invalid initializer for %q#D", field);
6770 return error_mark_node;
6773 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init), field, field_init);
6775 /* [dcl.init.aggr]
6777 When a union is initialized with a brace-enclosed
6778 initializer, the braces shall only contain an
6779 initializer for the first member of the union. */
6780 if (TREE_CODE (type) == UNION_TYPE)
6781 break;
6783 continue_:
6784 if (base_binfo)
6786 if (BINFO_BASE_ITERATE (binfo, ++binfo_idx, base_binfo))
6787 field = base_binfo;
6788 else
6789 field = next_aggregate_field (TYPE_FIELDS (type));
6791 else
6792 field = next_aggregate_field (DECL_CHAIN (field));
6795 /* A trailing aggregate element that is a pack expansion is assumed to
6796 correspond to all remaining elements of the initializer list (if any). */
6797 if (last_was_pack_expansion)
6799 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
6800 last_was_pack_expansion, d->cur->value);
6801 while (d->cur != d->end)
6802 d->cur++;
6805 return new_init;
6808 /* Subroutine of reshape_init_r. We're in a context where C99 initializer
6809 designators are not valid; either complain or return true to indicate
6810 that reshape_init_r should return error_mark_node. */
6812 static bool
6813 has_designator_problem (reshape_iter *d, tsubst_flags_t complain)
6815 if (d->cur->index)
6817 if (complain & tf_error)
6818 error_at (cp_expr_loc_or_input_loc (d->cur->index),
6819 "C99 designator %qE outside aggregate initializer",
6820 d->cur->index);
6821 else
6822 return true;
6824 return false;
6827 /* Subroutine of reshape_init, which processes a single initializer (part of
6828 a CONSTRUCTOR). TYPE is the type of the variable being initialized, D is the
6829 iterator within the CONSTRUCTOR which points to the initializer to process.
6830 If this is the first initializer of the outermost CONSTRUCTOR node,
6831 FIRST_INITIALIZER_P is that CONSTRUCTOR; otherwise, it is NULL_TREE. */
6833 static tree
6834 reshape_init_r (tree type, reshape_iter *d, tree first_initializer_p,
6835 tsubst_flags_t complain)
6837 tree init = d->cur->value;
6839 if (error_operand_p (init))
6840 return error_mark_node;
6842 if (first_initializer_p && !CP_AGGREGATE_TYPE_P (type)
6843 && has_designator_problem (d, complain))
6844 return error_mark_node;
6846 tree stripped_init = tree_strip_any_location_wrapper (init);
6848 if (TREE_CODE (type) == COMPLEX_TYPE)
6850 /* A complex type can be initialized from one or two initializers,
6851 but braces are not elided. */
6852 d->cur++;
6853 if (BRACE_ENCLOSED_INITIALIZER_P (stripped_init))
6855 if (CONSTRUCTOR_NELTS (stripped_init) > 2)
6857 if (complain & tf_error)
6858 error ("too many initializers for %qT", type);
6859 else
6860 return error_mark_node;
6863 else if (first_initializer_p && d->cur != d->end)
6865 vec<constructor_elt, va_gc> *v = 0;
6866 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
6867 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, d->cur->value);
6868 if (has_designator_problem (d, complain))
6869 return error_mark_node;
6870 d->cur++;
6871 init = build_constructor (init_list_type_node, v);
6873 return init;
6876 /* A non-aggregate type is always initialized with a single
6877 initializer. */
6878 if (!CP_AGGREGATE_TYPE_P (type)
6879 /* As is an array with dependent bound, which we can see
6880 during C++20 aggregate CTAD. */
6881 || (cxx_dialect >= cxx20
6882 && TREE_CODE (type) == ARRAY_TYPE
6883 && uses_template_parms (TYPE_DOMAIN (type))))
6885 /* It is invalid to initialize a non-aggregate type with a
6886 brace-enclosed initializer before C++0x.
6887 We need to check for BRACE_ENCLOSED_INITIALIZER_P here because
6888 of g++.old-deja/g++.mike/p7626.C: a pointer-to-member constant is
6889 a CONSTRUCTOR (with a record type). */
6890 if (TREE_CODE (stripped_init) == CONSTRUCTOR
6891 /* Don't complain about a capture-init. */
6892 && !CONSTRUCTOR_IS_DIRECT_INIT (stripped_init)
6893 && BRACE_ENCLOSED_INITIALIZER_P (stripped_init)) /* p7626.C */
6895 if (SCALAR_TYPE_P (type))
6897 if (cxx_dialect < cxx11)
6899 if (complain & tf_error)
6900 error ("braces around scalar initializer for type %qT",
6901 type);
6902 init = error_mark_node;
6904 else if (first_initializer_p
6905 || (CONSTRUCTOR_NELTS (stripped_init) > 0
6906 && (BRACE_ENCLOSED_INITIALIZER_P
6907 (CONSTRUCTOR_ELT (stripped_init,0)->value))))
6909 if (complain & tf_error)
6910 error ("too many braces around scalar initializer "
6911 "for type %qT", type);
6912 init = error_mark_node;
6915 else
6916 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
6919 d->cur++;
6920 return init;
6923 /* "If T is a class type and the initializer list has a single element of
6924 type cv U, where U is T or a class derived from T, the object is
6925 initialized from that element." Even if T is an aggregate. */
6926 if (cxx_dialect >= cxx11 && (CLASS_TYPE_P (type) || VECTOR_TYPE_P (type))
6927 && first_initializer_p
6928 /* But not if it's a designated init. */
6929 && !d->cur->index
6930 && d->end - d->cur == 1
6931 && reference_related_p (type, TREE_TYPE (init)))
6933 d->cur++;
6934 return init;
6937 /* [dcl.init.aggr]
6939 All implicit type conversions (clause _conv_) are considered when
6940 initializing the aggregate member with an initializer from an
6941 initializer-list. If the initializer can initialize a member,
6942 the member is initialized. Otherwise, if the member is itself a
6943 non-empty subaggregate, brace elision is assumed and the
6944 initializer is considered for the initialization of the first
6945 member of the subaggregate. */
6946 if ((TREE_CODE (init) != CONSTRUCTOR || COMPOUND_LITERAL_P (init))
6947 /* But don't try this for the first initializer, since that would be
6948 looking through the outermost braces; A a2 = { a1 }; is not a
6949 valid aggregate initialization. */
6950 && !first_initializer_p
6951 && (same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (init))
6952 || can_convert_arg (type, TREE_TYPE (init), init, LOOKUP_NORMAL,
6953 complain)))
6955 d->cur++;
6956 return init;
6959 /* [dcl.init.string]
6961 A char array (whether plain char, signed char, or unsigned char)
6962 can be initialized by a string-literal (optionally enclosed in
6963 braces); a wchar_t array can be initialized by a wide
6964 string-literal (optionally enclosed in braces). */
6965 if (TREE_CODE (type) == ARRAY_TYPE
6966 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type))))
6968 tree str_init = init;
6969 tree stripped_str_init = stripped_init;
6970 reshape_iter stripd = {};
6972 /* Strip one level of braces if and only if they enclose a single
6973 element (as allowed by [dcl.init.string]). */
6974 if (!first_initializer_p
6975 && TREE_CODE (stripped_str_init) == CONSTRUCTOR
6976 && CONSTRUCTOR_NELTS (stripped_str_init) == 1)
6978 stripd.cur = CONSTRUCTOR_ELT (stripped_str_init, 0);
6979 str_init = stripd.cur->value;
6980 stripped_str_init = tree_strip_any_location_wrapper (str_init);
6983 /* If it's a string literal, then it's the initializer for the array
6984 as a whole. Otherwise, continue with normal initialization for
6985 array types (one value per array element). */
6986 if (TREE_CODE (stripped_str_init) == STRING_CST)
6988 if ((first_initializer_p && has_designator_problem (d, complain))
6989 || (stripd.cur && has_designator_problem (&stripd, complain)))
6990 return error_mark_node;
6991 d->cur++;
6992 return str_init;
6996 /* The following cases are about aggregates. If we are not within a full
6997 initializer already, and there is not a CONSTRUCTOR, it means that there
6998 is a missing set of braces (that is, we are processing the case for
6999 which reshape_init exists). */
7000 bool braces_elided_p = false;
7001 if (!first_initializer_p)
7003 if (TREE_CODE (stripped_init) == CONSTRUCTOR)
7005 tree init_type = TREE_TYPE (init);
7006 if (init_type && TYPE_PTRMEMFUNC_P (init_type))
7007 /* There is no need to call reshape_init for pointer-to-member
7008 function initializers, as they are always constructed correctly
7009 by the front end. Here we have e.g. {.__pfn=0B, .__delta=0},
7010 which is missing outermost braces. We should warn below, and
7011 one of the routines below will wrap it in additional { }. */;
7012 /* For a nested compound literal, proceed to specialized routines,
7013 to handle initialization of arrays and similar. */
7014 else if (COMPOUND_LITERAL_P (stripped_init))
7015 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
7016 /* If we have an unresolved designator, we need to find the member it
7017 designates within TYPE, so proceed to the routines below. For
7018 FIELD_DECL or INTEGER_CST designators, we're already initializing
7019 the designated element. */
7020 else if (d->cur->index
7021 && TREE_CODE (d->cur->index) == IDENTIFIER_NODE)
7022 /* Brace elision with designators is only permitted for anonymous
7023 aggregates. */
7024 gcc_checking_assert (ANON_AGGR_TYPE_P (type));
7025 /* A CONSTRUCTOR of the target's type is a previously
7026 digested initializer. */
7027 else if (same_type_ignoring_top_level_qualifiers_p (type, init_type))
7029 ++d->cur;
7030 return init;
7032 else
7034 /* Something that hasn't been reshaped yet. */
7035 ++d->cur;
7036 gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
7037 return reshape_init (type, init, complain);
7041 if (complain & tf_warning)
7042 warning (OPT_Wmissing_braces,
7043 "missing braces around initializer for %qT",
7044 type);
7045 braces_elided_p = true;
7048 /* Dispatch to specialized routines. */
7049 tree new_init;
7050 if (CLASS_TYPE_P (type))
7051 new_init = reshape_init_class (type, d, first_initializer_p, complain);
7052 else if (TREE_CODE (type) == ARRAY_TYPE)
7053 new_init = reshape_init_array (type, d, first_initializer_p, complain);
7054 else if (VECTOR_TYPE_P (type))
7055 new_init = reshape_init_vector (type, d, complain);
7056 else
7057 gcc_unreachable();
7059 if (braces_elided_p
7060 && TREE_CODE (new_init) == CONSTRUCTOR)
7061 CONSTRUCTOR_BRACES_ELIDED_P (new_init) = true;
7063 return new_init;
7066 /* Undo the brace-elision allowed by [dcl.init.aggr] in a
7067 brace-enclosed aggregate initializer.
7069 INIT is the CONSTRUCTOR containing the list of initializers describing
7070 a brace-enclosed initializer for an entity of the indicated aggregate TYPE.
7071 It may not presently match the shape of the TYPE; for example:
7073 struct S { int a; int b; };
7074 struct S a[] = { 1, 2, 3, 4 };
7076 Here INIT will hold a vector of four elements, rather than a
7077 vector of two elements, each itself a vector of two elements. This
7078 routine transforms INIT from the former form into the latter. The
7079 revised CONSTRUCTOR node is returned. */
7081 tree
7082 reshape_init (tree type, tree init, tsubst_flags_t complain)
7084 vec<constructor_elt, va_gc> *v;
7085 reshape_iter d;
7086 tree new_init;
7088 gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (init));
7090 v = CONSTRUCTOR_ELTS (init);
7092 /* An empty constructor does not need reshaping, and it is always a valid
7093 initializer. */
7094 if (vec_safe_is_empty (v))
7095 return init;
7097 if ((*v)[0].index && TREE_CODE ((*v)[0].index) == FIELD_DECL)
7098 /* Already reshaped. */
7099 return init;
7101 /* Brace elision is not performed for a CONSTRUCTOR representing
7102 parenthesized aggregate initialization. */
7103 if (CONSTRUCTOR_IS_PAREN_INIT (init))
7105 tree elt = (*v)[0].value;
7106 /* If we're initializing a char array from a string-literal that is
7107 enclosed in braces, unwrap it here. */
7108 if (TREE_CODE (type) == ARRAY_TYPE
7109 && vec_safe_length (v) == 1
7110 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
7111 && TREE_CODE (tree_strip_any_location_wrapper (elt)) == STRING_CST)
7112 return elt;
7113 return init;
7116 /* Handle [dcl.init.list] direct-list-initialization from
7117 single element of enumeration with a fixed underlying type. */
7118 if (is_direct_enum_init (type, init))
7120 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
7121 type = cv_unqualified (type);
7122 if (check_narrowing (ENUM_UNDERLYING_TYPE (type), elt, complain))
7124 warning_sentinel w (warn_useless_cast);
7125 warning_sentinel w2 (warn_ignored_qualifiers);
7126 return cp_build_c_cast (input_location, type, elt,
7127 tf_warning_or_error);
7129 else
7130 return error_mark_node;
7133 /* Recurse on this CONSTRUCTOR. */
7134 d.cur = &(*v)[0];
7135 d.end = d.cur + v->length ();
7137 new_init = reshape_init_r (type, &d, init, complain);
7138 if (new_init == error_mark_node)
7139 return error_mark_node;
7141 /* Make sure all the element of the constructor were used. Otherwise,
7142 issue an error about exceeding initializers. */
7143 if (d.cur != d.end)
7145 if (complain & tf_error)
7146 error ("too many initializers for %qT", type);
7147 return error_mark_node;
7150 if (CONSTRUCTOR_IS_DIRECT_INIT (init)
7151 && BRACE_ENCLOSED_INITIALIZER_P (new_init))
7152 CONSTRUCTOR_IS_DIRECT_INIT (new_init) = true;
7153 if (CONSTRUCTOR_IS_DESIGNATED_INIT (init)
7154 && BRACE_ENCLOSED_INITIALIZER_P (new_init))
7155 CONSTRUCTOR_IS_DESIGNATED_INIT (new_init) = true;
7157 return new_init;
7160 /* Verify array initializer. Returns true if errors have been reported. */
7162 bool
7163 check_array_initializer (tree decl, tree type, tree init)
7165 tree element_type = TREE_TYPE (type);
7167 /* Structured binding when initialized with an array type needs
7168 to have complete type. */
7169 if (decl
7170 && DECL_DECOMPOSITION_P (decl)
7171 && !DECL_DECOMP_BASE (decl)
7172 && !COMPLETE_TYPE_P (type))
7174 error_at (DECL_SOURCE_LOCATION (decl),
7175 "structured binding has incomplete type %qT", type);
7176 TREE_TYPE (decl) = error_mark_node;
7177 return true;
7180 /* The array type itself need not be complete, because the
7181 initializer may tell us how many elements are in the array.
7182 But, the elements of the array must be complete. */
7183 if (!COMPLETE_TYPE_P (complete_type (element_type)))
7185 if (decl)
7186 error_at (DECL_SOURCE_LOCATION (decl),
7187 "elements of array %q#D have incomplete type", decl);
7188 else
7189 error ("elements of array %q#T have incomplete type", type);
7190 return true;
7193 location_t loc = (decl ? location_of (decl) : input_location);
7194 if (!verify_type_context (loc, TCTX_ARRAY_ELEMENT, element_type))
7195 return true;
7197 /* A compound literal can't have variable size. */
7198 if (init && !decl
7199 && ((COMPLETE_TYPE_P (type) && !TREE_CONSTANT (TYPE_SIZE (type)))
7200 || !TREE_CONSTANT (TYPE_SIZE (element_type))))
7202 error ("variable-sized compound literal");
7203 return true;
7205 return false;
7208 /* Subroutine of check_initializer; args are passed down from that function.
7209 Set stmts_are_full_exprs_p to 1 across a call to build_aggr_init. */
7211 static tree
7212 build_aggr_init_full_exprs (tree decl, tree init, int flags)
7215 gcc_assert (stmts_are_full_exprs_p ());
7216 return build_aggr_init (decl, init, flags, tf_warning_or_error);
7219 /* Verify INIT (the initializer for DECL), and record the
7220 initialization in DECL_INITIAL, if appropriate. CLEANUP is as for
7221 grok_reference_init.
7223 If the return value is non-NULL, it is an expression that must be
7224 evaluated dynamically to initialize DECL. */
7226 static tree
7227 check_initializer (tree decl, tree init, int flags, vec<tree, va_gc> **cleanups)
7229 tree type;
7230 tree init_code = NULL;
7231 tree core_type;
7233 /* Things that are going to be initialized need to have complete
7234 type. */
7235 TREE_TYPE (decl) = type = complete_type (TREE_TYPE (decl));
7237 if (DECL_HAS_VALUE_EXPR_P (decl))
7239 /* A variable with DECL_HAS_VALUE_EXPR_P set is just a placeholder,
7240 it doesn't have storage to be initialized. */
7241 gcc_assert (init == NULL_TREE);
7242 return NULL_TREE;
7245 if (type == error_mark_node)
7246 /* We will have already complained. */
7247 return NULL_TREE;
7249 if (TREE_CODE (type) == ARRAY_TYPE)
7251 if (check_array_initializer (decl, type, init))
7252 return NULL_TREE;
7254 else if (!COMPLETE_TYPE_P (type))
7256 error_at (DECL_SOURCE_LOCATION (decl),
7257 "%q#D has incomplete type", decl);
7258 TREE_TYPE (decl) = error_mark_node;
7259 return NULL_TREE;
7261 else
7262 /* There is no way to make a variable-sized class type in GNU C++. */
7263 gcc_assert (TREE_CONSTANT (TYPE_SIZE (type)));
7265 if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
7267 int init_len = CONSTRUCTOR_NELTS (init);
7268 if (SCALAR_TYPE_P (type))
7270 if (init_len == 0)
7272 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
7273 init = build_zero_init (type, NULL_TREE, false);
7275 else if (init_len != 1 && TREE_CODE (type) != COMPLEX_TYPE)
7277 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
7278 "scalar object %qD requires one element in "
7279 "initializer", decl);
7280 TREE_TYPE (decl) = error_mark_node;
7281 return NULL_TREE;
7286 if (TREE_CODE (decl) == CONST_DECL)
7288 gcc_assert (!TYPE_REF_P (type));
7290 DECL_INITIAL (decl) = init;
7292 gcc_assert (init != NULL_TREE);
7293 init = NULL_TREE;
7295 else if (!init && DECL_REALLY_EXTERN (decl))
7297 else if (init || type_build_ctor_call (type)
7298 || TYPE_REF_P (type))
7300 if (TYPE_REF_P (type))
7302 init = grok_reference_init (decl, type, init, flags);
7303 flags |= LOOKUP_ALREADY_DIGESTED;
7305 else if (!init)
7306 check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
7307 tf_warning_or_error);
7308 /* Do not reshape constructors of vectors (they don't need to be
7309 reshaped. */
7310 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
7312 if (is_std_init_list (type))
7314 init = perform_implicit_conversion (type, init,
7315 tf_warning_or_error);
7316 flags |= LOOKUP_ALREADY_DIGESTED;
7318 else if (TYPE_NON_AGGREGATE_CLASS (type))
7320 /* Don't reshape if the class has constructors. */
7321 if (cxx_dialect == cxx98)
7322 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
7323 "in C++98 %qD must be initialized by "
7324 "constructor, not by %<{...}%>",
7325 decl);
7327 else if (VECTOR_TYPE_P (type) && TYPE_VECTOR_OPAQUE (type))
7329 error ("opaque vector types cannot be initialized");
7330 init = error_mark_node;
7332 else
7334 init = reshape_init (type, init, tf_warning_or_error);
7335 flags |= LOOKUP_NO_NARROWING;
7338 /* [dcl.init] "Otherwise, if the destination type is an array, the object
7339 is initialized as follows..." So handle things like
7341 int a[](1, 2, 3);
7343 which is permitted in C++20 by P0960. */
7344 else if (TREE_CODE (init) == TREE_LIST
7345 && TREE_TYPE (init) == NULL_TREE
7346 && TREE_CODE (type) == ARRAY_TYPE
7347 && !DECL_DECOMPOSITION_P (decl)
7348 && (cxx_dialect >= cxx20))
7349 init = do_aggregate_paren_init (init, type);
7350 else if (TREE_CODE (init) == TREE_LIST
7351 && TREE_TYPE (init) != unknown_type_node
7352 && !MAYBE_CLASS_TYPE_P (type))
7354 gcc_assert (TREE_CODE (decl) != RESULT_DECL);
7356 /* We get here with code like `int a (2);' */
7357 init = build_x_compound_expr_from_list (init, ELK_INIT,
7358 tf_warning_or_error);
7361 /* If DECL has an array type without a specific bound, deduce the
7362 array size from the initializer. */
7363 maybe_deduce_size_from_array_init (decl, init);
7364 type = TREE_TYPE (decl);
7365 if (type == error_mark_node)
7366 return NULL_TREE;
7368 if (((type_build_ctor_call (type) || CLASS_TYPE_P (type))
7369 && !(flags & LOOKUP_ALREADY_DIGESTED)
7370 && !(init && BRACE_ENCLOSED_INITIALIZER_P (init)
7371 && CP_AGGREGATE_TYPE_P (type)
7372 && (CLASS_TYPE_P (type)
7373 /* The call to build_aggr_init below could end up
7374 calling build_vec_init, which may break when we
7375 are processing a template. */
7376 || processing_template_decl
7377 || !TYPE_NEEDS_CONSTRUCTING (type)
7378 || type_has_extended_temps (type))))
7379 || (DECL_DECOMPOSITION_P (decl) && TREE_CODE (type) == ARRAY_TYPE))
7381 init_code = build_aggr_init_full_exprs (decl, init, flags);
7383 /* A constructor call is a non-trivial initializer even if
7384 it isn't explicitly written. */
7385 if (TREE_SIDE_EFFECTS (init_code))
7386 DECL_NONTRIVIALLY_INITIALIZED_P (decl) = true;
7388 /* If this is a constexpr initializer, expand_default_init will
7389 have returned an INIT_EXPR rather than a CALL_EXPR. In that
7390 case, pull the initializer back out and pass it down into
7391 store_init_value. */
7392 while (true)
7394 if (TREE_CODE (init_code) == EXPR_STMT
7395 || TREE_CODE (init_code) == STMT_EXPR
7396 || TREE_CODE (init_code) == CONVERT_EXPR)
7397 init_code = TREE_OPERAND (init_code, 0);
7398 else if (TREE_CODE (init_code) == BIND_EXPR)
7399 init_code = BIND_EXPR_BODY (init_code);
7400 else
7401 break;
7403 if (TREE_CODE (init_code) == INIT_EXPR)
7405 /* In C++20, the call to build_aggr_init could have created
7406 an INIT_EXPR with a CONSTRUCTOR as the RHS to handle
7407 A(1, 2). */
7408 tree rhs = TREE_OPERAND (init_code, 1);
7409 if (processing_template_decl && TREE_CODE (rhs) == TARGET_EXPR)
7410 /* Avoid leaking TARGET_EXPR into template trees. */
7411 rhs = build_implicit_conv_flags (type, init, flags);
7412 init = rhs;
7414 init_code = NULL_TREE;
7415 /* Don't call digest_init; it's unnecessary and will complain
7416 about aggregate initialization of non-aggregate classes. */
7417 flags |= LOOKUP_ALREADY_DIGESTED;
7419 else if (DECL_DECLARED_CONSTEXPR_P (decl)
7420 || DECL_DECLARED_CONSTINIT_P (decl))
7422 /* Declared constexpr or constinit, but no suitable initializer;
7423 massage init appropriately so we can pass it into
7424 store_init_value for the error. */
7425 tree new_init = NULL_TREE;
7426 if (!processing_template_decl
7427 && TREE_CODE (init_code) == CALL_EXPR)
7428 new_init = build_cplus_new (type, init_code, tf_none);
7429 else if (CLASS_TYPE_P (type)
7430 && (!init || TREE_CODE (init) == TREE_LIST))
7431 new_init = build_functional_cast (input_location, type,
7432 init, tf_none);
7433 if (new_init)
7435 init = new_init;
7436 if (TREE_CODE (init) == TARGET_EXPR
7437 && !(flags & LOOKUP_ONLYCONVERTING))
7438 TARGET_EXPR_DIRECT_INIT_P (init) = true;
7440 init_code = NULL_TREE;
7442 else
7443 init = NULL_TREE;
7446 if (init && TREE_CODE (init) != TREE_VEC)
7448 init_code = store_init_value (decl, init, cleanups, flags);
7450 if (DECL_INITIAL (decl)
7451 && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
7452 && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl))))
7454 tree elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ().value;
7455 if (TREE_CODE (TREE_TYPE (elt)) == ARRAY_TYPE
7456 && TYPE_SIZE (TREE_TYPE (elt)) == NULL_TREE)
7457 cp_complete_array_type (&TREE_TYPE (elt), elt, false);
7460 if (pedantic && TREE_CODE (type) == ARRAY_TYPE
7461 && DECL_INITIAL (decl)
7462 && TREE_CODE (DECL_INITIAL (decl)) == STRING_CST
7463 && PAREN_STRING_LITERAL_P (DECL_INITIAL (decl)))
7464 warning_at (cp_expr_loc_or_loc (DECL_INITIAL (decl),
7465 DECL_SOURCE_LOCATION (decl)),
7466 0, "array %qD initialized by parenthesized "
7467 "string literal %qE",
7468 decl, DECL_INITIAL (decl));
7469 init = NULL_TREE;
7472 else
7474 if (CLASS_TYPE_P (core_type = strip_array_types (type))
7475 && (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type)
7476 || CLASSTYPE_REF_FIELDS_NEED_INIT (core_type)))
7477 diagnose_uninitialized_cst_or_ref_member (core_type, /*using_new=*/false,
7478 /*complain=*/true);
7480 check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
7481 tf_warning_or_error);
7484 if (init && init != error_mark_node)
7485 init_code = build2 (INIT_EXPR, type, decl, init);
7487 if (init_code && !TREE_SIDE_EFFECTS (init_code)
7488 && init_code != error_mark_node)
7489 init_code = NULL_TREE;
7491 if (init_code)
7493 /* We might have set these in cp_finish_decl. */
7494 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = false;
7495 TREE_CONSTANT (decl) = false;
7498 if (init_code
7499 && DECL_IN_AGGR_P (decl)
7500 && DECL_INITIALIZED_IN_CLASS_P (decl))
7502 static int explained = 0;
7504 if (cxx_dialect < cxx11)
7505 error ("initializer invalid for static member with constructor");
7506 else if (cxx_dialect < cxx17)
7507 error ("non-constant in-class initialization invalid for static "
7508 "member %qD", decl);
7509 else
7510 error ("non-constant in-class initialization invalid for non-inline "
7511 "static member %qD", decl);
7512 if (!explained)
7514 inform (input_location,
7515 "(an out of class initialization is required)");
7516 explained = 1;
7518 return NULL_TREE;
7521 return init_code;
7524 /* If DECL is not a local variable, give it RTL. */
7526 static void
7527 make_rtl_for_nonlocal_decl (tree decl, tree init, const char* asmspec)
7529 int toplev = toplevel_bindings_p ();
7530 int defer_p;
7532 /* Set the DECL_ASSEMBLER_NAME for the object. */
7533 if (asmspec)
7535 /* The `register' keyword, when used together with an
7536 asm-specification, indicates that the variable should be
7537 placed in a particular register. */
7538 if (VAR_P (decl) && DECL_REGISTER (decl))
7540 set_user_assembler_name (decl, asmspec);
7541 DECL_HARD_REGISTER (decl) = 1;
7543 else
7545 if (TREE_CODE (decl) == FUNCTION_DECL
7546 && fndecl_built_in_p (decl, BUILT_IN_NORMAL))
7547 set_builtin_user_assembler_name (decl, asmspec);
7548 set_user_assembler_name (decl, asmspec);
7549 if (DECL_LOCAL_DECL_P (decl))
7550 if (auto ns_decl = DECL_LOCAL_DECL_ALIAS (decl))
7551 /* We have to propagate the name to the ns-alias.
7552 This is horrible, as we're affecting a
7553 possibly-shared decl. Again, a one-true-decl
7554 model breaks down. */
7555 if (ns_decl != error_mark_node)
7556 set_user_assembler_name (ns_decl, asmspec);
7560 /* Handle non-variables up front. */
7561 if (!VAR_P (decl))
7563 rest_of_decl_compilation (decl, toplev, at_eof);
7564 return;
7567 /* If we see a class member here, it should be a static data
7568 member. */
7569 if (DECL_LANG_SPECIFIC (decl) && DECL_IN_AGGR_P (decl))
7571 gcc_assert (TREE_STATIC (decl));
7572 /* An in-class declaration of a static data member should be
7573 external; it is only a declaration, and not a definition. */
7574 if (init == NULL_TREE)
7575 gcc_assert (DECL_EXTERNAL (decl)
7576 || !TREE_PUBLIC (decl));
7579 /* We don't create any RTL for local variables. */
7580 if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
7581 return;
7583 /* We defer emission of local statics until the corresponding
7584 DECL_EXPR is expanded. But with constexpr its function might never
7585 be expanded, so go ahead and tell cgraph about the variable now. */
7586 defer_p = ((DECL_FUNCTION_SCOPE_P (decl)
7587 && !var_in_maybe_constexpr_fn (decl))
7588 || DECL_VIRTUAL_P (decl));
7590 /* Defer template instantiations. */
7591 if (DECL_LANG_SPECIFIC (decl)
7592 && DECL_IMPLICIT_INSTANTIATION (decl))
7593 defer_p = 1;
7595 /* If we're not deferring, go ahead and assemble the variable. */
7596 if (!defer_p)
7597 rest_of_decl_compilation (decl, toplev, at_eof);
7600 /* walk_tree helper for wrap_temporary_cleanups, below. */
7602 static tree
7603 wrap_cleanups_r (tree *stmt_p, int *walk_subtrees, void *data)
7605 /* Stop at types or full-expression boundaries. */
7606 if (TYPE_P (*stmt_p)
7607 || TREE_CODE (*stmt_p) == CLEANUP_POINT_EXPR)
7609 *walk_subtrees = 0;
7610 return NULL_TREE;
7613 if (TREE_CODE (*stmt_p) == TARGET_EXPR)
7615 tree guard = (tree)data;
7616 tree tcleanup = TARGET_EXPR_CLEANUP (*stmt_p);
7618 if (tcleanup && !CLEANUP_EH_ONLY (*stmt_p)
7619 && !expr_noexcept_p (tcleanup, tf_none))
7621 tcleanup = build2 (TRY_CATCH_EXPR, void_type_node, tcleanup, guard);
7622 /* Tell honor_protect_cleanup_actions to handle this as a separate
7623 cleanup. */
7624 TRY_CATCH_IS_CLEANUP (tcleanup) = 1;
7625 TARGET_EXPR_CLEANUP (*stmt_p) = tcleanup;
7629 return NULL_TREE;
7632 /* We're initializing a local variable which has a cleanup GUARD. If there
7633 are any temporaries used in the initializer INIT of this variable, we
7634 need to wrap their cleanups with TRY_CATCH_EXPR (, GUARD) so that the
7635 variable will be cleaned up properly if one of them throws.
7637 Unfortunately, there's no way to express this properly in terms of
7638 nesting, as the regions for the temporaries overlap the region for the
7639 variable itself; if there are two temporaries, the variable needs to be
7640 the first thing destroyed if either of them throws. However, we only
7641 want to run the variable's cleanup if it actually got constructed. So
7642 we need to guard the temporary cleanups with the variable's cleanup if
7643 they are run on the normal path, but not if they are run on the
7644 exceptional path. We implement this by telling
7645 honor_protect_cleanup_actions to strip the variable cleanup from the
7646 exceptional path.
7648 Another approach could be to make the variable cleanup region enclose
7649 initialization, but depend on a flag to indicate that the variable is
7650 initialized; that's effectively what we do for arrays. But the current
7651 approach works fine for non-arrays, and has no code overhead in the usual
7652 case where the temporary destructors are noexcept. */
7654 static void
7655 wrap_temporary_cleanups (tree init, tree guard)
7657 if (TREE_CODE (guard) == BIND_EXPR)
7659 /* An array cleanup region already encloses any temporary cleanups,
7660 don't wrap it around them again. */
7661 gcc_checking_assert (BIND_EXPR_VEC_DTOR (guard));
7662 return;
7664 cp_walk_tree_without_duplicates (&init, wrap_cleanups_r, (void *)guard);
7667 /* Generate code to initialize DECL (a local variable). */
7669 static void
7670 initialize_local_var (tree decl, tree init)
7672 tree type = TREE_TYPE (decl);
7673 tree cleanup;
7674 int already_used;
7676 gcc_assert (VAR_P (decl)
7677 || TREE_CODE (decl) == RESULT_DECL);
7678 gcc_assert (!TREE_STATIC (decl));
7680 if (DECL_SIZE (decl) == NULL_TREE)
7682 /* If we used it already as memory, it must stay in memory. */
7683 DECL_INITIAL (decl) = NULL_TREE;
7684 TREE_ADDRESSABLE (decl) = TREE_USED (decl);
7685 return;
7688 if (type == error_mark_node)
7689 return;
7691 /* Compute and store the initial value. */
7692 already_used = TREE_USED (decl) || TREE_USED (type);
7693 if (TREE_USED (type))
7694 DECL_READ_P (decl) = 1;
7696 /* Generate a cleanup, if necessary. */
7697 cleanup = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
7699 /* Perform the initialization. */
7700 if (init)
7702 tree rinit = (TREE_CODE (init) == INIT_EXPR
7703 ? TREE_OPERAND (init, 1) : NULL_TREE);
7704 if (rinit && !TREE_SIDE_EFFECTS (rinit)
7705 && TREE_OPERAND (init, 0) == decl)
7707 /* Stick simple initializers in DECL_INITIAL so that
7708 -Wno-init-self works (c++/34772). */
7709 DECL_INITIAL (decl) = rinit;
7711 if (warn_init_self && TYPE_REF_P (type))
7713 STRIP_NOPS (rinit);
7714 if (rinit == decl)
7715 warning_at (DECL_SOURCE_LOCATION (decl),
7716 OPT_Winit_self,
7717 "reference %qD is initialized with itself", decl);
7720 else
7722 int saved_stmts_are_full_exprs_p;
7724 /* If we're only initializing a single object, guard the
7725 destructors of any temporaries used in its initializer with
7726 its destructor. */
7727 if (cleanup)
7728 wrap_temporary_cleanups (init, cleanup);
7730 gcc_assert (building_stmt_list_p ());
7731 saved_stmts_are_full_exprs_p = stmts_are_full_exprs_p ();
7732 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
7733 finish_expr_stmt (init);
7734 current_stmt_tree ()->stmts_are_full_exprs_p =
7735 saved_stmts_are_full_exprs_p;
7739 /* Set this to 0 so we can tell whether an aggregate which was
7740 initialized was ever used. Don't do this if it has a
7741 destructor, so we don't complain about the 'resource
7742 allocation is initialization' idiom. Now set
7743 attribute((unused)) on types so decls of that type will be
7744 marked used. (see TREE_USED, above.) */
7745 if (TYPE_NEEDS_CONSTRUCTING (type)
7746 && ! already_used
7747 && TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
7748 && DECL_NAME (decl))
7749 TREE_USED (decl) = 0;
7750 else if (already_used)
7751 TREE_USED (decl) = 1;
7753 if (cleanup)
7754 finish_decl_cleanup (decl, cleanup);
7757 /* DECL is a VAR_DECL for a compiler-generated variable with static
7758 storage duration (like a virtual table) whose initializer is a
7759 compile-time constant. Initialize the variable and provide it to the
7760 back end. */
7762 void
7763 initialize_artificial_var (tree decl, vec<constructor_elt, va_gc> *v)
7765 tree init;
7766 gcc_assert (DECL_ARTIFICIAL (decl));
7767 init = build_constructor (TREE_TYPE (decl), v);
7768 gcc_assert (TREE_CODE (init) == CONSTRUCTOR);
7769 DECL_INITIAL (decl) = init;
7770 DECL_INITIALIZED_P (decl) = 1;
7771 /* Mark the decl as constexpr so that we can access its content
7772 at compile time. */
7773 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
7774 DECL_DECLARED_CONSTEXPR_P (decl) = true;
7775 determine_visibility (decl);
7776 layout_var_decl (decl);
7777 maybe_commonize_var (decl);
7778 make_rtl_for_nonlocal_decl (decl, init, /*asmspec=*/NULL);
7781 /* INIT is the initializer for a variable, as represented by the
7782 parser. Returns true iff INIT is value-dependent. */
7784 static bool
7785 value_dependent_init_p (tree init)
7787 if (TREE_CODE (init) == TREE_LIST)
7788 /* A parenthesized initializer, e.g.: int i (3, 2); ? */
7789 return any_value_dependent_elements_p (init);
7790 else if (TREE_CODE (init) == CONSTRUCTOR)
7791 /* A brace-enclosed initializer, e.g.: int i = { 3 }; ? */
7793 if (dependent_type_p (TREE_TYPE (init)))
7794 return true;
7796 vec<constructor_elt, va_gc> *elts;
7797 size_t nelts;
7798 size_t i;
7800 elts = CONSTRUCTOR_ELTS (init);
7801 nelts = vec_safe_length (elts);
7802 for (i = 0; i < nelts; ++i)
7803 if (value_dependent_init_p ((*elts)[i].value))
7804 return true;
7806 else
7807 /* It must be a simple expression, e.g., int i = 3; */
7808 return value_dependent_expression_p (init);
7810 return false;
7813 // Returns true if a DECL is VAR_DECL with the concept specifier.
7814 static inline bool
7815 is_concept_var (tree decl)
7817 return (VAR_P (decl)
7818 // Not all variables have DECL_LANG_SPECIFIC.
7819 && DECL_LANG_SPECIFIC (decl)
7820 && DECL_DECLARED_CONCEPT_P (decl));
7823 /* A helper function to be called via walk_tree. If any label exists
7824 under *TP, it is (going to be) forced. Set has_forced_label_in_static. */
7826 static tree
7827 notice_forced_label_r (tree *tp, int *walk_subtrees, void *)
7829 if (TYPE_P (*tp))
7830 *walk_subtrees = 0;
7831 if (TREE_CODE (*tp) == LABEL_DECL)
7832 cfun->has_forced_label_in_static = 1;
7833 return NULL_TREE;
7836 /* Return true if DECL has either a trivial destructor, or for C++20
7837 is constexpr and has a constexpr destructor. */
7839 static bool
7840 decl_maybe_constant_destruction (tree decl, tree type)
7842 return (TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
7843 || (cxx_dialect >= cxx20
7844 && VAR_P (decl)
7845 && DECL_DECLARED_CONSTEXPR_P (decl)
7846 && type_has_constexpr_destructor (strip_array_types (type))));
7849 static tree declare_simd_adjust_this (tree *, int *, void *);
7851 /* Helper function of omp_declare_variant_finalize. Finalize one
7852 "omp declare variant base" attribute. Return true if it should be
7853 removed. */
7855 static bool
7856 omp_declare_variant_finalize_one (tree decl, tree attr)
7858 if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
7860 walk_tree (&TREE_VALUE (TREE_VALUE (attr)), declare_simd_adjust_this,
7861 DECL_ARGUMENTS (decl), NULL);
7862 walk_tree (&TREE_PURPOSE (TREE_VALUE (attr)), declare_simd_adjust_this,
7863 DECL_ARGUMENTS (decl), NULL);
7866 tree ctx = TREE_VALUE (TREE_VALUE (attr));
7867 tree simd = omp_get_context_selector (ctx, "construct", "simd");
7868 if (simd)
7870 TREE_VALUE (simd)
7871 = c_omp_declare_simd_clauses_to_numbers (DECL_ARGUMENTS (decl),
7872 TREE_VALUE (simd));
7873 /* FIXME, adjusting simd args unimplemented. */
7874 return true;
7877 tree chain = TREE_CHAIN (TREE_VALUE (attr));
7878 location_t varid_loc
7879 = cp_expr_loc_or_input_loc (TREE_PURPOSE (TREE_CHAIN (chain)));
7880 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
7881 cp_id_kind idk = (cp_id_kind) tree_to_uhwi (TREE_VALUE (chain));
7882 tree variant = TREE_PURPOSE (TREE_VALUE (attr));
7884 location_t save_loc = input_location;
7885 input_location = varid_loc;
7887 releasing_vec args;
7888 tree parm = DECL_ARGUMENTS (decl);
7889 if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
7890 parm = DECL_CHAIN (parm);
7891 for (; parm; parm = DECL_CHAIN (parm))
7892 if (type_dependent_expression_p (parm))
7893 vec_safe_push (args, build_constructor (TREE_TYPE (parm), NULL));
7894 else if (MAYBE_CLASS_TYPE_P (TREE_TYPE (parm)))
7895 vec_safe_push (args, build_local_temp (TREE_TYPE (parm)));
7896 else
7897 vec_safe_push (args, build_zero_cst (TREE_TYPE (parm)));
7899 bool koenig_p = false;
7900 if (idk == CP_ID_KIND_UNQUALIFIED || idk == CP_ID_KIND_TEMPLATE_ID)
7902 if (identifier_p (variant)
7903 /* In C++20, we may need to perform ADL for a template
7904 name. */
7905 || (TREE_CODE (variant) == TEMPLATE_ID_EXPR
7906 && identifier_p (TREE_OPERAND (variant, 0))))
7908 if (!args->is_empty ())
7910 koenig_p = true;
7911 if (!any_type_dependent_arguments_p (args))
7912 variant = perform_koenig_lookup (variant, args,
7913 tf_warning_or_error);
7915 else
7916 variant = unqualified_fn_lookup_error (variant);
7918 else if (!args->is_empty () && is_overloaded_fn (variant))
7920 tree fn = get_first_fn (variant);
7921 fn = STRIP_TEMPLATE (fn);
7922 if (!((TREE_CODE (fn) == USING_DECL && DECL_DEPENDENT_P (fn))
7923 || DECL_FUNCTION_MEMBER_P (fn)
7924 || DECL_LOCAL_DECL_P (fn)))
7926 koenig_p = true;
7927 if (!any_type_dependent_arguments_p (args))
7928 variant = perform_koenig_lookup (variant, args,
7929 tf_warning_or_error);
7934 if (idk == CP_ID_KIND_QUALIFIED)
7935 variant = finish_call_expr (variant, &args, /*disallow_virtual=*/true,
7936 koenig_p, tf_warning_or_error);
7937 else
7938 variant = finish_call_expr (variant, &args, /*disallow_virtual=*/false,
7939 koenig_p, tf_warning_or_error);
7940 if (variant == error_mark_node && !processing_template_decl)
7941 return true;
7943 variant = cp_get_callee_fndecl_nofold (variant);
7944 input_location = save_loc;
7946 if (variant)
7948 const char *varname = IDENTIFIER_POINTER (DECL_NAME (variant));
7949 if (!comptypes (TREE_TYPE (decl), TREE_TYPE (variant), 0))
7951 error_at (varid_loc, "variant %qD and base %qD have incompatible "
7952 "types", variant, decl);
7953 return true;
7955 if (fndecl_built_in_p (variant)
7956 && (startswith (varname, "__builtin_")
7957 || startswith (varname, "__sync_")
7958 || startswith (varname, "__atomic_")))
7960 error_at (varid_loc, "variant %qD is a built-in", variant);
7961 return true;
7963 else
7965 tree construct = omp_get_context_selector (ctx, "construct", NULL);
7966 omp_mark_declare_variant (match_loc, variant, construct);
7967 if (!omp_context_selector_matches (ctx))
7968 return true;
7969 TREE_PURPOSE (TREE_VALUE (attr)) = variant;
7972 else if (!processing_template_decl)
7974 error_at (varid_loc, "could not find variant declaration");
7975 return true;
7978 return false;
7981 /* Helper function, finish up "omp declare variant base" attribute
7982 now that there is a DECL. ATTR is the first "omp declare variant base"
7983 attribute. */
7985 void
7986 omp_declare_variant_finalize (tree decl, tree attr)
7988 size_t attr_len = strlen ("omp declare variant base");
7989 tree *list = &DECL_ATTRIBUTES (decl);
7990 bool remove_all = false;
7991 location_t match_loc = DECL_SOURCE_LOCATION (decl);
7992 if (TREE_CHAIN (TREE_VALUE (attr))
7993 && TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))
7994 && EXPR_HAS_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))))
7995 match_loc = EXPR_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr))));
7996 if (DECL_CONSTRUCTOR_P (decl))
7998 error_at (match_loc, "%<declare variant%> on constructor %qD", decl);
7999 remove_all = true;
8001 else if (DECL_DESTRUCTOR_P (decl))
8003 error_at (match_loc, "%<declare variant%> on destructor %qD", decl);
8004 remove_all = true;
8006 else if (DECL_DEFAULTED_FN (decl))
8008 error_at (match_loc, "%<declare variant%> on defaulted %qD", decl);
8009 remove_all = true;
8011 else if (DECL_DELETED_FN (decl))
8013 error_at (match_loc, "%<declare variant%> on deleted %qD", decl);
8014 remove_all = true;
8016 else if (DECL_VIRTUAL_P (decl))
8018 error_at (match_loc, "%<declare variant%> on virtual %qD", decl);
8019 remove_all = true;
8021 /* This loop is like private_lookup_attribute, except that it works
8022 with tree * rather than tree, as we might want to remove the
8023 attributes that are diagnosed as errorneous. */
8024 while (*list)
8026 tree attr = get_attribute_name (*list);
8027 size_t ident_len = IDENTIFIER_LENGTH (attr);
8028 if (cmp_attribs ("omp declare variant base", attr_len,
8029 IDENTIFIER_POINTER (attr), ident_len))
8031 if (remove_all || omp_declare_variant_finalize_one (decl, *list))
8033 *list = TREE_CHAIN (*list);
8034 continue;
8037 list = &TREE_CHAIN (*list);
8041 /* Finish processing of a declaration;
8042 install its line number and initial value.
8043 If the length of an array type is not known before,
8044 it must be determined now, from the initial value, or it is an error.
8046 INIT is the initializer (if any) for DECL. If INIT_CONST_EXPR_P is
8047 true, then INIT is an integral constant expression.
8049 FLAGS is LOOKUP_ONLYCONVERTING if the = init syntax was used, else 0
8050 if the (init) syntax was used. */
8052 void
8053 cp_finish_decl (tree decl, tree init, bool init_const_expr_p,
8054 tree asmspec_tree, int flags)
8056 tree type;
8057 vec<tree, va_gc> *cleanups = NULL;
8058 const char *asmspec = NULL;
8059 int was_readonly = 0;
8060 bool var_definition_p = false;
8061 tree auto_node;
8063 if (decl == error_mark_node)
8064 return;
8065 else if (! decl)
8067 if (init)
8068 error ("assignment (not initialization) in declaration");
8069 return;
8072 gcc_assert (TREE_CODE (decl) != RESULT_DECL);
8073 /* Parameters are handled by store_parm_decls, not cp_finish_decl. */
8074 gcc_assert (TREE_CODE (decl) != PARM_DECL);
8076 type = TREE_TYPE (decl);
8077 if (type == error_mark_node)
8078 return;
8080 if (VAR_P (decl) && is_copy_initialization (init))
8081 flags |= LOOKUP_ONLYCONVERTING;
8083 /* Warn about register storage specifiers except when in GNU global
8084 or local register variable extension. */
8085 if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec_tree == NULL_TREE)
8087 if (cxx_dialect >= cxx17)
8088 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
8089 "ISO C++17 does not allow %<register%> storage "
8090 "class specifier");
8091 else
8092 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
8093 "%<register%> storage class specifier used");
8096 /* If a name was specified, get the string. */
8097 if (at_namespace_scope_p ())
8098 asmspec_tree = maybe_apply_renaming_pragma (decl, asmspec_tree);
8099 if (asmspec_tree && asmspec_tree != error_mark_node)
8100 asmspec = TREE_STRING_POINTER (asmspec_tree);
8102 bool in_class_decl
8103 = (current_class_type
8104 && CP_DECL_CONTEXT (decl) == current_class_type
8105 && TYPE_BEING_DEFINED (current_class_type)
8106 && !CLASSTYPE_TEMPLATE_INSTANTIATION (current_class_type));
8108 if (in_class_decl
8109 && (DECL_INITIAL (decl) || init))
8110 DECL_INITIALIZED_IN_CLASS_P (decl) = 1;
8112 if (VAR_P (decl)
8113 && (auto_node = type_uses_auto (type)))
8115 tree d_init;
8116 if (init == NULL_TREE)
8118 if (DECL_LANG_SPECIFIC (decl)
8119 && DECL_TEMPLATE_INSTANTIATION (decl)
8120 && !DECL_TEMPLATE_INSTANTIATED (decl))
8122 /* init is null because we're deferring instantiating the
8123 initializer until we need it. Well, we need it now. */
8124 instantiate_decl (decl, /*defer_ok*/true, /*expl*/false);
8125 return;
8128 gcc_assert (CLASS_PLACEHOLDER_TEMPLATE (auto_node));
8130 d_init = init;
8131 if (d_init)
8133 if (TREE_CODE (d_init) == TREE_LIST
8134 && !CLASS_PLACEHOLDER_TEMPLATE (auto_node))
8135 d_init = build_x_compound_expr_from_list (d_init, ELK_INIT,
8136 tf_warning_or_error);
8137 d_init = resolve_nondeduced_context (d_init, tf_warning_or_error);
8139 enum auto_deduction_context adc = adc_variable_type;
8140 if (DECL_DECOMPOSITION_P (decl))
8141 adc = adc_decomp_type;
8142 tree outer_targs = NULL_TREE;
8143 if (PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node)
8144 && DECL_LANG_SPECIFIC (decl)
8145 && DECL_TEMPLATE_INFO (decl)
8146 && !DECL_FUNCTION_SCOPE_P (decl))
8147 /* The outer template arguments might be needed for satisfaction.
8148 (For function scope variables, do_auto_deduction will obtain the
8149 outer template arguments from current_function_decl.) */
8150 outer_targs = DECL_TI_ARGS (decl);
8151 type = TREE_TYPE (decl) = do_auto_deduction (type, d_init, auto_node,
8152 tf_warning_or_error, adc,
8153 outer_targs, flags);
8154 if (type == error_mark_node)
8155 return;
8156 if (TREE_CODE (type) == FUNCTION_TYPE)
8158 error ("initializer for %<decltype(auto) %D%> has function type; "
8159 "did you forget the %<()%>?", decl);
8160 TREE_TYPE (decl) = error_mark_node;
8161 return;
8163 /* As in start_decl_1, complete so TREE_READONLY is set properly. */
8164 if (!processing_template_decl
8165 && !type_uses_auto (type)
8166 && !COMPLETE_TYPE_P (complete_type (type)))
8168 error_at (location_of (decl),
8169 "deduced type %qT for %qD is incomplete", type, decl);
8170 cxx_incomplete_type_inform (type);
8171 TREE_TYPE (decl) = error_mark_node;
8172 return;
8174 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
8177 if (ensure_literal_type_for_constexpr_object (decl) == error_mark_node)
8179 DECL_DECLARED_CONSTEXPR_P (decl) = 0;
8180 if (VAR_P (decl) && DECL_CLASS_SCOPE_P (decl))
8182 init = NULL_TREE;
8183 DECL_EXTERNAL (decl) = 1;
8187 if (VAR_P (decl)
8188 && DECL_CLASS_SCOPE_P (decl)
8189 && verify_type_context (DECL_SOURCE_LOCATION (decl),
8190 TCTX_STATIC_STORAGE, type)
8191 && DECL_INITIALIZED_IN_CLASS_P (decl))
8192 check_static_variable_definition (decl, type);
8194 if (!processing_template_decl && VAR_P (decl) && is_global_var (decl))
8196 type_context_kind context = (DECL_THREAD_LOCAL_P (decl)
8197 ? TCTX_THREAD_STORAGE
8198 : TCTX_STATIC_STORAGE);
8199 verify_type_context (input_location, context, TREE_TYPE (decl));
8202 if (init && TREE_CODE (decl) == FUNCTION_DECL)
8204 tree clone;
8205 if (init == ridpointers[(int)RID_DELETE])
8207 /* FIXME check this is 1st decl. */
8208 DECL_DELETED_FN (decl) = 1;
8209 DECL_DECLARED_INLINE_P (decl) = 1;
8210 DECL_INITIAL (decl) = error_mark_node;
8211 FOR_EACH_CLONE (clone, decl)
8213 DECL_DELETED_FN (clone) = 1;
8214 DECL_DECLARED_INLINE_P (clone) = 1;
8215 DECL_INITIAL (clone) = error_mark_node;
8217 init = NULL_TREE;
8219 else if (init == ridpointers[(int)RID_DEFAULT])
8221 if (defaultable_fn_check (decl))
8222 DECL_DEFAULTED_FN (decl) = 1;
8223 else
8224 DECL_INITIAL (decl) = NULL_TREE;
8228 if (init && VAR_P (decl))
8230 DECL_NONTRIVIALLY_INITIALIZED_P (decl) = 1;
8231 /* If DECL is a reference, then we want to know whether init is a
8232 reference constant; init_const_expr_p as passed tells us whether
8233 it's an rvalue constant. */
8234 if (TYPE_REF_P (type))
8235 init_const_expr_p = potential_constant_expression (init);
8236 if (init_const_expr_p)
8238 /* Set these flags now for templates. We'll update the flags in
8239 store_init_value for instantiations. */
8240 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
8241 if (decl_maybe_constant_var_p (decl)
8242 /* FIXME setting TREE_CONSTANT on refs breaks the back end. */
8243 && !TYPE_REF_P (type))
8244 TREE_CONSTANT (decl) = 1;
8248 if (flag_openmp
8249 && TREE_CODE (decl) == FUNCTION_DECL
8250 /* #pragma omp declare variant on methods handled in finish_struct
8251 instead. */
8252 && (!DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
8253 || COMPLETE_TYPE_P (DECL_CONTEXT (decl))))
8254 if (tree attr = lookup_attribute ("omp declare variant base",
8255 DECL_ATTRIBUTES (decl)))
8256 omp_declare_variant_finalize (decl, attr);
8258 if (processing_template_decl)
8260 bool type_dependent_p;
8262 /* Add this declaration to the statement-tree. */
8263 if (at_function_scope_p ())
8264 add_decl_expr (decl);
8266 type_dependent_p = dependent_type_p (type);
8268 if (check_for_bare_parameter_packs (init))
8270 init = NULL_TREE;
8271 DECL_INITIAL (decl) = NULL_TREE;
8274 /* Generally, initializers in templates are expanded when the
8275 template is instantiated. But, if DECL is a variable constant
8276 then it can be used in future constant expressions, so its value
8277 must be available. */
8279 bool dep_init = false;
8281 if (!VAR_P (decl) || type_dependent_p)
8282 /* We can't do anything if the decl has dependent type. */;
8283 else if (!init && is_concept_var (decl))
8285 error ("variable concept has no initializer");
8286 init = boolean_true_node;
8288 else if (init
8289 && (init_const_expr_p || DECL_DECLARED_CONSTEXPR_P (decl))
8290 && !TYPE_REF_P (type)
8291 && decl_maybe_constant_var_p (decl)
8292 && !(dep_init = value_dependent_init_p (init)))
8294 /* This variable seems to be a non-dependent constant, so process
8295 its initializer. If check_initializer returns non-null the
8296 initialization wasn't constant after all. */
8297 tree init_code;
8298 cleanups = make_tree_vector ();
8299 init_code = check_initializer (decl, init, flags, &cleanups);
8300 if (init_code == NULL_TREE)
8301 init = NULL_TREE;
8302 release_tree_vector (cleanups);
8304 else
8306 gcc_assert (!DECL_PRETTY_FUNCTION_P (decl));
8307 /* Try to deduce array size. */
8308 maybe_deduce_size_from_array_init (decl, init);
8309 /* And complain about multiple initializers. */
8310 if (init && TREE_CODE (init) == TREE_LIST && TREE_CHAIN (init)
8311 && !MAYBE_CLASS_TYPE_P (type))
8312 init = build_x_compound_expr_from_list (init, ELK_INIT,
8313 tf_warning_or_error);
8316 if (init)
8317 DECL_INITIAL (decl) = init;
8319 if (dep_init)
8321 retrofit_lang_decl (decl);
8322 SET_DECL_DEPENDENT_INIT_P (decl, true);
8325 if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec)
8327 set_user_assembler_name (decl, asmspec);
8328 DECL_HARD_REGISTER (decl) = 1;
8330 return;
8333 /* Just store non-static data member initializers for later. */
8334 if (init && TREE_CODE (decl) == FIELD_DECL)
8335 DECL_INITIAL (decl) = init;
8337 /* Take care of TYPE_DECLs up front. */
8338 if (TREE_CODE (decl) == TYPE_DECL)
8340 if (type != error_mark_node
8341 && MAYBE_CLASS_TYPE_P (type) && DECL_NAME (decl))
8343 if (TREE_TYPE (DECL_NAME (decl)) && TREE_TYPE (decl) != type)
8344 warning (0, "shadowing previous type declaration of %q#D", decl);
8345 set_identifier_type_value (DECL_NAME (decl), decl);
8348 /* If we have installed this as the canonical typedef for this
8349 type, and that type has not been defined yet, delay emitting
8350 the debug information for it, as we will emit it later. */
8351 if (TYPE_MAIN_DECL (TREE_TYPE (decl)) == decl
8352 && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
8353 TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
8355 rest_of_decl_compilation (decl, DECL_FILE_SCOPE_P (decl),
8356 at_eof);
8357 return;
8360 /* A reference will be modified here, as it is initialized. */
8361 if (! DECL_EXTERNAL (decl)
8362 && TREE_READONLY (decl)
8363 && TYPE_REF_P (type))
8365 was_readonly = 1;
8366 TREE_READONLY (decl) = 0;
8369 /* This needs to happen before extend_ref_init_temps. */
8370 if (VAR_OR_FUNCTION_DECL_P (decl))
8372 if (VAR_P (decl))
8373 maybe_commonize_var (decl);
8374 determine_visibility (decl);
8377 if (VAR_P (decl))
8379 duration_kind dk = decl_storage_duration (decl);
8380 /* [dcl.constinit]/1 "The constinit specifier shall be applied
8381 only to a declaration of a variable with static or thread storage
8382 duration." */
8383 if (DECL_DECLARED_CONSTINIT_P (decl)
8384 && !(dk == dk_thread || dk == dk_static))
8386 error_at (DECL_SOURCE_LOCATION (decl),
8387 "%<constinit%> can only be applied to a variable with "
8388 "static or thread storage duration");
8389 return;
8392 /* If this is a local variable that will need a mangled name,
8393 register it now. We must do this before processing the
8394 initializer for the variable, since the initialization might
8395 require a guard variable, and since the mangled name of the
8396 guard variable will depend on the mangled name of this
8397 variable. */
8398 if (DECL_FUNCTION_SCOPE_P (decl)
8399 && TREE_STATIC (decl)
8400 && !DECL_ARTIFICIAL (decl))
8402 /* The variable holding an anonymous union will have had its
8403 discriminator set in finish_anon_union, after which it's
8404 NAME will have been cleared. */
8405 if (DECL_NAME (decl))
8406 determine_local_discriminator (decl);
8407 /* Normally has_forced_label_in_static is set during GIMPLE
8408 lowering, but [cd]tors are never actually compiled directly.
8409 We need to set this early so we can deal with the label
8410 address extension. */
8411 if ((DECL_CONSTRUCTOR_P (current_function_decl)
8412 || DECL_DESTRUCTOR_P (current_function_decl))
8413 && init)
8415 walk_tree (&init, notice_forced_label_r, NULL, NULL);
8416 add_local_decl (cfun, decl);
8418 /* And make sure it's in the symbol table for
8419 c_parse_final_cleanups to find. */
8420 varpool_node::get_create (decl);
8423 /* Convert the initializer to the type of DECL, if we have not
8424 already initialized DECL. */
8425 if (!DECL_INITIALIZED_P (decl)
8426 /* If !DECL_EXTERNAL then DECL is being defined. In the
8427 case of a static data member initialized inside the
8428 class-specifier, there can be an initializer even if DECL
8429 is *not* defined. */
8430 && (!DECL_EXTERNAL (decl) || init))
8432 cleanups = make_tree_vector ();
8433 init = check_initializer (decl, init, flags, &cleanups);
8435 /* Handle:
8437 [dcl.init]
8439 The memory occupied by any object of static storage
8440 duration is zero-initialized at program startup before
8441 any other initialization takes place.
8443 We cannot create an appropriate initializer until after
8444 the type of DECL is finalized. If DECL_INITIAL is set,
8445 then the DECL is statically initialized, and any
8446 necessary zero-initialization has already been performed. */
8447 if (TREE_STATIC (decl) && !DECL_INITIAL (decl))
8448 DECL_INITIAL (decl) = build_zero_init (TREE_TYPE (decl),
8449 /*nelts=*/NULL_TREE,
8450 /*static_storage_p=*/true);
8451 /* Remember that the initialization for this variable has
8452 taken place. */
8453 DECL_INITIALIZED_P (decl) = 1;
8454 /* This declaration is the definition of this variable,
8455 unless we are initializing a static data member within
8456 the class specifier. */
8457 if (!DECL_EXTERNAL (decl))
8458 var_definition_p = true;
8460 /* If the variable has an array type, lay out the type, even if
8461 there is no initializer. It is valid to index through the
8462 array, and we must get TYPE_ALIGN set correctly on the array
8463 type. */
8464 else if (TREE_CODE (type) == ARRAY_TYPE)
8465 layout_type (type);
8467 if (TREE_STATIC (decl)
8468 && !at_function_scope_p ()
8469 && current_function_decl == NULL)
8470 /* So decl is a global variable or a static member of a
8471 non local class. Record the types it uses
8472 so that we can decide later to emit debug info for them. */
8473 record_types_used_by_current_var_decl (decl);
8476 /* Add this declaration to the statement-tree. This needs to happen
8477 after the call to check_initializer so that the DECL_EXPR for a
8478 reference temp is added before the DECL_EXPR for the reference itself. */
8479 if (DECL_FUNCTION_SCOPE_P (decl))
8481 /* If we're building a variable sized type, and we might be
8482 reachable other than via the top of the current binding
8483 level, then create a new BIND_EXPR so that we deallocate
8484 the object at the right time. */
8485 if (VAR_P (decl)
8486 && DECL_SIZE (decl)
8487 && !TREE_CONSTANT (DECL_SIZE (decl))
8488 && STATEMENT_LIST_HAS_LABEL (cur_stmt_list))
8490 tree bind;
8491 bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL);
8492 TREE_SIDE_EFFECTS (bind) = 1;
8493 add_stmt (bind);
8494 BIND_EXPR_BODY (bind) = push_stmt_list ();
8496 add_decl_expr (decl);
8499 /* Let the middle end know about variables and functions -- but not
8500 static data members in uninstantiated class templates. */
8501 if (VAR_OR_FUNCTION_DECL_P (decl))
8503 if (VAR_P (decl))
8505 layout_var_decl (decl);
8506 if (!flag_weak)
8507 /* Check again now that we have an initializer. */
8508 maybe_commonize_var (decl);
8509 /* A class-scope constexpr variable with an out-of-class declaration.
8510 C++17 makes them implicitly inline, but still force it out. */
8511 if (DECL_INLINE_VAR_P (decl)
8512 && !DECL_VAR_DECLARED_INLINE_P (decl)
8513 && !DECL_TEMPLATE_INSTANTIATION (decl)
8514 && !in_class_decl)
8515 mark_needed (decl);
8518 if (var_definition_p
8519 /* With -fmerge-all-constants, gimplify_init_constructor
8520 might add TREE_STATIC to the variable. */
8521 && (TREE_STATIC (decl) || flag_merge_constants >= 2))
8523 /* If a TREE_READONLY variable needs initialization
8524 at runtime, it is no longer readonly and we need to
8525 avoid MEM_READONLY_P being set on RTL created for it. */
8526 if (init)
8528 if (TREE_READONLY (decl))
8529 TREE_READONLY (decl) = 0;
8530 was_readonly = 0;
8532 else if (was_readonly)
8533 TREE_READONLY (decl) = 1;
8535 /* Likewise if it needs destruction. */
8536 if (!decl_maybe_constant_destruction (decl, type))
8537 TREE_READONLY (decl) = 0;
8540 make_rtl_for_nonlocal_decl (decl, init, asmspec);
8542 /* Check for abstractness of the type. */
8543 if (var_definition_p)
8544 abstract_virtuals_error (decl, type);
8546 if (TREE_TYPE (decl) == error_mark_node)
8547 /* No initialization required. */
8549 else if (TREE_CODE (decl) == FUNCTION_DECL)
8551 if (init)
8553 if (init == ridpointers[(int)RID_DEFAULT])
8555 /* An out-of-class default definition is defined at
8556 the point where it is explicitly defaulted. */
8557 if (DECL_DELETED_FN (decl))
8558 maybe_explain_implicit_delete (decl);
8559 else if (DECL_INITIAL (decl) == error_mark_node)
8560 synthesize_method (decl);
8562 else
8563 error_at (cp_expr_loc_or_loc (init,
8564 DECL_SOURCE_LOCATION (decl)),
8565 "function %q#D is initialized like a variable",
8566 decl);
8568 /* else no initialization required. */
8570 else if (DECL_EXTERNAL (decl)
8571 && ! (DECL_LANG_SPECIFIC (decl)
8572 && DECL_NOT_REALLY_EXTERN (decl)))
8574 /* check_initializer will have done any constant initialization. */
8576 /* A variable definition. */
8577 else if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
8578 /* Initialize the local variable. */
8579 initialize_local_var (decl, init);
8581 /* If a variable is defined, and then a subsequent
8582 definition with external linkage is encountered, we will
8583 get here twice for the same variable. We want to avoid
8584 calling expand_static_init more than once. For variables
8585 that are not static data members, we can call
8586 expand_static_init only when we actually process the
8587 initializer. It is not legal to redeclare a static data
8588 member, so this issue does not arise in that case. */
8589 else if (var_definition_p && TREE_STATIC (decl))
8590 expand_static_init (decl, init);
8593 /* If a CLEANUP_STMT was created to destroy a temporary bound to a
8594 reference, insert it in the statement-tree now. */
8595 if (cleanups)
8597 for (tree t : *cleanups)
8599 push_cleanup (NULL_TREE, t, false);
8600 /* As in initialize_local_var. */
8601 wrap_temporary_cleanups (init, t);
8603 release_tree_vector (cleanups);
8606 if (was_readonly)
8607 TREE_READONLY (decl) = 1;
8609 if (flag_openmp
8610 && VAR_P (decl)
8611 && lookup_attribute ("omp declare target implicit",
8612 DECL_ATTRIBUTES (decl)))
8614 DECL_ATTRIBUTES (decl)
8615 = remove_attribute ("omp declare target implicit",
8616 DECL_ATTRIBUTES (decl));
8617 complete_type (TREE_TYPE (decl));
8618 if (!cp_omp_mappable_type (TREE_TYPE (decl)))
8620 error ("%q+D in declare target directive does not have mappable"
8621 " type", decl);
8622 cp_omp_emit_unmappable_type_notes (TREE_TYPE (decl));
8624 else if (!lookup_attribute ("omp declare target",
8625 DECL_ATTRIBUTES (decl))
8626 && !lookup_attribute ("omp declare target link",
8627 DECL_ATTRIBUTES (decl)))
8629 DECL_ATTRIBUTES (decl)
8630 = tree_cons (get_identifier ("omp declare target"),
8631 NULL_TREE, DECL_ATTRIBUTES (decl));
8632 symtab_node *node = symtab_node::get (decl);
8633 if (node != NULL)
8635 node->offloadable = 1;
8636 if (ENABLE_OFFLOADING)
8638 g->have_offload = true;
8639 if (is_a <varpool_node *> (node))
8640 vec_safe_push (offload_vars, decl);
8646 /* This is the last point we can lower alignment so give the target the
8647 chance to do so. */
8648 if (VAR_P (decl)
8649 && !is_global_var (decl)
8650 && !DECL_HARD_REGISTER (decl))
8651 targetm.lower_local_decl_alignment (decl);
8653 invoke_plugin_callbacks (PLUGIN_FINISH_DECL, decl);
8656 /* For class TYPE return itself or some its bases that contain
8657 any direct non-static data members. Return error_mark_node if an
8658 error has been diagnosed. */
8660 static tree
8661 find_decomp_class_base (location_t loc, tree type, tree ret)
8663 bool member_seen = false;
8664 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
8665 if (TREE_CODE (field) != FIELD_DECL
8666 || DECL_ARTIFICIAL (field)
8667 || DECL_UNNAMED_BIT_FIELD (field))
8668 continue;
8669 else if (ret)
8670 return type;
8671 else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
8673 if (TREE_CODE (TREE_TYPE (field)) == RECORD_TYPE)
8674 error_at (loc, "cannot decompose class type %qT because it has an "
8675 "anonymous struct member", type);
8676 else
8677 error_at (loc, "cannot decompose class type %qT because it has an "
8678 "anonymous union member", type);
8679 inform (DECL_SOURCE_LOCATION (field), "declared here");
8680 return error_mark_node;
8682 else if (!accessible_p (type, field, true))
8684 error_at (loc, "cannot decompose inaccessible member %qD of %qT",
8685 field, type);
8686 inform (DECL_SOURCE_LOCATION (field),
8687 TREE_PRIVATE (field)
8688 ? G_("declared private here")
8689 : G_("declared protected here"));
8690 return error_mark_node;
8692 else
8693 member_seen = true;
8695 tree base_binfo, binfo;
8696 tree orig_ret = ret;
8697 int i;
8698 if (member_seen)
8699 ret = type;
8700 for (binfo = TYPE_BINFO (type), i = 0;
8701 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
8703 tree t = find_decomp_class_base (loc, TREE_TYPE (base_binfo), ret);
8704 if (t == error_mark_node)
8705 return error_mark_node;
8706 if (t != NULL_TREE && t != ret)
8708 if (ret == type)
8710 error_at (loc, "cannot decompose class type %qT: both it and "
8711 "its base class %qT have non-static data members",
8712 type, t);
8713 return error_mark_node;
8715 else if (orig_ret != NULL_TREE)
8716 return t;
8717 else if (ret != NULL_TREE)
8719 error_at (loc, "cannot decompose class type %qT: its base "
8720 "classes %qT and %qT have non-static data "
8721 "members", type, ret, t);
8722 return error_mark_node;
8724 else
8725 ret = t;
8728 return ret;
8731 /* Return std::tuple_size<TYPE>::value. */
8733 static tree
8734 get_tuple_size (tree type)
8736 tree args = make_tree_vec (1);
8737 TREE_VEC_ELT (args, 0) = type;
8738 tree inst = lookup_template_class (tuple_size_identifier, args,
8739 /*in_decl*/NULL_TREE,
8740 /*context*/std_node,
8741 /*entering_scope*/false, tf_none);
8742 inst = complete_type (inst);
8743 if (inst == error_mark_node || !COMPLETE_TYPE_P (inst))
8744 return NULL_TREE;
8745 tree val = lookup_qualified_name (inst, value_identifier,
8746 LOOK_want::NORMAL, /*complain*/false);
8747 if (TREE_CODE (val) == VAR_DECL || TREE_CODE (val) == CONST_DECL)
8748 val = maybe_constant_value (val);
8749 if (TREE_CODE (val) == INTEGER_CST)
8750 return val;
8751 else
8752 return error_mark_node;
8755 /* Return std::tuple_element<I,TYPE>::type. */
8757 static tree
8758 get_tuple_element_type (tree type, unsigned i)
8760 tree args = make_tree_vec (2);
8761 TREE_VEC_ELT (args, 0) = build_int_cst (integer_type_node, i);
8762 TREE_VEC_ELT (args, 1) = type;
8763 tree inst = lookup_template_class (tuple_element_identifier, args,
8764 /*in_decl*/NULL_TREE,
8765 /*context*/std_node,
8766 /*entering_scope*/false,
8767 tf_warning_or_error);
8768 return make_typename_type (inst, type_identifier,
8769 none_type, tf_warning_or_error);
8772 /* Return e.get<i>() or get<i>(e). */
8774 static tree
8775 get_tuple_decomp_init (tree decl, unsigned i)
8777 tree targs = make_tree_vec (1);
8778 TREE_VEC_ELT (targs, 0) = build_int_cst (integer_type_node, i);
8780 tree etype = TREE_TYPE (decl);
8781 tree e = convert_from_reference (decl);
8783 /* [The id-expression] e is an lvalue if the type of the entity e is an
8784 lvalue reference and an xvalue otherwise. */
8785 if (!TYPE_REF_P (etype)
8786 || TYPE_REF_IS_RVALUE (etype))
8787 e = move (e);
8789 tree fns = lookup_qualified_name (TREE_TYPE (e), get__identifier,
8790 LOOK_want::NORMAL, /*complain*/false);
8791 bool use_member_get = false;
8793 /* To use a member get, member lookup must find at least one
8794 declaration that is a function template
8795 whose first template parameter is a non-type parameter. */
8796 for (lkp_iterator iter (MAYBE_BASELINK_FUNCTIONS (fns)); iter; ++iter)
8798 tree fn = *iter;
8799 if (TREE_CODE (fn) == TEMPLATE_DECL)
8801 tree tparms = DECL_TEMPLATE_PARMS (fn);
8802 tree parm = TREE_VEC_ELT (INNERMOST_TEMPLATE_PARMS (tparms), 0);
8803 if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
8805 use_member_get = true;
8806 break;
8811 if (use_member_get)
8813 fns = lookup_template_function (fns, targs);
8814 return build_new_method_call (e, fns, /*args*/NULL,
8815 /*path*/NULL_TREE, LOOKUP_NORMAL,
8816 /*fn_p*/NULL, tf_warning_or_error);
8818 else
8820 releasing_vec args (make_tree_vector_single (e));
8821 fns = lookup_template_function (get__identifier, targs);
8822 fns = perform_koenig_lookup (fns, args, tf_warning_or_error);
8823 return finish_call_expr (fns, &args, /*novirt*/false,
8824 /*koenig*/true, tf_warning_or_error);
8828 /* It's impossible to recover the decltype of a tuple decomposition variable
8829 based on the actual type of the variable, so store it in a hash table. */
8831 static GTY((cache)) decl_tree_cache_map *decomp_type_table;
8833 tree
8834 lookup_decomp_type (tree v)
8836 return *decomp_type_table->get (v);
8839 /* Mangle a decomposition declaration if needed. Arguments like
8840 in cp_finish_decomp. */
8842 void
8843 cp_maybe_mangle_decomp (tree decl, tree first, unsigned int count)
8845 if (!processing_template_decl
8846 && !error_operand_p (decl)
8847 && TREE_STATIC (decl))
8849 auto_vec<tree, 16> v;
8850 v.safe_grow (count, true);
8851 tree d = first;
8852 for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
8853 v[count - i - 1] = d;
8854 SET_DECL_ASSEMBLER_NAME (decl, mangle_decomp (decl, v));
8855 maybe_apply_pragma_weak (decl);
8859 /* Finish a decomposition declaration. DECL is the underlying declaration
8860 "e", FIRST is the head of a chain of decls for the individual identifiers
8861 chained through DECL_CHAIN in reverse order and COUNT is the number of
8862 those decls. */
8864 void
8865 cp_finish_decomp (tree decl, tree first, unsigned int count)
8867 if (error_operand_p (decl))
8869 error_out:
8870 while (count--)
8872 TREE_TYPE (first) = error_mark_node;
8873 if (DECL_HAS_VALUE_EXPR_P (first))
8875 SET_DECL_VALUE_EXPR (first, NULL_TREE);
8876 DECL_HAS_VALUE_EXPR_P (first) = 0;
8878 first = DECL_CHAIN (first);
8880 if (DECL_P (decl) && DECL_NAMESPACE_SCOPE_P (decl))
8881 SET_DECL_ASSEMBLER_NAME (decl, get_identifier ("<decomp>"));
8882 return;
8885 location_t loc = DECL_SOURCE_LOCATION (decl);
8886 if (type_dependent_expression_p (decl)
8887 /* This happens for range for when not in templates.
8888 Still add the DECL_VALUE_EXPRs for later processing. */
8889 || (!processing_template_decl
8890 && type_uses_auto (TREE_TYPE (decl))))
8892 for (unsigned int i = 0; i < count; i++)
8894 if (!DECL_HAS_VALUE_EXPR_P (first))
8896 tree v = build_nt (ARRAY_REF, decl,
8897 size_int (count - i - 1),
8898 NULL_TREE, NULL_TREE);
8899 SET_DECL_VALUE_EXPR (first, v);
8900 DECL_HAS_VALUE_EXPR_P (first) = 1;
8902 if (processing_template_decl)
8903 fit_decomposition_lang_decl (first, decl);
8904 first = DECL_CHAIN (first);
8906 return;
8909 auto_vec<tree, 16> v;
8910 v.safe_grow (count, true);
8911 tree d = first;
8912 for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
8914 v[count - i - 1] = d;
8915 fit_decomposition_lang_decl (d, decl);
8918 tree type = TREE_TYPE (decl);
8919 tree dexp = decl;
8921 if (TYPE_REF_P (type))
8923 dexp = convert_from_reference (dexp);
8924 type = complete_type (TREE_TYPE (type));
8925 if (type == error_mark_node)
8926 goto error_out;
8927 if (!COMPLETE_TYPE_P (type))
8929 error_at (loc, "structured binding refers to incomplete type %qT",
8930 type);
8931 goto error_out;
8935 tree eltype = NULL_TREE;
8936 unsigned HOST_WIDE_INT eltscnt = 0;
8937 if (TREE_CODE (type) == ARRAY_TYPE)
8939 tree nelts;
8940 nelts = array_type_nelts_top (type);
8941 if (nelts == error_mark_node)
8942 goto error_out;
8943 if (!tree_fits_uhwi_p (nelts))
8945 error_at (loc, "cannot decompose variable length array %qT", type);
8946 goto error_out;
8948 eltscnt = tree_to_uhwi (nelts);
8949 if (count != eltscnt)
8951 cnt_mismatch:
8952 if (count > eltscnt)
8953 error_n (loc, count,
8954 "%u name provided for structured binding",
8955 "%u names provided for structured binding", count);
8956 else
8957 error_n (loc, count,
8958 "only %u name provided for structured binding",
8959 "only %u names provided for structured binding", count);
8960 inform_n (loc, eltscnt,
8961 "while %qT decomposes into %wu element",
8962 "while %qT decomposes into %wu elements",
8963 type, eltscnt);
8964 goto error_out;
8966 eltype = TREE_TYPE (type);
8967 for (unsigned int i = 0; i < count; i++)
8969 TREE_TYPE (v[i]) = eltype;
8970 layout_decl (v[i], 0);
8971 if (processing_template_decl)
8972 continue;
8973 tree t = unshare_expr (dexp);
8974 t = build4_loc (DECL_SOURCE_LOCATION (v[i]), ARRAY_REF,
8975 eltype, t, size_int (i), NULL_TREE,
8976 NULL_TREE);
8977 SET_DECL_VALUE_EXPR (v[i], t);
8978 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
8981 /* 2 GNU extensions. */
8982 else if (TREE_CODE (type) == COMPLEX_TYPE)
8984 eltscnt = 2;
8985 if (count != eltscnt)
8986 goto cnt_mismatch;
8987 eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
8988 for (unsigned int i = 0; i < count; i++)
8990 TREE_TYPE (v[i]) = eltype;
8991 layout_decl (v[i], 0);
8992 if (processing_template_decl)
8993 continue;
8994 tree t = unshare_expr (dexp);
8995 t = build1_loc (DECL_SOURCE_LOCATION (v[i]),
8996 i ? IMAGPART_EXPR : REALPART_EXPR, eltype,
8998 SET_DECL_VALUE_EXPR (v[i], t);
8999 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9002 else if (TREE_CODE (type) == VECTOR_TYPE)
9004 if (!TYPE_VECTOR_SUBPARTS (type).is_constant (&eltscnt))
9006 error_at (loc, "cannot decompose variable length vector %qT", type);
9007 goto error_out;
9009 if (count != eltscnt)
9010 goto cnt_mismatch;
9011 eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
9012 for (unsigned int i = 0; i < count; i++)
9014 TREE_TYPE (v[i]) = eltype;
9015 layout_decl (v[i], 0);
9016 if (processing_template_decl)
9017 continue;
9018 tree t = unshare_expr (dexp);
9019 convert_vector_to_array_for_subscript (DECL_SOURCE_LOCATION (v[i]),
9020 &t, size_int (i));
9021 t = build4_loc (DECL_SOURCE_LOCATION (v[i]), ARRAY_REF,
9022 eltype, t, size_int (i), NULL_TREE,
9023 NULL_TREE);
9024 SET_DECL_VALUE_EXPR (v[i], t);
9025 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9028 else if (tree tsize = get_tuple_size (type))
9030 if (tsize == error_mark_node)
9032 error_at (loc, "%<std::tuple_size<%T>::value%> is not an integral "
9033 "constant expression", type);
9034 goto error_out;
9036 if (!tree_fits_uhwi_p (tsize))
9038 error_n (loc, count,
9039 "%u name provided for structured binding",
9040 "%u names provided for structured binding", count);
9041 inform (loc, "while %qT decomposes into %E elements",
9042 type, tsize);
9043 goto error_out;
9045 eltscnt = tree_to_uhwi (tsize);
9046 if (count != eltscnt)
9047 goto cnt_mismatch;
9048 int save_read = DECL_READ_P (decl);
9049 for (unsigned i = 0; i < count; ++i)
9051 location_t sloc = input_location;
9052 location_t dloc = DECL_SOURCE_LOCATION (v[i]);
9054 input_location = dloc;
9055 tree init = get_tuple_decomp_init (decl, i);
9056 tree eltype = (init == error_mark_node ? error_mark_node
9057 : get_tuple_element_type (type, i));
9058 input_location = sloc;
9060 if (VOID_TYPE_P (eltype))
9062 error ("%<std::tuple_element<%u, %T>::type%> is %<void%>",
9063 i, type);
9064 eltype = error_mark_node;
9066 if (init == error_mark_node || eltype == error_mark_node)
9068 inform (dloc, "in initialization of structured binding "
9069 "variable %qD", v[i]);
9070 goto error_out;
9072 /* Save the decltype away before reference collapse. */
9073 hash_map_safe_put<hm_ggc> (decomp_type_table, v[i], eltype);
9074 eltype = cp_build_reference_type (eltype, !lvalue_p (init));
9075 TREE_TYPE (v[i]) = eltype;
9076 layout_decl (v[i], 0);
9077 if (DECL_HAS_VALUE_EXPR_P (v[i]))
9079 /* In this case the names are variables, not just proxies. */
9080 SET_DECL_VALUE_EXPR (v[i], NULL_TREE);
9081 DECL_HAS_VALUE_EXPR_P (v[i]) = 0;
9083 if (!processing_template_decl)
9085 copy_linkage (v[i], decl);
9086 cp_finish_decl (v[i], init, /*constexpr*/false,
9087 /*asm*/NULL_TREE, LOOKUP_NORMAL);
9090 /* Ignore reads from the underlying decl performed during initialization
9091 of the individual variables. If those will be read, we'll mark
9092 the underlying decl as read at that point. */
9093 DECL_READ_P (decl) = save_read;
9095 else if (TREE_CODE (type) == UNION_TYPE)
9097 error_at (loc, "cannot decompose union type %qT", type);
9098 goto error_out;
9100 else if (!CLASS_TYPE_P (type))
9102 error_at (loc, "cannot decompose non-array non-class type %qT", type);
9103 goto error_out;
9105 else if (LAMBDA_TYPE_P (type))
9107 error_at (loc, "cannot decompose lambda closure type %qT", type);
9108 goto error_out;
9110 else if (processing_template_decl && complete_type (type) == error_mark_node)
9111 goto error_out;
9112 else if (processing_template_decl && !COMPLETE_TYPE_P (type))
9113 pedwarn (loc, 0, "structured binding refers to incomplete class type %qT",
9114 type);
9115 else
9117 tree btype = find_decomp_class_base (loc, type, NULL_TREE);
9118 if (btype == error_mark_node)
9119 goto error_out;
9120 else if (btype == NULL_TREE)
9122 error_at (loc, "cannot decompose class type %qT without non-static "
9123 "data members", type);
9124 goto error_out;
9126 for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
9127 if (TREE_CODE (field) != FIELD_DECL
9128 || DECL_ARTIFICIAL (field)
9129 || DECL_UNNAMED_BIT_FIELD (field))
9130 continue;
9131 else
9132 eltscnt++;
9133 if (count != eltscnt)
9134 goto cnt_mismatch;
9135 tree t = dexp;
9136 if (type != btype)
9138 t = convert_to_base (t, btype, /*check_access*/true,
9139 /*nonnull*/false, tf_warning_or_error);
9140 type = btype;
9142 unsigned int i = 0;
9143 for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
9144 if (TREE_CODE (field) != FIELD_DECL
9145 || DECL_ARTIFICIAL (field)
9146 || DECL_UNNAMED_BIT_FIELD (field))
9147 continue;
9148 else
9150 tree tt = finish_non_static_data_member (field, unshare_expr (t),
9151 NULL_TREE);
9152 if (REFERENCE_REF_P (tt))
9153 tt = TREE_OPERAND (tt, 0);
9154 TREE_TYPE (v[i]) = TREE_TYPE (tt);
9155 layout_decl (v[i], 0);
9156 if (!processing_template_decl)
9158 SET_DECL_VALUE_EXPR (v[i], tt);
9159 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9161 i++;
9164 if (processing_template_decl)
9166 for (unsigned int i = 0; i < count; i++)
9167 if (!DECL_HAS_VALUE_EXPR_P (v[i]))
9169 tree a = build_nt (ARRAY_REF, decl, size_int (i),
9170 NULL_TREE, NULL_TREE);
9171 SET_DECL_VALUE_EXPR (v[i], a);
9172 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9177 /* Returns a declaration for a VAR_DECL as if:
9179 extern "C" TYPE NAME;
9181 had been seen. Used to create compiler-generated global
9182 variables. */
9184 static tree
9185 declare_global_var (tree name, tree type)
9187 auto cookie = push_abi_namespace (global_namespace);
9188 tree decl = build_decl (input_location, VAR_DECL, name, type);
9189 TREE_PUBLIC (decl) = 1;
9190 DECL_EXTERNAL (decl) = 1;
9191 DECL_ARTIFICIAL (decl) = 1;
9192 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
9193 /* If the user has explicitly declared this variable (perhaps
9194 because the code we are compiling is part of a low-level runtime
9195 library), then it is possible that our declaration will be merged
9196 with theirs by pushdecl. */
9197 decl = pushdecl (decl);
9198 cp_finish_decl (decl, NULL_TREE, false, NULL_TREE, 0);
9199 pop_abi_namespace (cookie, global_namespace);
9201 return decl;
9204 /* Returns the type for the argument to "__cxa_atexit" (or "atexit",
9205 if "__cxa_atexit" is not being used) corresponding to the function
9206 to be called when the program exits. */
9208 static tree
9209 get_atexit_fn_ptr_type (void)
9211 tree fn_type;
9213 if (!atexit_fn_ptr_type_node)
9215 tree arg_type;
9216 if (flag_use_cxa_atexit
9217 && !targetm.cxx.use_atexit_for_cxa_atexit ())
9218 /* The parameter to "__cxa_atexit" is "void (*)(void *)". */
9219 arg_type = ptr_type_node;
9220 else
9221 /* The parameter to "atexit" is "void (*)(void)". */
9222 arg_type = NULL_TREE;
9224 fn_type = build_function_type_list (void_type_node,
9225 arg_type, NULL_TREE);
9226 atexit_fn_ptr_type_node = build_pointer_type (fn_type);
9229 return atexit_fn_ptr_type_node;
9232 /* Returns a pointer to the `atexit' function. Note that if
9233 FLAG_USE_CXA_ATEXIT is nonzero, then this will actually be the new
9234 `__cxa_atexit' function specified in the IA64 C++ ABI. */
9236 static tree
9237 get_atexit_node (void)
9239 tree atexit_fndecl;
9240 tree fn_type;
9241 tree fn_ptr_type;
9242 const char *name;
9243 bool use_aeabi_atexit;
9244 tree ctx = global_namespace;
9246 if (atexit_node)
9247 return atexit_node;
9249 if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
9251 /* The declaration for `__cxa_atexit' is:
9253 int __cxa_atexit (void (*)(void *), void *, void *)
9255 We build up the argument types and then the function type
9256 itself. */
9257 tree argtype0, argtype1, argtype2;
9259 use_aeabi_atexit = targetm.cxx.use_aeabi_atexit ();
9260 /* First, build the pointer-to-function type for the first
9261 argument. */
9262 fn_ptr_type = get_atexit_fn_ptr_type ();
9263 /* Then, build the rest of the argument types. */
9264 argtype2 = ptr_type_node;
9265 if (use_aeabi_atexit)
9267 argtype1 = fn_ptr_type;
9268 argtype0 = ptr_type_node;
9270 else
9272 argtype1 = ptr_type_node;
9273 argtype0 = fn_ptr_type;
9275 /* And the final __cxa_atexit type. */
9276 fn_type = build_function_type_list (integer_type_node,
9277 argtype0, argtype1, argtype2,
9278 NULL_TREE);
9279 /* ... which needs noexcept. */
9280 fn_type = build_exception_variant (fn_type, noexcept_true_spec);
9281 if (use_aeabi_atexit)
9283 name = "__aeabi_atexit";
9284 push_to_top_level ();
9285 int n = push_namespace (get_identifier ("__aeabiv1"), false);
9286 ctx = current_namespace;
9287 while (n--)
9288 pop_namespace ();
9289 pop_from_top_level ();
9291 else
9293 name = "__cxa_atexit";
9294 ctx = abi_node;
9297 else
9299 /* The declaration for `atexit' is:
9301 int atexit (void (*)());
9303 We build up the argument types and then the function type
9304 itself. */
9305 fn_ptr_type = get_atexit_fn_ptr_type ();
9306 /* Build the final atexit type. */
9307 fn_type = build_function_type_list (integer_type_node,
9308 fn_ptr_type, NULL_TREE);
9309 /* ... which needs noexcept. */
9310 fn_type = build_exception_variant (fn_type, noexcept_true_spec);
9311 name = "atexit";
9314 /* Now, build the function declaration. */
9315 push_lang_context (lang_name_c);
9316 auto cookie = push_abi_namespace (ctx);
9317 atexit_fndecl = build_library_fn_ptr (name, fn_type, ECF_LEAF | ECF_NOTHROW);
9318 DECL_CONTEXT (atexit_fndecl) = FROB_CONTEXT (current_namespace);
9319 /* Install as hidden builtin so we're (a) more relaxed about
9320 exception spec matching and (b) will not give a confusing location
9321 in diagnostic and (c) won't magically appear in user-visible name
9322 lookups. */
9323 DECL_SOURCE_LOCATION (atexit_fndecl) = BUILTINS_LOCATION;
9324 atexit_fndecl = pushdecl (atexit_fndecl, /*hiding=*/true);
9325 pop_abi_namespace (cookie, ctx);
9326 mark_used (atexit_fndecl);
9327 pop_lang_context ();
9328 atexit_node = decay_conversion (atexit_fndecl, tf_warning_or_error);
9330 return atexit_node;
9333 /* Like get_atexit_node, but for thread-local cleanups. */
9335 static tree
9336 get_thread_atexit_node (void)
9338 /* The declaration for `__cxa_thread_atexit' is:
9340 int __cxa_thread_atexit (void (*)(void *), void *, void *) */
9341 tree fn_type = build_function_type_list (integer_type_node,
9342 get_atexit_fn_ptr_type (),
9343 ptr_type_node, ptr_type_node,
9344 NULL_TREE);
9346 /* Now, build the function declaration. */
9347 tree atexit_fndecl = build_library_fn_ptr ("__cxa_thread_atexit", fn_type,
9348 ECF_LEAF | ECF_NOTHROW);
9349 return decay_conversion (atexit_fndecl, tf_warning_or_error);
9352 /* Returns the __dso_handle VAR_DECL. */
9354 static tree
9355 get_dso_handle_node (void)
9357 if (dso_handle_node)
9358 return dso_handle_node;
9360 /* Declare the variable. */
9361 dso_handle_node = declare_global_var (get_identifier ("__dso_handle"),
9362 ptr_type_node);
9364 #ifdef HAVE_GAS_HIDDEN
9365 if (dso_handle_node != error_mark_node)
9367 DECL_VISIBILITY (dso_handle_node) = VISIBILITY_HIDDEN;
9368 DECL_VISIBILITY_SPECIFIED (dso_handle_node) = 1;
9370 #endif
9372 return dso_handle_node;
9375 /* Begin a new function with internal linkage whose job will be simply
9376 to destroy some particular variable. */
9378 static GTY(()) int start_cleanup_cnt;
9380 static tree
9381 start_cleanup_fn (void)
9383 char name[32];
9385 push_to_top_level ();
9387 /* No need to mangle this. */
9388 push_lang_context (lang_name_c);
9390 /* Build the name of the function. */
9391 sprintf (name, "__tcf_%d", start_cleanup_cnt++);
9392 /* Build the function declaration. */
9393 tree fntype = TREE_TYPE (get_atexit_fn_ptr_type ());
9394 tree fndecl = build_lang_decl (FUNCTION_DECL, get_identifier (name), fntype);
9395 DECL_CONTEXT (fndecl) = FROB_CONTEXT (current_namespace);
9396 /* It's a function with internal linkage, generated by the
9397 compiler. */
9398 TREE_PUBLIC (fndecl) = 0;
9399 DECL_ARTIFICIAL (fndecl) = 1;
9400 /* Make the function `inline' so that it is only emitted if it is
9401 actually needed. It is unlikely that it will be inlined, since
9402 it is only called via a function pointer, but we avoid unnecessary
9403 emissions this way. */
9404 DECL_DECLARED_INLINE_P (fndecl) = 1;
9405 DECL_INTERFACE_KNOWN (fndecl) = 1;
9406 if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
9408 /* Build the parameter. */
9409 tree parmdecl = cp_build_parm_decl (fndecl, NULL_TREE, ptr_type_node);
9410 TREE_USED (parmdecl) = 1;
9411 DECL_READ_P (parmdecl) = 1;
9412 DECL_ARGUMENTS (fndecl) = parmdecl;
9415 fndecl = pushdecl (fndecl, /*hidden=*/true);
9416 start_preparsed_function (fndecl, NULL_TREE, SF_PRE_PARSED);
9418 pop_lang_context ();
9420 return current_function_decl;
9423 /* Finish the cleanup function begun by start_cleanup_fn. */
9425 static void
9426 end_cleanup_fn (void)
9428 expand_or_defer_fn (finish_function (/*inline_p=*/false));
9430 pop_from_top_level ();
9433 /* Generate code to handle the destruction of DECL, an object with
9434 static storage duration. */
9436 tree
9437 register_dtor_fn (tree decl)
9439 tree cleanup;
9440 tree addr;
9441 tree compound_stmt;
9442 tree fcall;
9443 tree type;
9444 bool ob_parm, dso_parm, use_dtor;
9445 tree arg0, arg1, arg2;
9446 tree atex_node;
9448 type = TREE_TYPE (decl);
9449 if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
9450 return void_node;
9452 if (decl_maybe_constant_destruction (decl, type)
9453 && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
9455 cxx_maybe_build_cleanup (decl, tf_warning_or_error);
9456 return void_node;
9459 /* If we're using "__cxa_atexit" (or "__cxa_thread_atexit" or
9460 "__aeabi_atexit"), and DECL is a class object, we can just pass the
9461 destructor to "__cxa_atexit"; we don't have to build a temporary
9462 function to do the cleanup. */
9463 dso_parm = (flag_use_cxa_atexit
9464 && !targetm.cxx.use_atexit_for_cxa_atexit ());
9465 ob_parm = (CP_DECL_THREAD_LOCAL_P (decl) || dso_parm);
9466 use_dtor = ob_parm && CLASS_TYPE_P (type);
9467 if (use_dtor)
9469 cleanup = get_class_binding (type, complete_dtor_identifier);
9471 /* Make sure it is accessible. */
9472 perform_or_defer_access_check (TYPE_BINFO (type), cleanup, cleanup,
9473 tf_warning_or_error);
9475 else
9477 /* Call build_cleanup before we enter the anonymous function so
9478 that any access checks will be done relative to the current
9479 scope, rather than the scope of the anonymous function. */
9480 build_cleanup (decl);
9482 /* Now start the function. */
9483 cleanup = start_cleanup_fn ();
9485 /* Now, recompute the cleanup. It may contain SAVE_EXPRs that refer
9486 to the original function, rather than the anonymous one. That
9487 will make the back end think that nested functions are in use,
9488 which causes confusion. */
9489 push_deferring_access_checks (dk_no_check);
9490 fcall = build_cleanup (decl);
9491 pop_deferring_access_checks ();
9493 /* Create the body of the anonymous function. */
9494 compound_stmt = begin_compound_stmt (BCS_FN_BODY);
9495 finish_expr_stmt (fcall);
9496 finish_compound_stmt (compound_stmt);
9497 end_cleanup_fn ();
9500 /* Call atexit with the cleanup function. */
9501 mark_used (cleanup);
9502 cleanup = build_address (cleanup);
9504 if (CP_DECL_THREAD_LOCAL_P (decl))
9505 atex_node = get_thread_atexit_node ();
9506 else
9507 atex_node = get_atexit_node ();
9509 if (use_dtor)
9511 /* We must convert CLEANUP to the type that "__cxa_atexit"
9512 expects. */
9513 cleanup = build_nop (get_atexit_fn_ptr_type (), cleanup);
9514 /* "__cxa_atexit" will pass the address of DECL to the
9515 cleanup function. */
9516 mark_used (decl);
9517 addr = build_address (decl);
9518 /* The declared type of the parameter to "__cxa_atexit" is
9519 "void *". For plain "T*", we could just let the
9520 machinery in cp_build_function_call convert it -- but if the
9521 type is "cv-qualified T *", then we need to convert it
9522 before passing it in, to avoid spurious errors. */
9523 addr = build_nop (ptr_type_node, addr);
9525 else
9526 /* Since the cleanup functions we build ignore the address
9527 they're given, there's no reason to pass the actual address
9528 in, and, in general, it's cheaper to pass NULL than any
9529 other value. */
9530 addr = null_pointer_node;
9532 if (dso_parm)
9533 arg2 = cp_build_addr_expr (get_dso_handle_node (),
9534 tf_warning_or_error);
9535 else if (ob_parm)
9536 /* Just pass NULL to the dso handle parm if we don't actually
9537 have a DSO handle on this target. */
9538 arg2 = null_pointer_node;
9539 else
9540 arg2 = NULL_TREE;
9542 if (ob_parm)
9544 if (!CP_DECL_THREAD_LOCAL_P (decl)
9545 && targetm.cxx.use_aeabi_atexit ())
9547 arg1 = cleanup;
9548 arg0 = addr;
9550 else
9552 arg1 = addr;
9553 arg0 = cleanup;
9556 else
9558 arg0 = cleanup;
9559 arg1 = NULL_TREE;
9561 return cp_build_function_call_nary (atex_node, tf_warning_or_error,
9562 arg0, arg1, arg2, NULL_TREE);
9565 /* DECL is a VAR_DECL with static storage duration. INIT, if present,
9566 is its initializer. Generate code to handle the construction
9567 and destruction of DECL. */
9569 static void
9570 expand_static_init (tree decl, tree init)
9572 gcc_assert (VAR_P (decl));
9573 gcc_assert (TREE_STATIC (decl));
9575 /* Some variables require no dynamic initialization. */
9576 if (decl_maybe_constant_destruction (decl, TREE_TYPE (decl)))
9578 /* Make sure the destructor is callable. */
9579 cxx_maybe_build_cleanup (decl, tf_warning_or_error);
9580 if (!init)
9581 return;
9584 if (CP_DECL_THREAD_LOCAL_P (decl) && DECL_GNU_TLS_P (decl)
9585 && !DECL_FUNCTION_SCOPE_P (decl))
9587 location_t dloc = DECL_SOURCE_LOCATION (decl);
9588 if (init)
9589 error_at (dloc, "non-local variable %qD declared %<__thread%> "
9590 "needs dynamic initialization", decl);
9591 else
9592 error_at (dloc, "non-local variable %qD declared %<__thread%> "
9593 "has a non-trivial destructor", decl);
9594 static bool informed;
9595 if (!informed)
9597 inform (dloc, "C++11 %<thread_local%> allows dynamic "
9598 "initialization and destruction");
9599 informed = true;
9601 return;
9604 if (DECL_FUNCTION_SCOPE_P (decl))
9606 /* Emit code to perform this initialization but once. */
9607 tree if_stmt = NULL_TREE, inner_if_stmt = NULL_TREE;
9608 tree then_clause = NULL_TREE, inner_then_clause = NULL_TREE;
9609 tree guard, guard_addr;
9610 tree flag, begin;
9611 /* We don't need thread-safety code for thread-local vars. */
9612 bool thread_guard = (flag_threadsafe_statics
9613 && !CP_DECL_THREAD_LOCAL_P (decl));
9615 /* Emit code to perform this initialization but once. This code
9616 looks like:
9618 static <type> guard;
9619 if (!__atomic_load (guard.first_byte)) {
9620 if (__cxa_guard_acquire (&guard)) {
9621 bool flag = false;
9622 try {
9623 // Do initialization.
9624 flag = true; __cxa_guard_release (&guard);
9625 // Register variable for destruction at end of program.
9626 } catch {
9627 if (!flag) __cxa_guard_abort (&guard);
9632 Note that the `flag' variable is only set to 1 *after* the
9633 initialization is complete. This ensures that an exception,
9634 thrown during the construction, will cause the variable to
9635 reinitialized when we pass through this code again, as per:
9637 [stmt.dcl]
9639 If the initialization exits by throwing an exception, the
9640 initialization is not complete, so it will be tried again
9641 the next time control enters the declaration.
9643 This process should be thread-safe, too; multiple threads
9644 should not be able to initialize the variable more than
9645 once. */
9647 /* Create the guard variable. */
9648 guard = get_guard (decl);
9650 /* Begin the conditional initialization. */
9651 if_stmt = begin_if_stmt ();
9653 finish_if_stmt_cond (get_guard_cond (guard, thread_guard), if_stmt);
9654 then_clause = begin_compound_stmt (BCS_NO_SCOPE);
9656 if (thread_guard)
9658 tree vfntype = NULL_TREE;
9659 tree acquire_name, release_name, abort_name;
9660 tree acquire_fn, release_fn, abort_fn;
9661 guard_addr = build_address (guard);
9663 acquire_name = get_identifier ("__cxa_guard_acquire");
9664 release_name = get_identifier ("__cxa_guard_release");
9665 abort_name = get_identifier ("__cxa_guard_abort");
9666 acquire_fn = get_global_binding (acquire_name);
9667 release_fn = get_global_binding (release_name);
9668 abort_fn = get_global_binding (abort_name);
9669 if (!acquire_fn)
9670 acquire_fn = push_library_fn
9671 (acquire_name, build_function_type_list (integer_type_node,
9672 TREE_TYPE (guard_addr),
9673 NULL_TREE),
9674 NULL_TREE, ECF_NOTHROW);
9675 if (!release_fn || !abort_fn)
9676 vfntype = build_function_type_list (void_type_node,
9677 TREE_TYPE (guard_addr),
9678 NULL_TREE);
9679 if (!release_fn)
9680 release_fn = push_library_fn (release_name, vfntype, NULL_TREE,
9681 ECF_NOTHROW);
9682 if (!abort_fn)
9683 abort_fn = push_library_fn (abort_name, vfntype, NULL_TREE,
9684 ECF_NOTHROW | ECF_LEAF);
9686 inner_if_stmt = begin_if_stmt ();
9687 finish_if_stmt_cond (build_call_n (acquire_fn, 1, guard_addr),
9688 inner_if_stmt);
9690 inner_then_clause = begin_compound_stmt (BCS_NO_SCOPE);
9691 begin = get_target_expr (boolean_false_node);
9692 flag = TARGET_EXPR_SLOT (begin);
9694 TARGET_EXPR_CLEANUP (begin)
9695 = build3 (COND_EXPR, void_type_node, flag,
9696 void_node,
9697 build_call_n (abort_fn, 1, guard_addr));
9698 CLEANUP_EH_ONLY (begin) = 1;
9700 /* Do the initialization itself. */
9701 init = add_stmt_to_compound (begin, init);
9702 init = add_stmt_to_compound (init,
9703 build2 (MODIFY_EXPR, void_type_node,
9704 flag, boolean_true_node));
9706 /* Use atexit to register a function for destroying this static
9707 variable. Do this before calling __cxa_guard_release. */
9708 init = add_stmt_to_compound (init, register_dtor_fn (decl));
9710 init = add_stmt_to_compound (init, build_call_n (release_fn, 1,
9711 guard_addr));
9713 else
9715 init = add_stmt_to_compound (init, set_guard (guard));
9717 /* Use atexit to register a function for destroying this static
9718 variable. */
9719 init = add_stmt_to_compound (init, register_dtor_fn (decl));
9722 finish_expr_stmt (init);
9724 if (thread_guard)
9726 finish_compound_stmt (inner_then_clause);
9727 finish_then_clause (inner_if_stmt);
9728 finish_if_stmt (inner_if_stmt);
9731 finish_compound_stmt (then_clause);
9732 finish_then_clause (if_stmt);
9733 finish_if_stmt (if_stmt);
9735 else if (CP_DECL_THREAD_LOCAL_P (decl))
9736 tls_aggregates = tree_cons (init, decl, tls_aggregates);
9737 else
9738 static_aggregates = tree_cons (init, decl, static_aggregates);
9742 /* Make TYPE a complete type based on INITIAL_VALUE.
9743 Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
9744 2 if there was no information (in which case assume 0 if DO_DEFAULT),
9745 3 if the initializer list is empty (in pedantic mode). */
9748 cp_complete_array_type (tree *ptype, tree initial_value, bool do_default)
9750 int failure;
9751 tree type, elt_type;
9753 /* Don't get confused by a CONSTRUCTOR for some other type. */
9754 if (initial_value && TREE_CODE (initial_value) == CONSTRUCTOR
9755 && !BRACE_ENCLOSED_INITIALIZER_P (initial_value)
9756 && TREE_CODE (TREE_TYPE (initial_value)) != ARRAY_TYPE)
9757 return 1;
9759 if (initial_value)
9761 /* An array of character type can be initialized from a
9762 brace-enclosed string constant so call reshape_init to
9763 remove the optional braces from a braced string literal. */
9764 if (char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (*ptype)))
9765 && BRACE_ENCLOSED_INITIALIZER_P (initial_value))
9766 initial_value = reshape_init (*ptype, initial_value,
9767 tf_warning_or_error);
9769 /* If any of the elements are parameter packs, we can't actually
9770 complete this type now because the array size is dependent. */
9771 if (TREE_CODE (initial_value) == CONSTRUCTOR)
9772 for (auto &e: CONSTRUCTOR_ELTS (initial_value))
9773 if (PACK_EXPANSION_P (e.value))
9774 return 0;
9777 failure = complete_array_type (ptype, initial_value, do_default);
9779 /* We can create the array before the element type is complete, which
9780 means that we didn't have these two bits set in the original type
9781 either. In completing the type, we are expected to propagate these
9782 bits. See also complete_type which does the same thing for arrays
9783 of fixed size. */
9784 type = *ptype;
9785 if (type != error_mark_node && TYPE_DOMAIN (type))
9787 elt_type = TREE_TYPE (type);
9788 TYPE_NEEDS_CONSTRUCTING (type) = TYPE_NEEDS_CONSTRUCTING (elt_type);
9789 TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
9790 = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (elt_type);
9793 return failure;
9796 /* As above, but either give an error or reject zero-size arrays, depending
9797 on COMPLAIN. */
9800 cp_complete_array_type_or_error (tree *ptype, tree initial_value,
9801 bool do_default, tsubst_flags_t complain)
9803 int failure;
9804 bool sfinae = !(complain & tf_error);
9805 /* In SFINAE context we can't be lenient about zero-size arrays. */
9806 if (sfinae)
9807 ++pedantic;
9808 failure = cp_complete_array_type (ptype, initial_value, do_default);
9809 if (sfinae)
9810 --pedantic;
9811 if (failure)
9813 if (sfinae)
9814 /* Not an error. */;
9815 else if (failure == 1)
9816 error ("initializer fails to determine size of %qT", *ptype);
9817 else if (failure == 2)
9819 if (do_default)
9820 error ("array size missing in %qT", *ptype);
9822 else if (failure == 3)
9823 error ("zero-size array %qT", *ptype);
9824 *ptype = error_mark_node;
9826 return failure;
9829 /* Return zero if something is declared to be a member of type
9830 CTYPE when in the context of CUR_TYPE. STRING is the error
9831 message to print in that case. Otherwise, quietly return 1. */
9833 static int
9834 member_function_or_else (tree ctype, tree cur_type, enum overload_flags flags)
9836 if (ctype && ctype != cur_type)
9838 if (flags == DTOR_FLAG)
9839 error ("destructor for alien class %qT cannot be a member", ctype);
9840 else
9841 error ("constructor for alien class %qT cannot be a member", ctype);
9842 return 0;
9844 return 1;
9847 /* Subroutine of `grokdeclarator'. */
9849 /* Generate errors possibly applicable for a given set of specifiers.
9850 This is for ARM $7.1.2. */
9852 static void
9853 bad_specifiers (tree object,
9854 enum bad_spec_place type,
9855 int virtualp,
9856 int quals,
9857 int inlinep,
9858 int friendp,
9859 int raises,
9860 const location_t* locations)
9862 switch (type)
9864 case BSP_VAR:
9865 if (virtualp)
9866 error_at (locations[ds_virtual],
9867 "%qD declared as a %<virtual%> variable", object);
9868 if (quals)
9869 error ("%<const%> and %<volatile%> function specifiers on "
9870 "%qD invalid in variable declaration", object);
9871 break;
9872 case BSP_PARM:
9873 if (virtualp)
9874 error_at (locations[ds_virtual],
9875 "%qD declared as a %<virtual%> parameter", object);
9876 if (inlinep)
9877 error_at (locations[ds_inline],
9878 "%qD declared as an %<inline%> parameter", object);
9879 if (quals)
9880 error ("%<const%> and %<volatile%> function specifiers on "
9881 "%qD invalid in parameter declaration", object);
9882 break;
9883 case BSP_TYPE:
9884 if (virtualp)
9885 error_at (locations[ds_virtual],
9886 "%qD declared as a %<virtual%> type", object);
9887 if (inlinep)
9888 error_at (locations[ds_inline],
9889 "%qD declared as an %<inline%> type", object);
9890 if (quals)
9891 error ("%<const%> and %<volatile%> function specifiers on "
9892 "%qD invalid in type declaration", object);
9893 break;
9894 case BSP_FIELD:
9895 if (virtualp)
9896 error_at (locations[ds_virtual],
9897 "%qD declared as a %<virtual%> field", object);
9898 if (inlinep)
9899 error_at (locations[ds_inline],
9900 "%qD declared as an %<inline%> field", object);
9901 if (quals)
9902 error ("%<const%> and %<volatile%> function specifiers on "
9903 "%qD invalid in field declaration", object);
9904 break;
9905 default:
9906 gcc_unreachable();
9908 if (friendp)
9909 error ("%q+D declared as a friend", object);
9910 if (raises
9911 && !flag_noexcept_type
9912 && (TREE_CODE (object) == TYPE_DECL
9913 || (!TYPE_PTRFN_P (TREE_TYPE (object))
9914 && !TYPE_REFFN_P (TREE_TYPE (object))
9915 && !TYPE_PTRMEMFUNC_P (TREE_TYPE (object)))))
9916 error ("%q+D declared with an exception specification", object);
9919 /* DECL is a member function or static data member and is presently
9920 being defined. Check that the definition is taking place in a
9921 valid namespace. */
9923 static void
9924 check_class_member_definition_namespace (tree decl)
9926 /* These checks only apply to member functions and static data
9927 members. */
9928 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
9929 /* We check for problems with specializations in pt.cc in
9930 check_specialization_namespace, where we can issue better
9931 diagnostics. */
9932 if (processing_specialization)
9933 return;
9934 /* We check this in check_explicit_instantiation_namespace. */
9935 if (processing_explicit_instantiation)
9936 return;
9937 /* [class.mfct]
9939 A member function definition that appears outside of the
9940 class definition shall appear in a namespace scope enclosing
9941 the class definition.
9943 [class.static.data]
9945 The definition for a static data member shall appear in a
9946 namespace scope enclosing the member's class definition. */
9947 if (!is_ancestor (current_namespace, DECL_CONTEXT (decl)))
9948 permerror (input_location, "definition of %qD is not in namespace enclosing %qT",
9949 decl, DECL_CONTEXT (decl));
9952 /* Build a PARM_DECL for the "this" parameter of FN. TYPE is the
9953 METHOD_TYPE for a non-static member function; QUALS are the
9954 cv-qualifiers that apply to the function. */
9956 tree
9957 build_this_parm (tree fn, tree type, cp_cv_quals quals)
9959 tree this_type;
9960 tree qual_type;
9961 tree parm;
9962 cp_cv_quals this_quals;
9964 if (CLASS_TYPE_P (type))
9966 this_type
9967 = cp_build_qualified_type (type, quals & ~TYPE_QUAL_RESTRICT);
9968 this_type = build_pointer_type (this_type);
9970 else
9971 this_type = type_of_this_parm (type);
9972 /* The `this' parameter is implicitly `const'; it cannot be
9973 assigned to. */
9974 this_quals = (quals & TYPE_QUAL_RESTRICT) | TYPE_QUAL_CONST;
9975 qual_type = cp_build_qualified_type (this_type, this_quals);
9976 parm = build_artificial_parm (fn, this_identifier, qual_type);
9977 cp_apply_type_quals_to_decl (this_quals, parm);
9978 return parm;
9981 /* DECL is a static member function. Complain if it was declared
9982 with function-cv-quals. */
9984 static void
9985 check_static_quals (tree decl, cp_cv_quals quals)
9987 if (quals != TYPE_UNQUALIFIED)
9988 error ("static member function %q#D declared with type qualifiers",
9989 decl);
9992 // Check that FN takes no arguments and returns bool.
9993 static void
9994 check_concept_fn (tree fn)
9996 // A constraint is nullary.
9997 if (DECL_ARGUMENTS (fn))
9998 error_at (DECL_SOURCE_LOCATION (fn),
9999 "concept %q#D declared with function parameters", fn);
10001 // The declared return type of the concept shall be bool, and
10002 // it shall not be deduced from it definition.
10003 tree type = TREE_TYPE (TREE_TYPE (fn));
10004 if (is_auto (type))
10005 error_at (DECL_SOURCE_LOCATION (fn),
10006 "concept %q#D declared with a deduced return type", fn);
10007 else if (type != boolean_type_node)
10008 error_at (DECL_SOURCE_LOCATION (fn),
10009 "concept %q#D with non-%<bool%> return type %qT", fn, type);
10012 /* Helper function. Replace the temporary this parameter injected
10013 during cp_finish_omp_declare_simd with the real this parameter. */
10015 static tree
10016 declare_simd_adjust_this (tree *tp, int *walk_subtrees, void *data)
10018 tree this_parm = (tree) data;
10019 if (TREE_CODE (*tp) == PARM_DECL
10020 && DECL_NAME (*tp) == this_identifier
10021 && *tp != this_parm)
10022 *tp = this_parm;
10023 else if (TYPE_P (*tp))
10024 *walk_subtrees = 0;
10025 return NULL_TREE;
10028 /* CTYPE is class type, or null if non-class.
10029 TYPE is type this FUNCTION_DECL should have, either FUNCTION_TYPE
10030 or METHOD_TYPE.
10031 DECLARATOR is the function's name.
10032 PARMS is a chain of PARM_DECLs for the function.
10033 VIRTUALP is truthvalue of whether the function is virtual or not.
10034 FLAGS are to be passed through to `grokclassfn'.
10035 QUALS are qualifiers indicating whether the function is `const'
10036 or `volatile'.
10037 RAISES is a list of exceptions that this function can raise.
10038 CHECK is 1 if we must find this method in CTYPE, 0 if we should
10039 not look, and -1 if we should not call `grokclassfn' at all.
10041 SFK is the kind of special function (if any) for the new function.
10043 Returns `NULL_TREE' if something goes wrong, after issuing
10044 applicable error messages. */
10046 static tree
10047 grokfndecl (tree ctype,
10048 tree type,
10049 tree declarator,
10050 tree parms,
10051 tree orig_declarator,
10052 const cp_decl_specifier_seq *declspecs,
10053 tree decl_reqs,
10054 int virtualp,
10055 enum overload_flags flags,
10056 cp_cv_quals quals,
10057 cp_ref_qualifier rqual,
10058 tree raises,
10059 int check,
10060 int friendp,
10061 int publicp,
10062 int inlinep,
10063 bool deletedp,
10064 special_function_kind sfk,
10065 bool funcdef_flag,
10066 bool late_return_type_p,
10067 int template_count,
10068 tree in_namespace,
10069 tree* attrlist,
10070 location_t location)
10072 tree decl;
10073 int staticp = ctype && TREE_CODE (type) == FUNCTION_TYPE;
10074 tree t;
10076 if (location == UNKNOWN_LOCATION)
10077 location = input_location;
10079 /* Was the concept specifier present? */
10080 bool concept_p = inlinep & 4;
10082 /* Concept declarations must have a corresponding definition. */
10083 if (concept_p && !funcdef_flag)
10085 error_at (location, "concept %qD has no definition", declarator);
10086 return NULL_TREE;
10089 type = build_cp_fntype_variant (type, rqual, raises, late_return_type_p);
10091 decl = build_lang_decl_loc (location, FUNCTION_DECL, declarator, type);
10093 /* Set the constraints on the declaration. */
10094 if (flag_concepts)
10096 tree tmpl_reqs = NULL_TREE;
10097 tree ctx = friendp ? current_class_type : ctype;
10098 bool block_local = TREE_CODE (current_scope ()) == FUNCTION_DECL;
10099 bool memtmpl = (!block_local
10100 && (current_template_depth
10101 > template_class_depth (ctx)));
10102 if (memtmpl)
10104 if (!current_template_parms)
10105 /* If there are no template parameters, something must have
10106 gone wrong. */
10107 gcc_assert (seen_error ());
10108 else
10109 tmpl_reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
10111 tree ci = build_constraints (tmpl_reqs, decl_reqs);
10112 if (concept_p && ci)
10114 error_at (location, "a function concept cannot be constrained");
10115 ci = NULL_TREE;
10117 /* C++20 CA378: Remove non-templated constrained functions. */
10118 if (ci
10119 && (block_local
10120 || (!flag_concepts_ts
10121 && (!processing_template_decl
10122 || (friendp && !memtmpl && !funcdef_flag)))))
10124 error_at (location, "constraints on a non-templated function");
10125 ci = NULL_TREE;
10127 set_constraints (decl, ci);
10130 if (TREE_CODE (type) == METHOD_TYPE)
10132 tree parm = build_this_parm (decl, type, quals);
10133 DECL_CHAIN (parm) = parms;
10134 parms = parm;
10136 /* Allocate space to hold the vptr bit if needed. */
10137 SET_DECL_ALIGN (decl, MINIMUM_METHOD_BOUNDARY);
10140 DECL_ARGUMENTS (decl) = parms;
10141 for (t = parms; t; t = DECL_CHAIN (t))
10142 DECL_CONTEXT (t) = decl;
10144 /* Propagate volatile out from type to decl. */
10145 if (TYPE_VOLATILE (type))
10146 TREE_THIS_VOLATILE (decl) = 1;
10148 /* Setup decl according to sfk. */
10149 switch (sfk)
10151 case sfk_constructor:
10152 case sfk_copy_constructor:
10153 case sfk_move_constructor:
10154 DECL_CXX_CONSTRUCTOR_P (decl) = 1;
10155 DECL_NAME (decl) = ctor_identifier;
10156 break;
10157 case sfk_destructor:
10158 DECL_CXX_DESTRUCTOR_P (decl) = 1;
10159 DECL_NAME (decl) = dtor_identifier;
10160 break;
10161 default:
10162 break;
10165 if (friendp && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)
10167 if (funcdef_flag)
10168 error_at (location,
10169 "defining explicit specialization %qD in friend declaration",
10170 orig_declarator);
10171 else
10173 tree fns = TREE_OPERAND (orig_declarator, 0);
10174 tree args = TREE_OPERAND (orig_declarator, 1);
10176 if (PROCESSING_REAL_TEMPLATE_DECL_P ())
10178 /* Something like `template <class T> friend void f<T>()'. */
10179 error_at (location,
10180 "invalid use of template-id %qD in declaration "
10181 "of primary template",
10182 orig_declarator);
10183 return NULL_TREE;
10187 /* A friend declaration of the form friend void f<>(). Record
10188 the information in the TEMPLATE_ID_EXPR. */
10189 SET_DECL_IMPLICIT_INSTANTIATION (decl);
10191 gcc_assert (identifier_p (fns) || OVL_P (fns));
10192 DECL_TEMPLATE_INFO (decl) = build_template_info (fns, args);
10194 for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
10195 if (TREE_PURPOSE (t)
10196 && TREE_CODE (TREE_PURPOSE (t)) == DEFERRED_PARSE)
10198 error_at (defparse_location (TREE_PURPOSE (t)),
10199 "default arguments are not allowed in declaration "
10200 "of friend template specialization %qD",
10201 decl);
10202 return NULL_TREE;
10205 if (inlinep & 1)
10207 error_at (declspecs->locations[ds_inline],
10208 "%<inline%> is not allowed in declaration of friend "
10209 "template specialization %qD",
10210 decl);
10211 return NULL_TREE;
10216 /* C++17 11.3.6/4: "If a friend declaration specifies a default argument
10217 expression, that declaration shall be a definition..." */
10218 if (friendp && !funcdef_flag)
10220 for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
10221 t && t != void_list_node; t = TREE_CHAIN (t))
10222 if (TREE_PURPOSE (t))
10224 permerror (DECL_SOURCE_LOCATION (decl),
10225 "friend declaration of %qD specifies default "
10226 "arguments and isn%'t a definition", decl);
10227 break;
10231 /* If this decl has namespace scope, set that up. */
10232 if (in_namespace)
10233 set_decl_namespace (decl, in_namespace, friendp);
10234 else if (ctype)
10235 DECL_CONTEXT (decl) = ctype;
10236 else
10237 DECL_CONTEXT (decl) = FROB_CONTEXT (current_decl_namespace ());
10239 /* `main' and builtins have implicit 'C' linkage. */
10240 if (ctype == NULL_TREE
10241 && DECL_FILE_SCOPE_P (decl)
10242 && current_lang_name == lang_name_cplusplus
10243 && (MAIN_NAME_P (declarator)
10244 || (IDENTIFIER_LENGTH (declarator) > 10
10245 && IDENTIFIER_POINTER (declarator)[0] == '_'
10246 && IDENTIFIER_POINTER (declarator)[1] == '_'
10247 && startswith (IDENTIFIER_POINTER (declarator) + 2,
10248 "builtin_"))
10249 || (targetcm.cxx_implicit_extern_c
10250 && (targetcm.cxx_implicit_extern_c
10251 (IDENTIFIER_POINTER (declarator))))))
10252 SET_DECL_LANGUAGE (decl, lang_c);
10254 /* Should probably propagate const out from type to decl I bet (mrs). */
10255 if (staticp)
10257 DECL_STATIC_FUNCTION_P (decl) = 1;
10258 DECL_CONTEXT (decl) = ctype;
10261 if (deletedp)
10262 DECL_DELETED_FN (decl) = 1;
10264 if (ctype && funcdef_flag)
10265 check_class_member_definition_namespace (decl);
10267 if (ctype == NULL_TREE && DECL_MAIN_P (decl))
10269 if (PROCESSING_REAL_TEMPLATE_DECL_P())
10270 error_at (location, "cannot declare %<::main%> to be a template");
10271 if (inlinep & 1)
10272 error_at (declspecs->locations[ds_inline],
10273 "cannot declare %<::main%> to be inline");
10274 if (inlinep & 2)
10275 error_at (declspecs->locations[ds_constexpr],
10276 "cannot declare %<::main%> to be %qs", "constexpr");
10277 if (inlinep & 8)
10278 error_at (declspecs->locations[ds_consteval],
10279 "cannot declare %<::main%> to be %qs", "consteval");
10280 if (!publicp)
10281 error_at (location, "cannot declare %<::main%> to be static");
10282 inlinep = 0;
10283 publicp = 1;
10286 /* Members of anonymous types and local classes have no linkage; make
10287 them internal. If a typedef is made later, this will be changed. */
10288 if (ctype && (!TREE_PUBLIC (TYPE_MAIN_DECL (ctype))
10289 || decl_function_context (TYPE_MAIN_DECL (ctype))))
10290 publicp = 0;
10292 if (publicp && cxx_dialect == cxx98)
10294 /* [basic.link]: A name with no linkage (notably, the name of a class
10295 or enumeration declared in a local scope) shall not be used to
10296 declare an entity with linkage.
10298 DR 757 relaxes this restriction for C++0x. */
10299 no_linkage_error (decl);
10302 TREE_PUBLIC (decl) = publicp;
10303 if (! publicp)
10305 DECL_INTERFACE_KNOWN (decl) = 1;
10306 DECL_NOT_REALLY_EXTERN (decl) = 1;
10309 /* If the declaration was declared inline, mark it as such. */
10310 if (inlinep)
10312 DECL_DECLARED_INLINE_P (decl) = 1;
10313 if (publicp)
10314 DECL_COMDAT (decl) = 1;
10316 if (inlinep & 2)
10317 DECL_DECLARED_CONSTEXPR_P (decl) = true;
10318 else if (inlinep & 8)
10320 DECL_DECLARED_CONSTEXPR_P (decl) = true;
10321 SET_DECL_IMMEDIATE_FUNCTION_P (decl);
10324 // If the concept declaration specifier was found, check
10325 // that the declaration satisfies the necessary requirements.
10326 if (concept_p)
10328 DECL_DECLARED_CONCEPT_P (decl) = true;
10329 check_concept_fn (decl);
10332 DECL_EXTERNAL (decl) = 1;
10333 if (TREE_CODE (type) == FUNCTION_TYPE)
10335 if (quals || rqual)
10336 TREE_TYPE (decl) = apply_memfn_quals (TREE_TYPE (decl),
10337 TYPE_UNQUALIFIED,
10338 REF_QUAL_NONE);
10340 if (quals)
10342 error (ctype
10343 ? G_("static member function %qD cannot have cv-qualifier")
10344 : G_("non-member function %qD cannot have cv-qualifier"),
10345 decl);
10346 quals = TYPE_UNQUALIFIED;
10349 if (rqual)
10351 error (ctype
10352 ? G_("static member function %qD cannot have ref-qualifier")
10353 : G_("non-member function %qD cannot have ref-qualifier"),
10354 decl);
10355 rqual = REF_QUAL_NONE;
10359 if (deduction_guide_p (decl))
10361 tree type = TREE_TYPE (DECL_NAME (decl));
10362 if (in_namespace == NULL_TREE
10363 && CP_DECL_CONTEXT (decl) != CP_TYPE_CONTEXT (type))
10365 error_at (location, "deduction guide %qD must be declared in the "
10366 "same scope as %qT", decl, type);
10367 inform (location_of (type), " declared here");
10368 return NULL_TREE;
10370 if (DECL_CLASS_SCOPE_P (decl)
10371 && current_access_specifier != declared_access (TYPE_NAME (type)))
10373 error_at (location, "deduction guide %qD must have the same access "
10374 "as %qT", decl, type);
10375 inform (location_of (type), " declared here");
10377 if (funcdef_flag)
10378 error_at (location,
10379 "deduction guide %qD must not have a function body", decl);
10381 else if (IDENTIFIER_ANY_OP_P (DECL_NAME (decl))
10382 && !grok_op_properties (decl, /*complain=*/true))
10383 return NULL_TREE;
10384 else if (UDLIT_OPER_P (DECL_NAME (decl)))
10386 bool long_long_unsigned_p;
10387 bool long_double_p;
10388 const char *suffix = NULL;
10389 /* [over.literal]/6: Literal operators shall not have C linkage. */
10390 if (DECL_LANGUAGE (decl) == lang_c)
10392 error_at (location, "literal operator with C linkage");
10393 maybe_show_extern_c_location ();
10394 return NULL_TREE;
10397 if (DECL_NAMESPACE_SCOPE_P (decl))
10399 if (!check_literal_operator_args (decl, &long_long_unsigned_p,
10400 &long_double_p))
10402 error_at (location, "%qD has invalid argument list", decl);
10403 return NULL_TREE;
10406 suffix = UDLIT_OP_SUFFIX (DECL_NAME (decl));
10407 if (long_long_unsigned_p)
10409 if (cpp_interpret_int_suffix (parse_in, suffix, strlen (suffix)))
10410 warning_at (location, 0, "integer suffix %qs"
10411 " shadowed by implementation", suffix);
10413 else if (long_double_p)
10415 if (cpp_interpret_float_suffix (parse_in, suffix, strlen (suffix)))
10416 warning_at (location, 0, "floating-point suffix %qs"
10417 " shadowed by implementation", suffix);
10419 /* 17.6.3.3.5 */
10420 if (suffix[0] != '_'
10421 && !current_function_decl && !(friendp && !funcdef_flag))
10422 warning_at (location, OPT_Wliteral_suffix,
10423 "literal operator suffixes not preceded by %<_%>"
10424 " are reserved for future standardization");
10426 else
10428 error_at (location, "%qD must be a non-member function", decl);
10429 return NULL_TREE;
10433 if (funcdef_flag)
10434 /* Make the init_value nonzero so pushdecl knows this is not
10435 tentative. error_mark_node is replaced later with the BLOCK. */
10436 DECL_INITIAL (decl) = error_mark_node;
10438 if (TYPE_NOTHROW_P (type) || nothrow_libfn_p (decl))
10439 TREE_NOTHROW (decl) = 1;
10441 if (flag_openmp || flag_openmp_simd)
10443 /* Adjust "omp declare simd" attributes. */
10444 tree ods = lookup_attribute ("omp declare simd", *attrlist);
10445 if (ods)
10447 tree attr;
10448 for (attr = ods; attr;
10449 attr = lookup_attribute ("omp declare simd", TREE_CHAIN (attr)))
10451 if (TREE_CODE (type) == METHOD_TYPE)
10452 walk_tree (&TREE_VALUE (attr), declare_simd_adjust_this,
10453 DECL_ARGUMENTS (decl), NULL);
10454 if (TREE_VALUE (attr) != NULL_TREE)
10456 tree cl = TREE_VALUE (TREE_VALUE (attr));
10457 cl = c_omp_declare_simd_clauses_to_numbers
10458 (DECL_ARGUMENTS (decl), cl);
10459 if (cl)
10460 TREE_VALUE (TREE_VALUE (attr)) = cl;
10461 else
10462 TREE_VALUE (attr) = NULL_TREE;
10468 /* Caller will do the rest of this. */
10469 if (check < 0)
10470 return decl;
10472 if (ctype != NULL_TREE)
10473 grokclassfn (ctype, decl, flags);
10475 /* 12.4/3 */
10476 if (cxx_dialect >= cxx11
10477 && DECL_DESTRUCTOR_P (decl)
10478 && !TYPE_BEING_DEFINED (DECL_CONTEXT (decl))
10479 && !processing_template_decl)
10480 deduce_noexcept_on_destructor (decl);
10482 set_originating_module (decl);
10484 decl = check_explicit_specialization (orig_declarator, decl,
10485 template_count,
10486 2 * funcdef_flag +
10487 4 * (friendp != 0) +
10488 8 * concept_p,
10489 *attrlist);
10490 if (decl == error_mark_node)
10491 return NULL_TREE;
10493 if (DECL_STATIC_FUNCTION_P (decl))
10494 check_static_quals (decl, quals);
10496 if (attrlist)
10498 cplus_decl_attributes (&decl, *attrlist, 0);
10499 *attrlist = NULL_TREE;
10502 /* Check main's type after attributes have been applied. */
10503 if (ctype == NULL_TREE && DECL_MAIN_P (decl))
10505 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
10506 integer_type_node))
10508 tree oldtypeargs = TYPE_ARG_TYPES (TREE_TYPE (decl));
10509 tree newtype;
10510 error_at (declspecs->locations[ds_type_spec],
10511 "%<::main%> must return %<int%>");
10512 newtype = build_function_type (integer_type_node, oldtypeargs);
10513 TREE_TYPE (decl) = newtype;
10515 if (warn_main)
10516 check_main_parameter_types (decl);
10519 if (ctype != NULL_TREE && check)
10521 tree old_decl = check_classfn (ctype, decl,
10522 (current_template_depth
10523 > template_class_depth (ctype))
10524 ? current_template_parms
10525 : NULL_TREE);
10527 if (old_decl == error_mark_node)
10528 return NULL_TREE;
10530 if (old_decl)
10532 tree ok;
10533 tree pushed_scope;
10535 if (TREE_CODE (old_decl) == TEMPLATE_DECL)
10536 /* Because grokfndecl is always supposed to return a
10537 FUNCTION_DECL, we pull out the DECL_TEMPLATE_RESULT
10538 here. We depend on our callers to figure out that its
10539 really a template that's being returned. */
10540 old_decl = DECL_TEMPLATE_RESULT (old_decl);
10542 if (DECL_STATIC_FUNCTION_P (old_decl)
10543 && TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
10545 /* Remove the `this' parm added by grokclassfn. */
10546 revert_static_member_fn (decl);
10547 check_static_quals (decl, quals);
10549 if (DECL_ARTIFICIAL (old_decl))
10551 error ("definition of implicitly-declared %qD", old_decl);
10552 return NULL_TREE;
10554 else if (DECL_DEFAULTED_FN (old_decl))
10556 error ("definition of explicitly-defaulted %q+D", decl);
10557 inform (DECL_SOURCE_LOCATION (old_decl),
10558 "%q#D explicitly defaulted here", old_decl);
10559 return NULL_TREE;
10562 /* Since we've smashed OLD_DECL to its
10563 DECL_TEMPLATE_RESULT, we must do the same to DECL. */
10564 if (TREE_CODE (decl) == TEMPLATE_DECL)
10565 decl = DECL_TEMPLATE_RESULT (decl);
10567 /* Attempt to merge the declarations. This can fail, in
10568 the case of some invalid specialization declarations. */
10569 pushed_scope = push_scope (ctype);
10570 ok = duplicate_decls (decl, old_decl);
10571 if (pushed_scope)
10572 pop_scope (pushed_scope);
10573 if (!ok)
10575 error ("no %q#D member function declared in class %qT",
10576 decl, ctype);
10577 return NULL_TREE;
10579 if (ok == error_mark_node)
10580 return NULL_TREE;
10581 return old_decl;
10585 if (DECL_CONSTRUCTOR_P (decl) && !grok_ctor_properties (ctype, decl))
10586 return NULL_TREE;
10588 if (ctype == NULL_TREE || check)
10589 return decl;
10591 if (virtualp)
10592 DECL_VIRTUAL_P (decl) = 1;
10594 return decl;
10597 /* decl is a FUNCTION_DECL.
10598 specifiers are the parsed virt-specifiers.
10600 Set flags to reflect the virt-specifiers.
10602 Returns decl. */
10604 static tree
10605 set_virt_specifiers (tree decl, cp_virt_specifiers specifiers)
10607 if (decl == NULL_TREE)
10608 return decl;
10609 if (specifiers & VIRT_SPEC_OVERRIDE)
10610 DECL_OVERRIDE_P (decl) = 1;
10611 if (specifiers & VIRT_SPEC_FINAL)
10612 DECL_FINAL_P (decl) = 1;
10613 return decl;
10616 /* DECL is a VAR_DECL for a static data member. Set flags to reflect
10617 the linkage that DECL will receive in the object file. */
10619 static void
10620 set_linkage_for_static_data_member (tree decl)
10622 /* A static data member always has static storage duration and
10623 external linkage. Note that static data members are forbidden in
10624 local classes -- the only situation in which a class has
10625 non-external linkage. */
10626 TREE_PUBLIC (decl) = 1;
10627 TREE_STATIC (decl) = 1;
10628 /* For non-template classes, static data members are always put
10629 out in exactly those files where they are defined, just as
10630 with ordinary namespace-scope variables. */
10631 if (!processing_template_decl)
10632 DECL_INTERFACE_KNOWN (decl) = 1;
10635 /* Create a VAR_DECL named NAME with the indicated TYPE.
10637 If SCOPE is non-NULL, it is the class type or namespace containing
10638 the variable. If SCOPE is NULL, the variable should is created in
10639 the innermost enclosing scope. */
10641 static tree
10642 grokvardecl (tree type,
10643 tree name,
10644 tree orig_declarator,
10645 const cp_decl_specifier_seq *declspecs,
10646 int initialized,
10647 int type_quals,
10648 int inlinep,
10649 bool conceptp,
10650 int template_count,
10651 tree scope,
10652 location_t location)
10654 tree decl;
10655 tree explicit_scope;
10657 gcc_assert (!name || identifier_p (name));
10659 bool constp = (type_quals & TYPE_QUAL_CONST) != 0;
10660 bool volatilep = (type_quals & TYPE_QUAL_VOLATILE) != 0;
10662 /* Compute the scope in which to place the variable, but remember
10663 whether or not that scope was explicitly specified by the user. */
10664 explicit_scope = scope;
10665 if (!scope)
10667 /* An explicit "extern" specifier indicates a namespace-scope
10668 variable. */
10669 if (declspecs->storage_class == sc_extern)
10670 scope = current_decl_namespace ();
10671 else if (!at_function_scope_p ())
10672 scope = current_scope ();
10675 if (scope
10676 && (/* If the variable is a namespace-scope variable declared in a
10677 template, we need DECL_LANG_SPECIFIC. */
10678 (TREE_CODE (scope) == NAMESPACE_DECL && processing_template_decl)
10679 /* Similarly for namespace-scope variables with language linkage
10680 other than C++. */
10681 || (TREE_CODE (scope) == NAMESPACE_DECL
10682 && current_lang_name != lang_name_cplusplus)
10683 /* Similarly for static data members. */
10684 || TYPE_P (scope)
10685 /* Similarly for explicit specializations. */
10686 || (orig_declarator
10687 && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)))
10688 decl = build_lang_decl_loc (location, VAR_DECL, name, type);
10689 else
10690 decl = build_decl (location, VAR_DECL, name, type);
10692 if (explicit_scope && TREE_CODE (explicit_scope) == NAMESPACE_DECL)
10693 set_decl_namespace (decl, explicit_scope, 0);
10694 else
10695 DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
10697 if (declspecs->storage_class == sc_extern)
10699 DECL_THIS_EXTERN (decl) = 1;
10700 DECL_EXTERNAL (decl) = !initialized;
10703 if (DECL_CLASS_SCOPE_P (decl))
10705 set_linkage_for_static_data_member (decl);
10706 /* This function is only called with out-of-class definitions. */
10707 DECL_EXTERNAL (decl) = 0;
10708 check_class_member_definition_namespace (decl);
10710 /* At top level, either `static' or no s.c. makes a definition
10711 (perhaps tentative), and absence of `static' makes it public. */
10712 else if (toplevel_bindings_p ())
10714 TREE_PUBLIC (decl) = (declspecs->storage_class != sc_static
10715 && (DECL_THIS_EXTERN (decl)
10716 || ! constp
10717 || volatilep
10718 || inlinep));
10719 TREE_STATIC (decl) = ! DECL_EXTERNAL (decl);
10721 /* Not at top level, only `static' makes a static definition. */
10722 else
10724 TREE_STATIC (decl) = declspecs->storage_class == sc_static;
10725 TREE_PUBLIC (decl) = DECL_EXTERNAL (decl);
10728 set_originating_module (decl);
10730 if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
10732 if (DECL_EXTERNAL (decl) || TREE_STATIC (decl))
10734 CP_DECL_THREAD_LOCAL_P (decl) = true;
10735 if (!processing_template_decl)
10736 set_decl_tls_model (decl, decl_default_tls_model (decl));
10738 if (declspecs->gnu_thread_keyword_p)
10739 SET_DECL_GNU_TLS_P (decl);
10742 /* If the type of the decl has no linkage, make sure that we'll
10743 notice that in mark_used. */
10744 if (cxx_dialect > cxx98
10745 && decl_linkage (decl) != lk_none
10746 && DECL_LANG_SPECIFIC (decl) == NULL
10747 && !DECL_EXTERN_C_P (decl)
10748 && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
10749 retrofit_lang_decl (decl);
10751 if (TREE_PUBLIC (decl))
10753 /* [basic.link]: A name with no linkage (notably, the name of a class
10754 or enumeration declared in a local scope) shall not be used to
10755 declare an entity with linkage.
10757 DR 757 relaxes this restriction for C++0x. */
10758 if (cxx_dialect < cxx11)
10759 no_linkage_error (decl);
10761 else
10762 DECL_INTERFACE_KNOWN (decl) = 1;
10764 if (DECL_NAME (decl)
10765 && MAIN_NAME_P (DECL_NAME (decl))
10766 && scope == global_namespace)
10767 error_at (DECL_SOURCE_LOCATION (decl),
10768 "cannot declare %<::main%> to be a global variable");
10770 /* Check that the variable can be safely declared as a concept.
10771 Note that this also forbids explicit specializations. */
10772 if (conceptp)
10774 if (!processing_template_decl)
10776 error_at (declspecs->locations[ds_concept],
10777 "a non-template variable cannot be %<concept%>");
10778 return NULL_TREE;
10780 else if (!at_namespace_scope_p ())
10782 error_at (declspecs->locations[ds_concept],
10783 "concept must be defined at namespace scope");
10784 return NULL_TREE;
10786 else
10787 DECL_DECLARED_CONCEPT_P (decl) = true;
10788 if (!same_type_ignoring_top_level_qualifiers_p (type, boolean_type_node))
10789 error_at (declspecs->locations[ds_type_spec],
10790 "concept must have type %<bool%>");
10791 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
10793 error_at (location, "a variable concept cannot be constrained");
10794 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
10797 else if (flag_concepts
10798 && current_template_depth > template_class_depth (scope))
10800 tree ci = current_template_constraints ();
10801 set_constraints (decl, ci);
10804 // Handle explicit specializations and instantiations of variable templates.
10805 if (orig_declarator)
10806 decl = check_explicit_specialization (orig_declarator, decl,
10807 template_count, conceptp * 8);
10809 return decl != error_mark_node ? decl : NULL_TREE;
10812 /* Create and return a canonical pointer to member function type, for
10813 TYPE, which is a POINTER_TYPE to a METHOD_TYPE. */
10815 tree
10816 build_ptrmemfunc_type (tree type)
10818 tree field, fields;
10819 tree t;
10821 if (type == error_mark_node)
10822 return type;
10824 /* Make sure that we always have the unqualified pointer-to-member
10825 type first. */
10826 if (cp_cv_quals quals = cp_type_quals (type))
10828 tree unqual = build_ptrmemfunc_type (TYPE_MAIN_VARIANT (type));
10829 return cp_build_qualified_type (unqual, quals);
10832 /* If a canonical type already exists for this type, use it. We use
10833 this method instead of type_hash_canon, because it only does a
10834 simple equality check on the list of field members. */
10836 t = TYPE_PTRMEMFUNC_TYPE (type);
10837 if (t)
10838 return t;
10840 t = make_node (RECORD_TYPE);
10842 /* Let the front end know this is a pointer to member function. */
10843 TYPE_PTRMEMFUNC_FLAG (t) = 1;
10845 field = build_decl (input_location, FIELD_DECL, pfn_identifier, type);
10846 DECL_NONADDRESSABLE_P (field) = 1;
10847 fields = field;
10849 field = build_decl (input_location, FIELD_DECL, delta_identifier,
10850 delta_type_node);
10851 DECL_NONADDRESSABLE_P (field) = 1;
10852 DECL_CHAIN (field) = fields;
10853 fields = field;
10855 finish_builtin_struct (t, "__ptrmemfunc_type", fields, ptr_type_node);
10857 /* Zap out the name so that the back end will give us the debugging
10858 information for this anonymous RECORD_TYPE. */
10859 TYPE_NAME (t) = NULL_TREE;
10861 /* Cache this pointer-to-member type so that we can find it again
10862 later. */
10863 TYPE_PTRMEMFUNC_TYPE (type) = t;
10865 if (TYPE_STRUCTURAL_EQUALITY_P (type))
10866 SET_TYPE_STRUCTURAL_EQUALITY (t);
10867 else if (TYPE_CANONICAL (type) != type)
10868 TYPE_CANONICAL (t) = build_ptrmemfunc_type (TYPE_CANONICAL (type));
10870 return t;
10873 /* Create and return a pointer to data member type. */
10875 tree
10876 build_ptrmem_type (tree class_type, tree member_type)
10878 if (TREE_CODE (member_type) == METHOD_TYPE)
10880 cp_cv_quals quals = type_memfn_quals (member_type);
10881 cp_ref_qualifier rqual = type_memfn_rqual (member_type);
10882 member_type = build_memfn_type (member_type, class_type, quals, rqual);
10883 return build_ptrmemfunc_type (build_pointer_type (member_type));
10885 else
10887 gcc_assert (TREE_CODE (member_type) != FUNCTION_TYPE);
10888 return build_offset_type (class_type, member_type);
10892 /* DECL is a VAR_DECL defined in-class, whose TYPE is also given.
10893 Check to see that the definition is valid. Issue appropriate error
10894 messages. */
10896 static void
10897 check_static_variable_definition (tree decl, tree type)
10899 /* Avoid redundant diagnostics on out-of-class definitions. */
10900 if (!current_class_type || !TYPE_BEING_DEFINED (current_class_type))
10902 /* Can't check yet if we don't know the type. */
10903 else if (dependent_type_p (type))
10905 /* If DECL is declared constexpr, we'll do the appropriate checks
10906 in check_initializer. Similarly for inline static data members. */
10907 else if (DECL_P (decl)
10908 && (DECL_DECLARED_CONSTEXPR_P (decl)
10909 || DECL_VAR_DECLARED_INLINE_P (decl)))
10911 else if (cxx_dialect >= cxx11 && !INTEGRAL_OR_ENUMERATION_TYPE_P (type))
10913 if (!COMPLETE_TYPE_P (type))
10914 error_at (DECL_SOURCE_LOCATION (decl),
10915 "in-class initialization of static data member %q#D of "
10916 "incomplete type", decl);
10917 else if (literal_type_p (type))
10918 permerror (DECL_SOURCE_LOCATION (decl),
10919 "%<constexpr%> needed for in-class initialization of "
10920 "static data member %q#D of non-integral type", decl);
10921 else
10922 error_at (DECL_SOURCE_LOCATION (decl),
10923 "in-class initialization of static data member %q#D of "
10924 "non-literal type", decl);
10926 /* Motion 10 at San Diego: If a static const integral data member is
10927 initialized with an integral constant expression, the initializer
10928 may appear either in the declaration (within the class), or in
10929 the definition, but not both. If it appears in the class, the
10930 member is a member constant. The file-scope definition is always
10931 required. */
10932 else if (!ARITHMETIC_TYPE_P (type) && TREE_CODE (type) != ENUMERAL_TYPE)
10933 error_at (DECL_SOURCE_LOCATION (decl),
10934 "invalid in-class initialization of static data member "
10935 "of non-integral type %qT",
10936 type);
10937 else if (!CP_TYPE_CONST_P (type))
10938 error_at (DECL_SOURCE_LOCATION (decl),
10939 "ISO C++ forbids in-class initialization of non-const "
10940 "static member %qD",
10941 decl);
10942 else if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type))
10943 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
10944 "ISO C++ forbids initialization of member constant "
10945 "%qD of non-integral type %qT", decl, type);
10948 /* *expr_p is part of the TYPE_SIZE of a variably-sized array. If any
10949 SAVE_EXPRs in *expr_p wrap expressions with side-effects, break those
10950 expressions out into temporary variables so that walk_tree doesn't
10951 step into them (c++/15764). */
10953 static tree
10954 stabilize_save_expr_r (tree *expr_p, int *walk_subtrees, void *data)
10956 hash_set<tree> *pset = (hash_set<tree> *)data;
10957 tree expr = *expr_p;
10958 if (TREE_CODE (expr) == SAVE_EXPR)
10960 tree op = TREE_OPERAND (expr, 0);
10961 cp_walk_tree (&op, stabilize_save_expr_r, data, pset);
10962 if (TREE_SIDE_EFFECTS (op))
10963 TREE_OPERAND (expr, 0) = get_temp_regvar (TREE_TYPE (op), op);
10964 *walk_subtrees = 0;
10966 else if (!EXPR_P (expr) || !TREE_SIDE_EFFECTS (expr))
10967 *walk_subtrees = 0;
10968 return NULL;
10971 /* Entry point for the above. */
10973 static void
10974 stabilize_vla_size (tree size)
10976 hash_set<tree> pset;
10977 /* Break out any function calls into temporary variables. */
10978 cp_walk_tree (&size, stabilize_save_expr_r, &pset, &pset);
10981 /* Reduce a SIZEOF_EXPR to its value. */
10983 tree
10984 fold_sizeof_expr (tree t)
10986 tree r;
10987 if (SIZEOF_EXPR_TYPE_P (t))
10988 r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
10989 TREE_TYPE (TREE_OPERAND (t, 0)),
10990 SIZEOF_EXPR, false, false);
10991 else if (TYPE_P (TREE_OPERAND (t, 0)))
10992 r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
10993 TREE_OPERAND (t, 0), SIZEOF_EXPR,
10994 false, false);
10995 else
10996 r = cxx_sizeof_or_alignof_expr (EXPR_LOCATION (t),
10997 TREE_OPERAND (t, 0), SIZEOF_EXPR,
10998 false, false);
10999 if (r == error_mark_node)
11000 r = size_one_node;
11001 return r;
11004 /* Given the SIZE (i.e., number of elements) in an array, compute
11005 an appropriate index type for the array. If non-NULL, NAME is
11006 the name of the entity being declared. */
11008 static tree
11009 compute_array_index_type_loc (location_t name_loc, tree name, tree size,
11010 tsubst_flags_t complain)
11012 if (error_operand_p (size))
11013 return error_mark_node;
11015 /* The type of the index being computed. */
11016 tree itype;
11018 /* The original numeric size as seen in the source code before
11019 conversion to size_t. */
11020 tree origsize = size;
11022 location_t loc = cp_expr_loc_or_loc (size, name ? name_loc : input_location);
11024 if (!type_dependent_expression_p (size))
11026 origsize = size = mark_rvalue_use (size);
11028 if (cxx_dialect < cxx11 && TREE_CODE (size) == NOP_EXPR
11029 && TREE_SIDE_EFFECTS (size))
11030 /* In C++98, we mark a non-constant array bound with a magic
11031 NOP_EXPR with TREE_SIDE_EFFECTS; don't fold in that case. */;
11032 else
11034 size = build_converted_constant_expr (size_type_node, size, complain);
11035 /* Pedantically a constant expression is required here and so
11036 __builtin_is_constant_evaluated () should fold to true if it
11037 is successfully folded into a constant. */
11038 size = fold_non_dependent_expr (size, complain,
11039 /*manifestly_const_eval=*/true);
11041 if (!TREE_CONSTANT (size))
11042 size = origsize;
11045 if (error_operand_p (size))
11046 return error_mark_node;
11048 /* The array bound must be an integer type. */
11049 tree type = TREE_TYPE (size);
11050 if (!INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
11052 if (!(complain & tf_error))
11053 return error_mark_node;
11054 if (name)
11055 error_at (loc, "size of array %qD has non-integral type %qT",
11056 name, type);
11057 else
11058 error_at (loc, "size of array has non-integral type %qT", type);
11059 size = integer_one_node;
11063 /* A type is dependent if it is...an array type constructed from any
11064 dependent type or whose size is specified by a constant expression
11065 that is value-dependent. */
11066 /* We can only call value_dependent_expression_p on integral constant
11067 expressions. */
11068 if (processing_template_decl
11069 && potential_constant_expression (size)
11070 && value_dependent_expression_p (size))
11072 /* Just build the index type and mark that it requires
11073 structural equality checks. */
11074 in_template:
11075 itype = build_index_type (build_min (MINUS_EXPR, sizetype,
11076 size, size_one_node));
11077 TYPE_DEPENDENT_P (itype) = 1;
11078 TYPE_DEPENDENT_P_VALID (itype) = 1;
11079 SET_TYPE_STRUCTURAL_EQUALITY (itype);
11080 return itype;
11083 if (TREE_CODE (size) != INTEGER_CST)
11085 tree folded = cp_fully_fold (size);
11086 if (TREE_CODE (folded) == INTEGER_CST)
11088 if (name)
11089 pedwarn (loc, OPT_Wpedantic, "size of array %qD is not an "
11090 "integral constant-expression", name);
11091 else
11092 pedwarn (loc, OPT_Wpedantic,
11093 "size of array is not an integral constant-expression");
11095 if (TREE_CONSTANT (size) && !TREE_CONSTANT (folded))
11096 /* We might have lost the TREE_CONSTANT flag e.g. when we are
11097 folding a conversion from a pointer to integral type. In that
11098 case issue an error below and don't treat this as a VLA. */;
11099 else
11100 /* Use the folded result for VLAs, too; it will have resolved
11101 SIZEOF_EXPR. */
11102 size = folded;
11105 /* Normally, the array-bound will be a constant. */
11106 if (TREE_CODE (size) == INTEGER_CST)
11108 /* The size to use in diagnostics that reflects the constant
11109 size used in the source, rather than SIZE massaged above. */
11110 tree diagsize = size;
11112 /* If the original size before conversion to size_t was signed
11113 and negative, convert it to ssizetype to restore the sign. */
11114 if (!TYPE_UNSIGNED (TREE_TYPE (origsize))
11115 && TREE_CODE (size) == INTEGER_CST
11116 && tree_int_cst_sign_bit (size))
11118 diagsize = fold_convert (ssizetype, size);
11120 /* Clear the overflow bit that may have been set as a result
11121 of the conversion from the sizetype of the new size to
11122 ssizetype. */
11123 TREE_OVERFLOW (diagsize) = false;
11126 /* Verify that the array has a positive number of elements
11127 and issue the appropriate diagnostic if it doesn't. */
11128 if (!valid_array_size_p (loc, diagsize, name, (complain & tf_error)))
11130 if (!(complain & tf_error))
11131 return error_mark_node;
11132 size = integer_one_node;
11134 /* As an extension we allow zero-sized arrays. */
11135 else if (integer_zerop (size))
11137 if (!(complain & tf_error))
11138 /* We must fail if performing argument deduction (as
11139 indicated by the state of complain), so that
11140 another substitution can be found. */
11141 return error_mark_node;
11142 else if (name)
11143 pedwarn (loc, OPT_Wpedantic,
11144 "ISO C++ forbids zero-size array %qD", name);
11145 else
11146 pedwarn (loc, OPT_Wpedantic,
11147 "ISO C++ forbids zero-size array");
11150 else if (TREE_CONSTANT (size)
11151 /* We don't allow VLAs at non-function scopes, or during
11152 tentative template substitution. */
11153 || !at_function_scope_p ()
11154 || !(complain & tf_error))
11156 if (!(complain & tf_error))
11157 return error_mark_node;
11158 /* `(int) &fn' is not a valid array bound. */
11159 if (name)
11160 error_at (loc,
11161 "size of array %qD is not an integral constant-expression",
11162 name);
11163 else
11164 error_at (loc, "size of array is not an integral constant-expression");
11165 size = integer_one_node;
11167 else if (pedantic && warn_vla != 0)
11169 if (name)
11170 pedwarn (name_loc, OPT_Wvla,
11171 "ISO C++ forbids variable length array %qD", name);
11172 else
11173 pedwarn (input_location, OPT_Wvla,
11174 "ISO C++ forbids variable length array");
11176 else if (warn_vla > 0)
11178 if (name)
11179 warning_at (name_loc, OPT_Wvla,
11180 "variable length array %qD is used", name);
11181 else
11182 warning (OPT_Wvla,
11183 "variable length array is used");
11186 if (processing_template_decl && !TREE_CONSTANT (size))
11187 goto in_template;
11188 else
11190 if (!TREE_CONSTANT (size))
11192 /* A variable sized array. Arrange for the SAVE_EXPR on the inside
11193 of the MINUS_EXPR, which allows the -1 to get folded with the +1
11194 that happens when building TYPE_SIZE. */
11195 size = variable_size (size);
11196 stabilize_vla_size (size);
11199 /* Compute the index of the largest element in the array. It is
11200 one less than the number of elements in the array. We save
11201 and restore PROCESSING_TEMPLATE_DECL so that computations in
11202 cp_build_binary_op will be appropriately folded. */
11204 processing_template_decl_sentinel s;
11205 itype = cp_build_binary_op (input_location,
11206 MINUS_EXPR,
11207 cp_convert (ssizetype, size, complain),
11208 cp_convert (ssizetype, integer_one_node,
11209 complain),
11210 complain);
11211 itype = maybe_constant_value (itype, NULL_TREE, true);
11214 if (!TREE_CONSTANT (itype))
11216 if (sanitize_flags_p (SANITIZE_VLA)
11217 && current_function_decl != NULL_TREE)
11219 /* We have to add 1 -- in the ubsan routine we generate
11220 LE_EXPR rather than LT_EXPR. */
11221 tree t = fold_build2 (PLUS_EXPR, TREE_TYPE (itype), itype,
11222 build_one_cst (TREE_TYPE (itype)));
11223 t = ubsan_instrument_vla (input_location, t);
11224 finish_expr_stmt (t);
11227 /* Make sure that there was no overflow when creating to a signed
11228 index type. (For example, on a 32-bit machine, an array with
11229 size 2^32 - 1 is too big.) */
11230 else if (TREE_CODE (itype) == INTEGER_CST
11231 && TREE_OVERFLOW (itype))
11233 if (!(complain & tf_error))
11234 return error_mark_node;
11235 error ("overflow in array dimension");
11236 TREE_OVERFLOW (itype) = 0;
11240 /* Create and return the appropriate index type. */
11241 itype = build_index_type (itype);
11243 /* If the index type were dependent, we would have returned early, so
11244 remember that it isn't. */
11245 TYPE_DEPENDENT_P (itype) = 0;
11246 TYPE_DEPENDENT_P_VALID (itype) = 1;
11247 return itype;
11250 tree
11251 compute_array_index_type (tree name, tree size, tsubst_flags_t complain)
11253 return compute_array_index_type_loc (input_location, name, size, complain);
11256 /* Returns the scope (if any) in which the entity declared by
11257 DECLARATOR will be located. If the entity was declared with an
11258 unqualified name, NULL_TREE is returned. */
11260 tree
11261 get_scope_of_declarator (const cp_declarator *declarator)
11263 while (declarator && declarator->kind != cdk_id)
11264 declarator = declarator->declarator;
11266 /* If the declarator-id is a SCOPE_REF, the scope in which the
11267 declaration occurs is the first operand. */
11268 if (declarator
11269 && declarator->u.id.qualifying_scope)
11270 return declarator->u.id.qualifying_scope;
11272 /* Otherwise, the declarator is not a qualified name; the entity will
11273 be declared in the current scope. */
11274 return NULL_TREE;
11277 /* Returns an ARRAY_TYPE for an array with SIZE elements of the
11278 indicated TYPE. If non-NULL, NAME is the NAME of the declaration
11279 with this type. */
11281 static tree
11282 create_array_type_for_decl (tree name, tree type, tree size, location_t loc)
11284 tree itype = NULL_TREE;
11286 /* If things have already gone awry, bail now. */
11287 if (type == error_mark_node || size == error_mark_node)
11288 return error_mark_node;
11290 /* [dcl.type.class.deduct] prohibits forming an array of placeholder
11291 for a deduced class type. */
11292 if (template_placeholder_p (type))
11294 if (name)
11295 error_at (loc, "%qD declared as array of template placeholder "
11296 "type %qT", name, type);
11297 else
11298 error ("creating array of template placeholder type %qT", type);
11299 return error_mark_node;
11302 /* If there are some types which cannot be array elements,
11303 issue an error-message and return. */
11304 switch (TREE_CODE (type))
11306 case VOID_TYPE:
11307 if (name)
11308 error_at (loc, "declaration of %qD as array of void", name);
11309 else
11310 error ("creating array of void");
11311 return error_mark_node;
11313 case FUNCTION_TYPE:
11314 if (name)
11315 error_at (loc, "declaration of %qD as array of functions", name);
11316 else
11317 error ("creating array of functions");
11318 return error_mark_node;
11320 case REFERENCE_TYPE:
11321 if (name)
11322 error_at (loc, "declaration of %qD as array of references", name);
11323 else
11324 error ("creating array of references");
11325 return error_mark_node;
11327 case METHOD_TYPE:
11328 if (name)
11329 error_at (loc, "declaration of %qD as array of function members",
11330 name);
11331 else
11332 error ("creating array of function members");
11333 return error_mark_node;
11335 default:
11336 break;
11339 if (!verify_type_context (name ? loc : input_location,
11340 TCTX_ARRAY_ELEMENT, type))
11341 return error_mark_node;
11343 /* [dcl.array]
11345 The constant expressions that specify the bounds of the arrays
11346 can be omitted only for the first member of the sequence. */
11347 if (TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type))
11349 if (name)
11350 error_at (loc, "declaration of %qD as multidimensional array must "
11351 "have bounds for all dimensions except the first",
11352 name);
11353 else
11354 error ("multidimensional array must have bounds for all "
11355 "dimensions except the first");
11357 return error_mark_node;
11360 /* Figure out the index type for the array. */
11361 if (size)
11363 itype = compute_array_index_type_loc (loc, name, size,
11364 tf_warning_or_error);
11365 if (type_uses_auto (type)
11366 && variably_modified_type_p (itype, /*fn=*/NULL_TREE))
11368 sorry_at (loc, "variable-length array of %<auto%>");
11369 return error_mark_node;
11373 return build_cplus_array_type (type, itype);
11376 /* Returns the smallest location that is not UNKNOWN_LOCATION. */
11378 static location_t
11379 min_location (location_t loca, location_t locb)
11381 if (loca == UNKNOWN_LOCATION
11382 || (locb != UNKNOWN_LOCATION
11383 && linemap_location_before_p (line_table, locb, loca)))
11384 return locb;
11385 return loca;
11388 /* Returns the smallest location != UNKNOWN_LOCATION among the
11389 three stored in LOCATIONS[ds_const], LOCATIONS[ds_volatile],
11390 and LOCATIONS[ds_restrict]. */
11392 static location_t
11393 smallest_type_quals_location (int type_quals, const location_t* locations)
11395 location_t loc = UNKNOWN_LOCATION;
11397 if (type_quals & TYPE_QUAL_CONST)
11398 loc = locations[ds_const];
11400 if (type_quals & TYPE_QUAL_VOLATILE)
11401 loc = min_location (loc, locations[ds_volatile]);
11403 if (type_quals & TYPE_QUAL_RESTRICT)
11404 loc = min_location (loc, locations[ds_restrict]);
11406 return loc;
11409 /* Returns the smallest among the latter and locations[ds_type_spec]. */
11411 static location_t
11412 smallest_type_location (int type_quals, const location_t* locations)
11414 location_t loc = smallest_type_quals_location (type_quals, locations);
11415 return min_location (loc, locations[ds_type_spec]);
11418 static location_t
11419 smallest_type_location (const cp_decl_specifier_seq *declspecs)
11421 int type_quals = get_type_quals (declspecs);
11422 return smallest_type_location (type_quals, declspecs->locations);
11425 /* Check that it's OK to declare a function with the indicated TYPE
11426 and TYPE_QUALS. SFK indicates the kind of special function (if any)
11427 that this function is. OPTYPE is the type given in a conversion
11428 operator declaration, or the class type for a constructor/destructor.
11429 Returns the actual return type of the function; that may be different
11430 than TYPE if an error occurs, or for certain special functions. */
11432 static tree
11433 check_special_function_return_type (special_function_kind sfk,
11434 tree type,
11435 tree optype,
11436 int type_quals,
11437 const location_t* locations)
11439 switch (sfk)
11441 case sfk_constructor:
11442 if (type)
11443 error_at (smallest_type_location (type_quals, locations),
11444 "return type specification for constructor invalid");
11445 else if (type_quals != TYPE_UNQUALIFIED)
11446 error_at (smallest_type_quals_location (type_quals, locations),
11447 "qualifiers are not allowed on constructor declaration");
11449 if (targetm.cxx.cdtor_returns_this ())
11450 type = build_pointer_type (optype);
11451 else
11452 type = void_type_node;
11453 break;
11455 case sfk_destructor:
11456 if (type)
11457 error_at (smallest_type_location (type_quals, locations),
11458 "return type specification for destructor invalid");
11459 else if (type_quals != TYPE_UNQUALIFIED)
11460 error_at (smallest_type_quals_location (type_quals, locations),
11461 "qualifiers are not allowed on destructor declaration");
11463 /* We can't use the proper return type here because we run into
11464 problems with ambiguous bases and covariant returns. */
11465 if (targetm.cxx.cdtor_returns_this ())
11466 type = build_pointer_type (void_type_node);
11467 else
11468 type = void_type_node;
11469 break;
11471 case sfk_conversion:
11472 if (type)
11473 error_at (smallest_type_location (type_quals, locations),
11474 "return type specified for %<operator %T%>", optype);
11475 else if (type_quals != TYPE_UNQUALIFIED)
11476 error_at (smallest_type_quals_location (type_quals, locations),
11477 "qualifiers are not allowed on declaration of "
11478 "%<operator %T%>", optype);
11480 type = optype;
11481 break;
11483 case sfk_deduction_guide:
11484 if (type)
11485 error_at (smallest_type_location (type_quals, locations),
11486 "return type specified for deduction guide");
11487 else if (type_quals != TYPE_UNQUALIFIED)
11488 error_at (smallest_type_quals_location (type_quals, locations),
11489 "qualifiers are not allowed on declaration of "
11490 "deduction guide");
11491 if (TREE_CODE (optype) == TEMPLATE_TEMPLATE_PARM)
11493 error ("template template parameter %qT in declaration of "
11494 "deduction guide", optype);
11495 type = error_mark_node;
11497 else
11498 type = make_template_placeholder (CLASSTYPE_TI_TEMPLATE (optype));
11499 for (int i = 0; i < ds_last; ++i)
11500 if (i != ds_explicit && locations[i])
11501 error_at (locations[i],
11502 "%<decl-specifier%> in declaration of deduction guide");
11503 break;
11505 default:
11506 gcc_unreachable ();
11509 return type;
11512 /* A variable or data member (whose unqualified name is IDENTIFIER)
11513 has been declared with the indicated TYPE. If the TYPE is not
11514 acceptable, issue an error message and return a type to use for
11515 error-recovery purposes. */
11517 tree
11518 check_var_type (tree identifier, tree type, location_t loc)
11520 if (VOID_TYPE_P (type))
11522 if (!identifier)
11523 error_at (loc, "unnamed variable or field declared void");
11524 else if (identifier_p (identifier))
11526 gcc_assert (!IDENTIFIER_ANY_OP_P (identifier));
11527 error_at (loc, "variable or field %qE declared void",
11528 identifier);
11530 else
11531 error_at (loc, "variable or field declared void");
11532 type = error_mark_node;
11535 return type;
11538 /* Handle declaring DECL as an inline variable. */
11540 static void
11541 mark_inline_variable (tree decl, location_t loc)
11543 bool inlinep = true;
11544 if (! toplevel_bindings_p ())
11546 error_at (loc, "%<inline%> specifier invalid for variable "
11547 "%qD declared at block scope", decl);
11548 inlinep = false;
11550 else if (cxx_dialect < cxx17)
11551 pedwarn (loc, OPT_Wc__17_extensions, "inline variables are only available "
11552 "with %<-std=c++17%> or %<-std=gnu++17%>");
11553 if (inlinep)
11555 retrofit_lang_decl (decl);
11556 SET_DECL_VAR_DECLARED_INLINE_P (decl);
11561 /* Assign a typedef-given name to a class or enumeration type declared
11562 as anonymous at first. This was split out of grokdeclarator
11563 because it is also used in libcc1. */
11565 void
11566 name_unnamed_type (tree type, tree decl)
11568 gcc_assert (TYPE_UNNAMED_P (type));
11570 /* Replace the anonymous decl with the real decl. Be careful not to
11571 rename other typedefs (such as the self-reference) of type. */
11572 tree orig = TYPE_NAME (type);
11573 for (tree t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
11574 if (TYPE_NAME (t) == orig)
11575 TYPE_NAME (t) = decl;
11577 /* If this is a typedef within a template class, the nested
11578 type is a (non-primary) template. The name for the
11579 template needs updating as well. */
11580 if (TYPE_LANG_SPECIFIC (type) && CLASSTYPE_TEMPLATE_INFO (type))
11581 DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)) = DECL_NAME (decl);
11583 /* Adjust linkage now that we aren't unnamed anymore. */
11584 reset_type_linkage (type);
11586 /* FIXME remangle member functions; member functions of a
11587 type with external linkage have external linkage. */
11589 /* Check that our job is done, and that it would fail if we
11590 attempted to do it again. */
11591 gcc_assert (!TYPE_UNNAMED_P (type));
11594 /* Check that decltype(auto) was well-formed: only plain decltype(auto)
11595 is allowed. TYPE might contain a decltype(auto). Returns true if
11596 there was a problem, false otherwise. */
11598 static bool
11599 check_decltype_auto (location_t loc, tree type)
11601 if (tree a = type_uses_auto (type))
11603 if (AUTO_IS_DECLTYPE (a))
11605 if (a != type)
11607 error_at (loc, "%qT as type rather than plain "
11608 "%<decltype(auto)%>", type);
11609 return true;
11611 else if (TYPE_QUALS (type) != TYPE_UNQUALIFIED)
11613 error_at (loc, "%<decltype(auto)%> cannot be cv-qualified");
11614 return true;
11618 return false;
11621 /* Given declspecs and a declarator (abstract or otherwise), determine
11622 the name and type of the object declared and construct a DECL node
11623 for it.
11625 DECLSPECS points to the representation of declaration-specifier
11626 sequence that precedes declarator.
11628 DECL_CONTEXT says which syntactic context this declaration is in:
11629 NORMAL for most contexts. Make a VAR_DECL or FUNCTION_DECL or TYPE_DECL.
11630 FUNCDEF for a function definition. Like NORMAL but a few different
11631 error messages in each case. Return value may be zero meaning
11632 this definition is too screwy to try to parse.
11633 MEMFUNCDEF for a function definition. Like FUNCDEF but prepares to
11634 handle member functions (which have FIELD context).
11635 Return value may be zero meaning this definition is too screwy to
11636 try to parse.
11637 PARM for a parameter declaration (either within a function prototype
11638 or before a function body). Make a PARM_DECL, or return void_type_node.
11639 TPARM for a template parameter declaration.
11640 CATCHPARM for a parameter declaration before a catch clause.
11641 TYPENAME if for a typename (in a cast or sizeof).
11642 Don't make a DECL node; just return the ..._TYPE node.
11643 FIELD for a struct or union field; make a FIELD_DECL.
11644 BITFIELD for a field with specified width.
11646 INITIALIZED is as for start_decl.
11648 ATTRLIST is a pointer to the list of attributes, which may be NULL
11649 if there are none; *ATTRLIST may be modified if attributes from inside
11650 the declarator should be applied to the declaration.
11652 When this function is called, scoping variables (such as
11653 CURRENT_CLASS_TYPE) should reflect the scope in which the
11654 declaration occurs, not the scope in which the new declaration will
11655 be placed. For example, on:
11657 void S::f() { ... }
11659 when grokdeclarator is called for `S::f', the CURRENT_CLASS_TYPE
11660 should not be `S'.
11662 Returns a DECL (if a declarator is present), a TYPE (if there is no
11663 declarator, in cases like "struct S;"), or the ERROR_MARK_NODE if an
11664 error occurs. */
11666 tree
11667 grokdeclarator (const cp_declarator *declarator,
11668 cp_decl_specifier_seq *declspecs,
11669 enum decl_context decl_context,
11670 int initialized,
11671 tree* attrlist)
11673 tree type = NULL_TREE;
11674 int longlong = 0;
11675 int explicit_intN = 0;
11676 int int_n_alt = 0;
11677 int virtualp, explicitp, friendp, inlinep, staticp;
11678 int explicit_int = 0;
11679 int explicit_char = 0;
11680 int defaulted_int = 0;
11682 tree typedef_decl = NULL_TREE;
11683 const char *name = NULL;
11684 tree typedef_type = NULL_TREE;
11685 /* True if this declarator is a function definition. */
11686 bool funcdef_flag = false;
11687 cp_declarator_kind innermost_code = cdk_error;
11688 int bitfield = 0;
11689 #if 0
11690 /* See the code below that used this. */
11691 tree decl_attr = NULL_TREE;
11692 #endif
11694 /* Keep track of what sort of function is being processed
11695 so that we can warn about default return values, or explicit
11696 return values which do not match prescribed defaults. */
11697 special_function_kind sfk = sfk_none;
11699 tree dname = NULL_TREE;
11700 tree ctor_return_type = NULL_TREE;
11701 enum overload_flags flags = NO_SPECIAL;
11702 /* cv-qualifiers that apply to the declarator, for a declaration of
11703 a member function. */
11704 cp_cv_quals memfn_quals = TYPE_UNQUALIFIED;
11705 /* virt-specifiers that apply to the declarator, for a declaration of
11706 a member function. */
11707 cp_virt_specifiers virt_specifiers = VIRT_SPEC_UNSPECIFIED;
11708 /* ref-qualifier that applies to the declarator, for a declaration of
11709 a member function. */
11710 cp_ref_qualifier rqual = REF_QUAL_NONE;
11711 /* cv-qualifiers that apply to the type specified by the DECLSPECS. */
11712 int type_quals = get_type_quals (declspecs);
11713 tree raises = NULL_TREE;
11714 int template_count = 0;
11715 tree returned_attrs = NULL_TREE;
11716 tree parms = NULL_TREE;
11717 const cp_declarator *id_declarator;
11718 /* The unqualified name of the declarator; either an
11719 IDENTIFIER_NODE, BIT_NOT_EXPR, or TEMPLATE_ID_EXPR. */
11720 tree unqualified_id;
11721 /* The class type, if any, in which this entity is located,
11722 or NULL_TREE if none. Note that this value may be different from
11723 the current class type; for example if an attempt is made to declare
11724 "A::f" inside "B", this value will be "A". */
11725 tree ctype = current_class_type;
11726 /* The NAMESPACE_DECL for the namespace in which this entity is
11727 located. If an unqualified name is used to declare the entity,
11728 this value will be NULL_TREE, even if the entity is located at
11729 namespace scope. */
11730 tree in_namespace = NULL_TREE;
11731 cp_storage_class storage_class;
11732 bool unsigned_p, signed_p, short_p, long_p, thread_p;
11733 bool type_was_error_mark_node = false;
11734 bool parameter_pack_p = declarator ? declarator->parameter_pack_p : false;
11735 bool template_type_arg = false;
11736 bool template_parm_flag = false;
11737 bool typedef_p = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
11738 bool constexpr_p = decl_spec_seq_has_spec_p (declspecs, ds_constexpr);
11739 bool constinit_p = decl_spec_seq_has_spec_p (declspecs, ds_constinit);
11740 bool consteval_p = decl_spec_seq_has_spec_p (declspecs, ds_consteval);
11741 bool late_return_type_p = false;
11742 bool array_parameter_p = false;
11743 tree reqs = NULL_TREE;
11745 signed_p = decl_spec_seq_has_spec_p (declspecs, ds_signed);
11746 unsigned_p = decl_spec_seq_has_spec_p (declspecs, ds_unsigned);
11747 short_p = decl_spec_seq_has_spec_p (declspecs, ds_short);
11748 long_p = decl_spec_seq_has_spec_p (declspecs, ds_long);
11749 longlong = decl_spec_seq_has_spec_p (declspecs, ds_long_long);
11750 explicit_intN = declspecs->explicit_intN_p;
11751 int_n_alt = declspecs->int_n_alt;
11752 thread_p = decl_spec_seq_has_spec_p (declspecs, ds_thread);
11754 // Was concept_p specified? Note that ds_concept
11755 // implies ds_constexpr!
11756 bool concept_p = decl_spec_seq_has_spec_p (declspecs, ds_concept);
11757 if (concept_p)
11758 constexpr_p = true;
11760 if (decl_context == FUNCDEF)
11761 funcdef_flag = true, decl_context = NORMAL;
11762 else if (decl_context == MEMFUNCDEF)
11763 funcdef_flag = true, decl_context = FIELD;
11764 else if (decl_context == BITFIELD)
11765 bitfield = 1, decl_context = FIELD;
11766 else if (decl_context == TEMPLATE_TYPE_ARG)
11767 template_type_arg = true, decl_context = TYPENAME;
11768 else if (decl_context == TPARM)
11769 template_parm_flag = true, decl_context = PARM;
11771 if (initialized == SD_DEFAULTED || initialized == SD_DELETED)
11772 funcdef_flag = true;
11774 location_t typespec_loc = loc_or_input_loc (smallest_type_location
11775 (type_quals,
11776 declspecs->locations));
11777 location_t id_loc;
11778 location_t init_loc;
11779 if (declarator)
11781 id_loc = loc_or_input_loc (declarator->id_loc);
11782 init_loc = loc_or_input_loc (declarator->init_loc);
11784 else
11785 init_loc = id_loc = input_location;
11787 /* Look inside a declarator for the name being declared
11788 and get it as a string, for an error message. */
11789 for (id_declarator = declarator;
11790 id_declarator;
11791 id_declarator = id_declarator->declarator)
11793 if (id_declarator->kind != cdk_id)
11794 innermost_code = id_declarator->kind;
11796 switch (id_declarator->kind)
11798 case cdk_function:
11799 if (id_declarator->declarator
11800 && id_declarator->declarator->kind == cdk_id)
11802 sfk = id_declarator->declarator->u.id.sfk;
11803 if (sfk == sfk_destructor)
11804 flags = DTOR_FLAG;
11806 break;
11808 case cdk_id:
11810 tree qualifying_scope = id_declarator->u.id.qualifying_scope;
11811 tree decl = id_declarator->u.id.unqualified_name;
11812 if (!decl)
11813 break;
11814 if (qualifying_scope)
11816 if (check_for_bare_parameter_packs (qualifying_scope,
11817 id_declarator->id_loc))
11818 return error_mark_node;
11819 if (at_function_scope_p ())
11821 /* [dcl.meaning]
11823 A declarator-id shall not be qualified except
11824 for ...
11826 None of the cases are permitted in block
11827 scope. */
11828 if (qualifying_scope == global_namespace)
11829 error ("invalid use of qualified-name %<::%D%>",
11830 decl);
11831 else if (TYPE_P (qualifying_scope))
11832 error ("invalid use of qualified-name %<%T::%D%>",
11833 qualifying_scope, decl);
11834 else
11835 error ("invalid use of qualified-name %<%D::%D%>",
11836 qualifying_scope, decl);
11837 return error_mark_node;
11839 else if (TYPE_P (qualifying_scope))
11841 ctype = qualifying_scope;
11842 if (!MAYBE_CLASS_TYPE_P (ctype))
11844 error_at (id_declarator->id_loc,
11845 "%q#T is not a class or namespace", ctype);
11846 ctype = NULL_TREE;
11848 else if (innermost_code != cdk_function
11849 && current_class_type
11850 && !uniquely_derived_from_p (ctype,
11851 current_class_type))
11853 error_at (id_declarator->id_loc,
11854 "invalid use of qualified-name %<%T::%D%>",
11855 qualifying_scope, decl);
11856 return error_mark_node;
11859 else if (TREE_CODE (qualifying_scope) == NAMESPACE_DECL)
11860 in_namespace = qualifying_scope;
11862 switch (TREE_CODE (decl))
11864 case BIT_NOT_EXPR:
11866 if (innermost_code != cdk_function)
11868 error_at (EXPR_LOCATION (decl),
11869 "declaration of %qE as non-function", decl);
11870 return error_mark_node;
11872 else if (!qualifying_scope
11873 && !(current_class_type && at_class_scope_p ()))
11875 error_at (EXPR_LOCATION (decl),
11876 "declaration of %qE as non-member", decl);
11877 return error_mark_node;
11880 tree type = TREE_OPERAND (decl, 0);
11881 if (TYPE_P (type))
11882 type = constructor_name (type);
11883 name = identifier_to_locale (IDENTIFIER_POINTER (type));
11884 dname = decl;
11886 break;
11888 case TEMPLATE_ID_EXPR:
11890 tree fns = TREE_OPERAND (decl, 0);
11892 dname = fns;
11893 if (!identifier_p (dname))
11894 dname = OVL_NAME (dname);
11896 /* Fall through. */
11898 case IDENTIFIER_NODE:
11899 if (identifier_p (decl))
11900 dname = decl;
11902 if (IDENTIFIER_KEYWORD_P (dname))
11904 error ("declarator-id missing; using reserved word %qD",
11905 dname);
11906 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
11908 else if (!IDENTIFIER_CONV_OP_P (dname))
11909 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
11910 else
11912 gcc_assert (flags == NO_SPECIAL);
11913 flags = TYPENAME_FLAG;
11914 sfk = sfk_conversion;
11915 tree glob = get_global_binding (dname);
11916 if (glob && TREE_CODE (glob) == TYPE_DECL)
11917 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
11918 else
11919 name = "<invalid operator>";
11921 break;
11923 default:
11924 gcc_unreachable ();
11926 break;
11929 case cdk_array:
11930 case cdk_pointer:
11931 case cdk_reference:
11932 case cdk_ptrmem:
11933 break;
11935 case cdk_decomp:
11936 name = "structured binding";
11937 break;
11939 case cdk_error:
11940 return error_mark_node;
11942 default:
11943 gcc_unreachable ();
11945 if (id_declarator->kind == cdk_id)
11946 break;
11949 /* [dcl.fct.edf]
11951 The declarator in a function-definition shall have the form
11952 D1 ( parameter-declaration-clause) ... */
11953 if (funcdef_flag && innermost_code != cdk_function)
11955 error_at (id_loc, "function definition does not declare parameters");
11956 return error_mark_node;
11959 if (flags == TYPENAME_FLAG
11960 && innermost_code != cdk_function
11961 && ! (ctype && !declspecs->any_specifiers_p))
11963 error_at (id_loc, "declaration of %qD as non-function", dname);
11964 return error_mark_node;
11967 if (dname && identifier_p (dname))
11969 if (UDLIT_OPER_P (dname)
11970 && innermost_code != cdk_function)
11972 error_at (id_loc, "declaration of %qD as non-function", dname);
11973 return error_mark_node;
11976 if (IDENTIFIER_ANY_OP_P (dname))
11978 if (typedef_p)
11980 error_at (id_loc, "declaration of %qD as %<typedef%>", dname);
11981 return error_mark_node;
11983 else if (decl_context == PARM || decl_context == CATCHPARM)
11985 error_at (id_loc, "declaration of %qD as parameter", dname);
11986 return error_mark_node;
11991 /* Anything declared one level down from the top level
11992 must be one of the parameters of a function
11993 (because the body is at least two levels down). */
11995 /* This heuristic cannot be applied to C++ nodes! Fixed, however,
11996 by not allowing C++ class definitions to specify their parameters
11997 with xdecls (must be spec.d in the parmlist).
11999 Since we now wait to push a class scope until we are sure that
12000 we are in a legitimate method context, we must set oldcname
12001 explicitly (since current_class_name is not yet alive).
12003 We also want to avoid calling this a PARM if it is in a namespace. */
12005 if (decl_context == NORMAL && !toplevel_bindings_p ())
12007 cp_binding_level *b = current_binding_level;
12008 current_binding_level = b->level_chain;
12009 if (current_binding_level != 0 && toplevel_bindings_p ())
12010 decl_context = PARM;
12011 current_binding_level = b;
12014 if (name == NULL)
12015 name = decl_context == PARM ? "parameter" : "type name";
12017 if (consteval_p && constexpr_p)
12019 error_at (declspecs->locations[ds_consteval],
12020 "both %qs and %qs specified", "constexpr", "consteval");
12021 return error_mark_node;
12024 if (concept_p && typedef_p)
12026 error_at (declspecs->locations[ds_concept],
12027 "%qs cannot appear in a typedef declaration", "concept");
12028 return error_mark_node;
12031 if (constexpr_p && typedef_p)
12033 error_at (declspecs->locations[ds_constexpr],
12034 "%qs cannot appear in a typedef declaration", "constexpr");
12035 return error_mark_node;
12038 if (consteval_p && typedef_p)
12040 error_at (declspecs->locations[ds_consteval],
12041 "%qs cannot appear in a typedef declaration", "consteval");
12042 return error_mark_node;
12045 if (constinit_p && typedef_p)
12047 error_at (declspecs->locations[ds_constinit],
12048 "%qs cannot appear in a typedef declaration", "constinit");
12049 return error_mark_node;
12052 /* [dcl.spec]/2 "At most one of the constexpr, consteval, and constinit
12053 keywords shall appear in a decl-specifier-seq." */
12054 if (constinit_p && constexpr_p)
12056 gcc_rich_location richloc (declspecs->locations[ds_constinit]);
12057 richloc.add_range (declspecs->locations[ds_constexpr]);
12058 error_at (&richloc,
12059 "can use at most one of the %<constinit%> and %<constexpr%> "
12060 "specifiers");
12061 return error_mark_node;
12064 /* If there were multiple types specified in the decl-specifier-seq,
12065 issue an error message. */
12066 if (declspecs->multiple_types_p)
12068 error_at (typespec_loc,
12069 "two or more data types in declaration of %qs", name);
12070 return error_mark_node;
12073 if (declspecs->conflicting_specifiers_p)
12075 error_at (min_location (declspecs->locations[ds_typedef],
12076 declspecs->locations[ds_storage_class]),
12077 "conflicting specifiers in declaration of %qs", name);
12078 return error_mark_node;
12081 /* Extract the basic type from the decl-specifier-seq. */
12082 type = declspecs->type;
12083 if (type == error_mark_node)
12085 type = NULL_TREE;
12086 type_was_error_mark_node = true;
12089 /* Ignore erroneous attributes. */
12090 if (attrlist && *attrlist == error_mark_node)
12091 *attrlist = NULL_TREE;
12093 /* An object declared as __attribute__((unavailable)) suppresses
12094 any reports of being declared with unavailable or deprecated
12095 items. An object declared as __attribute__((deprecated))
12096 suppresses warnings of uses of other deprecated items. */
12097 auto ds = make_temp_override (deprecated_state);
12098 if (attrlist && lookup_attribute ("unavailable", *attrlist))
12099 deprecated_state = UNAVAILABLE_DEPRECATED_SUPPRESS;
12100 else if (attrlist && lookup_attribute ("deprecated", *attrlist))
12101 deprecated_state = DEPRECATED_SUPPRESS;
12103 cp_handle_deprecated_or_unavailable (type);
12104 if (type && TREE_CODE (type) == TYPE_DECL)
12106 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (type));
12107 typedef_decl = type;
12108 type = TREE_TYPE (typedef_decl);
12109 if (DECL_ARTIFICIAL (typedef_decl))
12110 cp_handle_deprecated_or_unavailable (type);
12112 /* No type at all: default to `int', and set DEFAULTED_INT
12113 because it was not a user-defined typedef. */
12114 if (type == NULL_TREE)
12116 if (signed_p || unsigned_p || long_p || short_p)
12118 /* These imply 'int'. */
12119 type = integer_type_node;
12120 defaulted_int = 1;
12122 /* If we just have "complex", it is equivalent to "complex double". */
12123 else if (!longlong && !explicit_intN
12124 && decl_spec_seq_has_spec_p (declspecs, ds_complex))
12126 type = double_type_node;
12127 pedwarn (declspecs->locations[ds_complex], OPT_Wpedantic,
12128 "ISO C++ does not support plain %<complex%> meaning "
12129 "%<double complex%>");
12132 /* Gather flags. */
12133 explicit_int = declspecs->explicit_int_p;
12134 explicit_char = declspecs->explicit_char_p;
12136 #if 0
12137 /* See the code below that used this. */
12138 if (typedef_decl)
12139 decl_attr = DECL_ATTRIBUTES (typedef_decl);
12140 #endif
12141 typedef_type = type;
12143 if (sfk == sfk_conversion || sfk == sfk_deduction_guide)
12144 ctor_return_type = TREE_TYPE (dname);
12145 else
12146 ctor_return_type = ctype;
12148 if (sfk != sfk_none)
12150 type = check_special_function_return_type (sfk, type,
12151 ctor_return_type,
12152 type_quals,
12153 declspecs->locations);
12154 type_quals = TYPE_UNQUALIFIED;
12156 else if (type == NULL_TREE)
12158 int is_main;
12160 explicit_int = -1;
12162 /* We handle `main' specially here, because 'main () { }' is so
12163 common. With no options, it is allowed. With -Wreturn-type,
12164 it is a warning. It is only an error with -pedantic-errors. */
12165 is_main = (funcdef_flag
12166 && dname && identifier_p (dname)
12167 && MAIN_NAME_P (dname)
12168 && ctype == NULL_TREE
12169 && in_namespace == NULL_TREE
12170 && current_namespace == global_namespace);
12172 if (type_was_error_mark_node)
12173 /* We've already issued an error, don't complain more. */;
12174 else if (in_system_header_at (id_loc) || flag_ms_extensions)
12175 /* Allow it, sigh. */;
12176 else if (! is_main)
12177 permerror (id_loc, "ISO C++ forbids declaration of %qs with no type",
12178 name);
12179 else if (pedantic)
12180 pedwarn (id_loc, OPT_Wpedantic,
12181 "ISO C++ forbids declaration of %qs with no type", name);
12182 else
12183 warning_at (id_loc, OPT_Wreturn_type,
12184 "ISO C++ forbids declaration of %qs with no type", name);
12186 if (type_was_error_mark_node && template_parm_flag)
12187 /* FIXME we should be able to propagate the error_mark_node as is
12188 for other contexts too. */
12189 type = error_mark_node;
12190 else
12191 type = integer_type_node;
12194 ctype = NULL_TREE;
12196 if (explicit_intN)
12198 if (! int_n_enabled_p[declspecs->int_n_idx])
12200 error_at (declspecs->locations[ds_type_spec],
12201 "%<__int%d%> is not supported by this target",
12202 int_n_data[declspecs->int_n_idx].bitsize);
12203 explicit_intN = false;
12205 /* Don't pedwarn if the alternate "__intN__" form has been used instead
12206 of "__intN". */
12207 else if (!int_n_alt && pedantic)
12208 pedwarn (declspecs->locations[ds_type_spec], OPT_Wpedantic,
12209 "ISO C++ does not support %<__int%d%> for %qs",
12210 int_n_data[declspecs->int_n_idx].bitsize, name);
12213 /* Now process the modifiers that were specified
12214 and check for invalid combinations. */
12216 /* Long double is a special combination. */
12217 if (long_p && !longlong && TYPE_MAIN_VARIANT (type) == double_type_node)
12219 long_p = false;
12220 type = cp_build_qualified_type (long_double_type_node,
12221 cp_type_quals (type));
12224 /* Check all other uses of type modifiers. */
12226 if (unsigned_p || signed_p || long_p || short_p)
12228 location_t loc;
12229 const char *key;
12230 if (unsigned_p)
12232 key = "unsigned";
12233 loc = declspecs->locations[ds_unsigned];
12235 else if (signed_p)
12237 key = "signed";
12238 loc = declspecs->locations[ds_signed];
12240 else if (longlong)
12242 key = "long long";
12243 loc = declspecs->locations[ds_long_long];
12245 else if (long_p)
12247 key = "long";
12248 loc = declspecs->locations[ds_long];
12250 else /* if (short_p) */
12252 key = "short";
12253 loc = declspecs->locations[ds_short];
12256 int ok = 0;
12258 if (signed_p && unsigned_p)
12260 gcc_rich_location richloc (declspecs->locations[ds_signed]);
12261 richloc.add_range (declspecs->locations[ds_unsigned]);
12262 error_at (&richloc,
12263 "%<signed%> and %<unsigned%> specified together");
12265 else if (long_p && short_p)
12267 gcc_rich_location richloc (declspecs->locations[ds_long]);
12268 richloc.add_range (declspecs->locations[ds_short]);
12269 error_at (&richloc, "%<long%> and %<short%> specified together");
12271 else if (TREE_CODE (type) != INTEGER_TYPE
12272 || type == char8_type_node
12273 || type == char16_type_node
12274 || type == char32_type_node
12275 || ((long_p || short_p)
12276 && (explicit_char || explicit_intN)))
12277 error_at (loc, "%qs specified with %qT", key, type);
12278 else if (!explicit_int && !defaulted_int
12279 && !explicit_char && !explicit_intN)
12281 if (typedef_decl)
12283 pedwarn (loc, OPT_Wpedantic, "%qs specified with %qT",
12284 key, type);
12285 ok = !flag_pedantic_errors;
12286 type = DECL_ORIGINAL_TYPE (typedef_decl);
12287 typedef_decl = NULL_TREE;
12289 else if (declspecs->decltype_p)
12290 error_at (loc, "%qs specified with %<decltype%>", key);
12291 else
12292 error_at (loc, "%qs specified with %<typeof%>", key);
12294 else
12295 ok = 1;
12297 /* Discard the type modifiers if they are invalid. */
12298 if (! ok)
12300 unsigned_p = false;
12301 signed_p = false;
12302 long_p = false;
12303 short_p = false;
12304 longlong = 0;
12308 /* Decide whether an integer type is signed or not.
12309 Optionally treat bitfields as signed by default. */
12310 if (unsigned_p
12311 /* [class.bit]
12313 It is implementation-defined whether a plain (neither
12314 explicitly signed or unsigned) char, short, int, or long
12315 bit-field is signed or unsigned.
12317 Naturally, we extend this to long long as well. Note that
12318 this does not include wchar_t. */
12319 || (bitfield && !flag_signed_bitfields
12320 && !signed_p
12321 /* A typedef for plain `int' without `signed' can be
12322 controlled just like plain `int', but a typedef for
12323 `signed int' cannot be so controlled. */
12324 && !(typedef_decl
12325 && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl))
12326 && TREE_CODE (type) == INTEGER_TYPE
12327 && !same_type_p (TYPE_MAIN_VARIANT (type), wchar_type_node)))
12329 if (explicit_intN)
12330 type = int_n_trees[declspecs->int_n_idx].unsigned_type;
12331 else if (longlong)
12332 type = long_long_unsigned_type_node;
12333 else if (long_p)
12334 type = long_unsigned_type_node;
12335 else if (short_p)
12336 type = short_unsigned_type_node;
12337 else if (type == char_type_node)
12338 type = unsigned_char_type_node;
12339 else if (typedef_decl)
12340 type = unsigned_type_for (type);
12341 else
12342 type = unsigned_type_node;
12344 else if (signed_p && type == char_type_node)
12345 type = signed_char_type_node;
12346 else if (explicit_intN)
12347 type = int_n_trees[declspecs->int_n_idx].signed_type;
12348 else if (longlong)
12349 type = long_long_integer_type_node;
12350 else if (long_p)
12351 type = long_integer_type_node;
12352 else if (short_p)
12353 type = short_integer_type_node;
12355 if (decl_spec_seq_has_spec_p (declspecs, ds_complex))
12357 if (TREE_CODE (type) != INTEGER_TYPE && TREE_CODE (type) != REAL_TYPE)
12358 error_at (declspecs->locations[ds_complex],
12359 "complex invalid for %qs", name);
12360 /* If a modifier is specified, the resulting complex is the complex
12361 form of TYPE. E.g, "complex short" is "complex short int". */
12362 else if (type == integer_type_node)
12363 type = complex_integer_type_node;
12364 else if (type == float_type_node)
12365 type = complex_float_type_node;
12366 else if (type == double_type_node)
12367 type = complex_double_type_node;
12368 else if (type == long_double_type_node)
12369 type = complex_long_double_type_node;
12370 else
12371 type = build_complex_type (type);
12374 /* If we're using the injected-class-name to form a compound type or a
12375 declaration, replace it with the underlying class so we don't get
12376 redundant typedefs in the debug output. But if we are returning the
12377 type unchanged, leave it alone so that it's available to
12378 maybe_get_template_decl_from_type_decl. */
12379 if (CLASS_TYPE_P (type)
12380 && DECL_SELF_REFERENCE_P (TYPE_NAME (type))
12381 && type == TREE_TYPE (TYPE_NAME (type))
12382 && (declarator || type_quals))
12383 type = DECL_ORIGINAL_TYPE (TYPE_NAME (type));
12385 type_quals |= cp_type_quals (type);
12386 type = cp_build_qualified_type
12387 (type, type_quals, ((((typedef_decl && !DECL_ARTIFICIAL (typedef_decl))
12388 || declspecs->decltype_p)
12389 ? tf_ignore_bad_quals : 0) | tf_warning_or_error));
12390 /* We might have ignored or rejected some of the qualifiers. */
12391 type_quals = cp_type_quals (type);
12393 if (cxx_dialect >= cxx17 && type && is_auto (type)
12394 && innermost_code != cdk_function
12395 && id_declarator && declarator != id_declarator)
12396 if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (type))
12398 error_at (typespec_loc, "template placeholder type %qT must be followed "
12399 "by a simple declarator-id", type);
12400 inform (DECL_SOURCE_LOCATION (tmpl), "%qD declared here", tmpl);
12401 type = error_mark_node;
12404 staticp = 0;
12405 inlinep = decl_spec_seq_has_spec_p (declspecs, ds_inline);
12406 virtualp = decl_spec_seq_has_spec_p (declspecs, ds_virtual);
12407 explicitp = decl_spec_seq_has_spec_p (declspecs, ds_explicit);
12409 storage_class = declspecs->storage_class;
12410 if (storage_class == sc_static)
12411 staticp = 1 + (decl_context == FIELD);
12412 else if (decl_context == FIELD && sfk == sfk_deduction_guide)
12413 /* Treat class-scope deduction guides as static member functions
12414 so that they get a FUNCTION_TYPE instead of a METHOD_TYPE. */
12415 staticp = 2;
12417 if (virtualp)
12419 if (staticp == 2)
12421 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
12422 richloc.add_range (declspecs->locations[ds_storage_class]);
12423 error_at (&richloc, "member %qD cannot be declared both %<virtual%> "
12424 "and %<static%>", dname);
12425 storage_class = sc_none;
12426 staticp = 0;
12428 if (constexpr_p && pedantic && cxx_dialect < cxx20)
12430 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
12431 richloc.add_range (declspecs->locations[ds_constexpr]);
12432 pedwarn (&richloc, OPT_Wc__20_extensions, "member %qD can be "
12433 "declared both %<virtual%> and %<constexpr%> only in "
12434 "%<-std=c++20%> or %<-std=gnu++20%>", dname);
12437 friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
12439 /* Issue errors about use of storage classes for parameters. */
12440 if (decl_context == PARM)
12442 if (typedef_p)
12444 error_at (declspecs->locations[ds_typedef],
12445 "typedef declaration invalid in parameter declaration");
12446 return error_mark_node;
12448 else if (template_parm_flag && storage_class != sc_none)
12450 error_at (min_location (declspecs->locations[ds_thread],
12451 declspecs->locations[ds_storage_class]),
12452 "storage class specified for template parameter %qs",
12453 name);
12454 return error_mark_node;
12456 else if (storage_class == sc_static
12457 || storage_class == sc_extern
12458 || thread_p)
12460 error_at (min_location (declspecs->locations[ds_thread],
12461 declspecs->locations[ds_storage_class]),
12462 "storage class specified for parameter %qs", name);
12463 return error_mark_node;
12466 /* Function parameters cannot be concept. */
12467 if (concept_p)
12469 error_at (declspecs->locations[ds_concept],
12470 "a parameter cannot be declared %qs", "concept");
12471 concept_p = 0;
12472 constexpr_p = 0;
12474 /* Function parameters cannot be constexpr. If we saw one, moan
12475 and pretend it wasn't there. */
12476 else if (constexpr_p)
12478 error_at (declspecs->locations[ds_constexpr],
12479 "a parameter cannot be declared %qs", "constexpr");
12480 constexpr_p = 0;
12482 if (constinit_p)
12484 error_at (declspecs->locations[ds_constinit],
12485 "a parameter cannot be declared %qs", "constinit");
12486 constinit_p = 0;
12488 if (consteval_p)
12490 error_at (declspecs->locations[ds_consteval],
12491 "a parameter cannot be declared %qs", "consteval");
12492 consteval_p = 0;
12496 /* Give error if `virtual' is used outside of class declaration. */
12497 if (virtualp
12498 && (current_class_name == NULL_TREE || decl_context != FIELD))
12500 error_at (declspecs->locations[ds_virtual],
12501 "%<virtual%> outside class declaration");
12502 virtualp = 0;
12505 if (innermost_code == cdk_decomp)
12507 location_t loc = (declarator->kind == cdk_reference
12508 ? declarator->declarator->id_loc : declarator->id_loc);
12509 if (inlinep)
12510 error_at (declspecs->locations[ds_inline],
12511 "structured binding declaration cannot be %qs", "inline");
12512 if (typedef_p)
12513 error_at (declspecs->locations[ds_typedef],
12514 "structured binding declaration cannot be %qs", "typedef");
12515 if (constexpr_p && !concept_p)
12516 error_at (declspecs->locations[ds_constexpr], "structured "
12517 "binding declaration cannot be %qs", "constexpr");
12518 if (consteval_p)
12519 error_at (declspecs->locations[ds_consteval], "structured "
12520 "binding declaration cannot be %qs", "consteval");
12521 if (thread_p && cxx_dialect < cxx20)
12522 pedwarn (declspecs->locations[ds_thread], OPT_Wc__20_extensions,
12523 "structured binding declaration can be %qs only in "
12524 "%<-std=c++20%> or %<-std=gnu++20%>",
12525 declspecs->gnu_thread_keyword_p
12526 ? "__thread" : "thread_local");
12527 if (concept_p)
12528 error_at (declspecs->locations[ds_concept],
12529 "structured binding declaration cannot be %qs", "concept");
12530 /* [dcl.struct.bind] "A cv that includes volatile is deprecated." */
12531 if (type_quals & TYPE_QUAL_VOLATILE)
12532 warning_at (declspecs->locations[ds_volatile], OPT_Wvolatile,
12533 "%<volatile%>-qualified structured binding is deprecated");
12534 switch (storage_class)
12536 case sc_none:
12537 break;
12538 case sc_register:
12539 error_at (loc, "structured binding declaration cannot be %qs",
12540 "register");
12541 break;
12542 case sc_static:
12543 if (cxx_dialect < cxx20)
12544 pedwarn (loc, OPT_Wc__20_extensions,
12545 "structured binding declaration can be %qs only in "
12546 "%<-std=c++20%> or %<-std=gnu++20%>", "static");
12547 break;
12548 case sc_extern:
12549 error_at (loc, "structured binding declaration cannot be %qs",
12550 "extern");
12551 break;
12552 case sc_mutable:
12553 error_at (loc, "structured binding declaration cannot be %qs",
12554 "mutable");
12555 break;
12556 case sc_auto:
12557 error_at (loc, "structured binding declaration cannot be "
12558 "C++98 %<auto%>");
12559 break;
12560 default:
12561 gcc_unreachable ();
12563 if (TREE_CODE (type) != TEMPLATE_TYPE_PARM
12564 || TYPE_IDENTIFIER (type) != auto_identifier)
12566 if (type != error_mark_node)
12568 error_at (loc, "structured binding declaration cannot have "
12569 "type %qT", type);
12570 inform (loc,
12571 "type must be cv-qualified %<auto%> or reference to "
12572 "cv-qualified %<auto%>");
12574 type = build_qualified_type (make_auto (), type_quals);
12575 declspecs->type = type;
12577 inlinep = 0;
12578 typedef_p = 0;
12579 constexpr_p = 0;
12580 consteval_p = 0;
12581 concept_p = 0;
12582 if (storage_class != sc_static)
12584 storage_class = sc_none;
12585 declspecs->storage_class = sc_none;
12589 /* Static anonymous unions are dealt with here. */
12590 if (staticp && decl_context == TYPENAME
12591 && declspecs->type
12592 && ANON_AGGR_TYPE_P (declspecs->type))
12593 decl_context = FIELD;
12595 /* Warn about storage classes that are invalid for certain
12596 kinds of declarations (parameters, typenames, etc.). */
12597 if (thread_p
12598 && ((storage_class
12599 && storage_class != sc_extern
12600 && storage_class != sc_static)
12601 || typedef_p))
12603 location_t loc
12604 = min_location (declspecs->locations[ds_thread],
12605 declspecs->locations[ds_storage_class]);
12606 error_at (loc, "multiple storage classes in declaration of %qs", name);
12607 thread_p = false;
12609 if (decl_context != NORMAL
12610 && ((storage_class != sc_none
12611 && storage_class != sc_mutable)
12612 || thread_p))
12614 if ((decl_context == PARM || decl_context == CATCHPARM)
12615 && (storage_class == sc_register
12616 || storage_class == sc_auto))
12618 else if (typedef_p)
12620 else if (decl_context == FIELD
12621 /* C++ allows static class elements. */
12622 && storage_class == sc_static)
12623 /* C++ also allows inlines and signed and unsigned elements,
12624 but in those cases we don't come in here. */
12626 else
12628 location_t loc
12629 = min_location (declspecs->locations[ds_thread],
12630 declspecs->locations[ds_storage_class]);
12631 if (decl_context == FIELD)
12632 error_at (loc, "storage class specified for %qs", name);
12633 else if (decl_context == PARM || decl_context == CATCHPARM)
12634 error_at (loc, "storage class specified for parameter %qs", name);
12635 else
12636 error_at (loc, "storage class specified for typename");
12637 if (storage_class == sc_register
12638 || storage_class == sc_auto
12639 || storage_class == sc_extern
12640 || thread_p)
12641 storage_class = sc_none;
12644 else if (storage_class == sc_extern && funcdef_flag
12645 && ! toplevel_bindings_p ())
12646 error ("nested function %qs declared %<extern%>", name);
12647 else if (toplevel_bindings_p ())
12649 if (storage_class == sc_auto)
12650 error_at (declspecs->locations[ds_storage_class],
12651 "top-level declaration of %qs specifies %<auto%>", name);
12653 else if (thread_p
12654 && storage_class != sc_extern
12655 && storage_class != sc_static)
12657 if (declspecs->gnu_thread_keyword_p)
12658 pedwarn (declspecs->locations[ds_thread],
12659 0, "function-scope %qs implicitly auto and "
12660 "declared %<__thread%>", name);
12662 /* When thread_local is applied to a variable of block scope the
12663 storage-class-specifier static is implied if it does not appear
12664 explicitly. */
12665 storage_class = declspecs->storage_class = sc_static;
12666 staticp = 1;
12669 if (storage_class && friendp)
12671 error_at (min_location (declspecs->locations[ds_thread],
12672 declspecs->locations[ds_storage_class]),
12673 "storage class specifiers invalid in friend function "
12674 "declarations");
12675 storage_class = sc_none;
12676 staticp = 0;
12679 if (!id_declarator)
12680 unqualified_id = NULL_TREE;
12681 else
12683 unqualified_id = id_declarator->u.id.unqualified_name;
12684 switch (TREE_CODE (unqualified_id))
12686 case BIT_NOT_EXPR:
12687 unqualified_id = TREE_OPERAND (unqualified_id, 0);
12688 if (TYPE_P (unqualified_id))
12689 unqualified_id = constructor_name (unqualified_id);
12690 break;
12692 case IDENTIFIER_NODE:
12693 case TEMPLATE_ID_EXPR:
12694 break;
12696 default:
12697 gcc_unreachable ();
12701 if (declspecs->std_attributes)
12703 location_t attr_loc = declspecs->locations[ds_std_attribute];
12704 if (warning_at (attr_loc, OPT_Wattributes, "attribute ignored"))
12705 inform (attr_loc, "an attribute that appertains to a type-specifier "
12706 "is ignored");
12709 /* Determine the type of the entity declared by recurring on the
12710 declarator. */
12711 for (; declarator; declarator = declarator->declarator)
12713 const cp_declarator *inner_declarator;
12714 tree attrs;
12716 if (type == error_mark_node)
12717 return error_mark_node;
12719 attrs = declarator->attributes;
12720 if (attrs)
12722 int attr_flags;
12724 attr_flags = 0;
12725 if (declarator->kind == cdk_id)
12726 attr_flags |= (int) ATTR_FLAG_DECL_NEXT;
12727 if (declarator->kind == cdk_function)
12728 attr_flags |= (int) ATTR_FLAG_FUNCTION_NEXT;
12729 if (declarator->kind == cdk_array)
12730 attr_flags |= (int) ATTR_FLAG_ARRAY_NEXT;
12731 tree late_attrs = NULL_TREE;
12732 if (decl_context != PARM && decl_context != TYPENAME)
12733 /* Assume that any attributes that get applied late to
12734 templates will DTRT when applied to the declaration
12735 as a whole. */
12736 late_attrs = splice_template_attributes (&attrs, type);
12737 returned_attrs = decl_attributes (&type,
12738 attr_chainon (returned_attrs,
12739 attrs),
12740 attr_flags);
12741 returned_attrs = attr_chainon (late_attrs, returned_attrs);
12744 inner_declarator = declarator->declarator;
12746 /* We don't want to warn in parameter context because we don't
12747 yet know if the parse will succeed, and this might turn out
12748 to be a constructor call. */
12749 if (decl_context != PARM
12750 && decl_context != TYPENAME
12751 && !typedef_p
12752 && declarator->parenthesized != UNKNOWN_LOCATION
12753 /* If the type is class-like and the inner name used a
12754 global namespace qualifier, we need the parens.
12755 Unfortunately all we can tell is whether a qualified name
12756 was used or not. */
12757 && !(inner_declarator
12758 && inner_declarator->kind == cdk_id
12759 && inner_declarator->u.id.qualifying_scope
12760 && (MAYBE_CLASS_TYPE_P (type)
12761 || TREE_CODE (type) == ENUMERAL_TYPE)))
12763 if (warning_at (declarator->parenthesized, OPT_Wparentheses,
12764 "unnecessary parentheses in declaration of %qs",
12765 name))
12767 gcc_rich_location iloc (declarator->parenthesized);
12768 iloc.add_fixit_remove (get_start (declarator->parenthesized));
12769 iloc.add_fixit_remove (get_finish (declarator->parenthesized));
12770 inform (&iloc, "remove parentheses");
12773 if (declarator->kind == cdk_id || declarator->kind == cdk_decomp)
12774 break;
12776 switch (declarator->kind)
12778 case cdk_array:
12779 type = create_array_type_for_decl (dname, type,
12780 declarator->u.array.bounds,
12781 declarator->id_loc);
12782 if (!valid_array_size_p (dname
12783 ? declarator->id_loc : input_location,
12784 type, dname))
12785 type = error_mark_node;
12787 if (declarator->std_attributes)
12788 /* [dcl.array]/1:
12790 The optional attribute-specifier-seq appertains to the
12791 array. */
12792 returned_attrs = attr_chainon (returned_attrs,
12793 declarator->std_attributes);
12794 break;
12796 case cdk_function:
12798 tree arg_types;
12799 int funcdecl_p;
12801 /* Declaring a function type. */
12803 /* Pick up type qualifiers which should be applied to `this'. */
12804 memfn_quals = declarator->u.function.qualifiers;
12805 /* Pick up virt-specifiers. */
12806 virt_specifiers = declarator->u.function.virt_specifiers;
12807 /* And ref-qualifier, too */
12808 rqual = declarator->u.function.ref_qualifier;
12809 /* And tx-qualifier. */
12810 tree tx_qual = declarator->u.function.tx_qualifier;
12811 /* Pick up the exception specifications. */
12812 raises = declarator->u.function.exception_specification;
12813 /* If the exception-specification is ill-formed, let's pretend
12814 there wasn't one. */
12815 if (raises == error_mark_node)
12816 raises = NULL_TREE;
12818 if (reqs)
12819 error_at (location_of (reqs), "requires-clause on return type");
12820 reqs = declarator->u.function.requires_clause;
12822 /* Say it's a definition only for the CALL_EXPR
12823 closest to the identifier. */
12824 funcdecl_p = inner_declarator && inner_declarator->kind == cdk_id;
12826 /* Handle a late-specified return type. */
12827 tree late_return_type = declarator->u.function.late_return_type;
12828 if (tree auto_node = type_uses_auto (type))
12830 if (!late_return_type)
12832 if (!funcdecl_p)
12833 /* auto (*fp)() = f; is OK. */;
12834 else if (current_class_type
12835 && LAMBDA_TYPE_P (current_class_type))
12836 /* OK for C++11 lambdas. */;
12837 else if (cxx_dialect < cxx14)
12839 error_at (typespec_loc, "%qs function uses "
12840 "%<auto%> type specifier without "
12841 "trailing return type", name);
12842 inform (typespec_loc,
12843 "deduced return type only available "
12844 "with %<-std=c++14%> or %<-std=gnu++14%>");
12846 else if (virtualp)
12848 error_at (typespec_loc, "virtual function "
12849 "cannot have deduced return type");
12850 virtualp = false;
12853 else if (!is_auto (type) && sfk != sfk_conversion)
12855 error_at (typespec_loc, "%qs function with trailing "
12856 "return type has %qT as its type rather "
12857 "than plain %<auto%>", name, type);
12858 return error_mark_node;
12860 else if (is_auto (type) && AUTO_IS_DECLTYPE (type))
12862 if (funcdecl_p)
12863 error_at (typespec_loc,
12864 "%qs function with trailing return type "
12865 "has %<decltype(auto)%> as its type "
12866 "rather than plain %<auto%>", name);
12867 else
12868 error_at (typespec_loc,
12869 "invalid use of %<decltype(auto)%>");
12870 return error_mark_node;
12872 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node);
12873 if (!tmpl)
12874 if (tree late_auto = type_uses_auto (late_return_type))
12875 tmpl = CLASS_PLACEHOLDER_TEMPLATE (late_auto);
12876 if (tmpl)
12878 if (!funcdecl_p || !dguide_name_p (unqualified_id))
12880 error_at (typespec_loc, "deduced class "
12881 "type %qD in function return type",
12882 DECL_NAME (tmpl));
12883 inform (DECL_SOURCE_LOCATION (tmpl),
12884 "%qD declared here", tmpl);
12885 return error_mark_node;
12887 else if (!late_return_type)
12889 error_at (declarator->id_loc, "deduction guide "
12890 "for %qT must have trailing return "
12891 "type", TREE_TYPE (tmpl));
12892 inform (DECL_SOURCE_LOCATION (tmpl),
12893 "%qD declared here", tmpl);
12894 return error_mark_node;
12896 else if (CLASS_TYPE_P (late_return_type)
12897 && CLASSTYPE_TEMPLATE_INFO (late_return_type)
12898 && (CLASSTYPE_TI_TEMPLATE (late_return_type)
12899 == tmpl))
12900 /* OK */;
12901 else
12902 error ("trailing return type %qT of deduction guide "
12903 "is not a specialization of %qT",
12904 late_return_type, TREE_TYPE (tmpl));
12907 else if (late_return_type
12908 && sfk != sfk_conversion)
12910 if (late_return_type == error_mark_node)
12911 return error_mark_node;
12912 if (cxx_dialect < cxx11)
12913 /* Not using maybe_warn_cpp0x because this should
12914 always be an error. */
12915 error_at (typespec_loc,
12916 "trailing return type only available "
12917 "with %<-std=c++11%> or %<-std=gnu++11%>");
12918 else
12919 error_at (typespec_loc, "%qs function with trailing "
12920 "return type not declared with %<auto%> "
12921 "type specifier", name);
12922 return error_mark_node;
12924 if (late_return_type && sfk == sfk_conversion)
12926 error ("a conversion function cannot have a trailing return type");
12927 return error_mark_node;
12929 type = splice_late_return_type (type, late_return_type);
12930 if (type == error_mark_node)
12931 return error_mark_node;
12933 if (late_return_type)
12935 late_return_type_p = true;
12936 type_quals = cp_type_quals (type);
12939 if (type_quals != TYPE_UNQUALIFIED)
12941 if (SCALAR_TYPE_P (type) || VOID_TYPE_P (type))
12942 warning_at (typespec_loc, OPT_Wignored_qualifiers, "type "
12943 "qualifiers ignored on function return type");
12944 /* [dcl.fct] "A volatile-qualified return type is
12945 deprecated." */
12946 if (type_quals & TYPE_QUAL_VOLATILE)
12947 warning_at (typespec_loc, OPT_Wvolatile,
12948 "%<volatile%>-qualified return type is "
12949 "deprecated");
12951 /* We now know that the TYPE_QUALS don't apply to the
12952 decl, but to its return type. */
12953 type_quals = TYPE_UNQUALIFIED;
12956 /* Error about some types functions can't return. */
12958 if (TREE_CODE (type) == FUNCTION_TYPE)
12960 error_at (typespec_loc, "%qs declared as function returning "
12961 "a function", name);
12962 return error_mark_node;
12964 if (TREE_CODE (type) == ARRAY_TYPE)
12966 error_at (typespec_loc, "%qs declared as function returning "
12967 "an array", name);
12968 return error_mark_node;
12970 if (constinit_p)
12972 error_at (declspecs->locations[ds_constinit],
12973 "%<constinit%> on function return type is not "
12974 "allowed");
12975 return error_mark_node;
12978 if (check_decltype_auto (typespec_loc, type))
12979 return error_mark_node;
12981 if (ctype == NULL_TREE
12982 && decl_context == FIELD
12983 && funcdecl_p
12984 && friendp == 0)
12985 ctype = current_class_type;
12987 if (ctype && (sfk == sfk_constructor
12988 || sfk == sfk_destructor))
12990 /* We are within a class's scope. If our declarator name
12991 is the same as the class name, and we are defining
12992 a function, then it is a constructor/destructor, and
12993 therefore returns a void type. */
12995 /* ISO C++ 12.4/2. A destructor may not be declared
12996 const or volatile. A destructor may not be static.
12997 A destructor may not be declared with ref-qualifier.
12999 ISO C++ 12.1. A constructor may not be declared
13000 const or volatile. A constructor may not be
13001 virtual. A constructor may not be static.
13002 A constructor may not be declared with ref-qualifier. */
13003 if (staticp == 2)
13004 error_at (declspecs->locations[ds_storage_class],
13005 (flags == DTOR_FLAG)
13006 ? G_("destructor cannot be static member "
13007 "function")
13008 : G_("constructor cannot be static member "
13009 "function"));
13010 if (memfn_quals)
13012 error ((flags == DTOR_FLAG)
13013 ? G_("destructors may not be cv-qualified")
13014 : G_("constructors may not be cv-qualified"));
13015 memfn_quals = TYPE_UNQUALIFIED;
13018 if (rqual)
13020 maybe_warn_cpp0x (CPP0X_REF_QUALIFIER);
13021 error ((flags == DTOR_FLAG)
13022 ? G_("destructors may not be ref-qualified")
13023 : G_("constructors may not be ref-qualified"));
13024 rqual = REF_QUAL_NONE;
13027 if (decl_context == FIELD
13028 && !member_function_or_else (ctype,
13029 current_class_type,
13030 flags))
13031 return error_mark_node;
13033 if (flags != DTOR_FLAG)
13035 /* It's a constructor. */
13036 if (explicitp == 1)
13037 explicitp = 2;
13038 if (virtualp)
13040 permerror (declspecs->locations[ds_virtual],
13041 "constructors cannot be declared %<virtual%>");
13042 virtualp = 0;
13044 if (decl_context == FIELD
13045 && sfk != sfk_constructor)
13046 return error_mark_node;
13048 if (decl_context == FIELD)
13049 staticp = 0;
13051 else if (friendp)
13053 if (virtualp)
13055 /* Cannot be both friend and virtual. */
13056 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
13057 richloc.add_range (declspecs->locations[ds_friend]);
13058 error_at (&richloc, "virtual functions cannot be friends");
13059 friendp = 0;
13061 if (decl_context == NORMAL)
13062 error_at (declarator->id_loc,
13063 "friend declaration not in class definition");
13064 if (current_function_decl && funcdef_flag)
13066 error_at (declarator->id_loc,
13067 "cannot define friend function %qs in a local "
13068 "class definition", name);
13069 friendp = 0;
13071 /* [class.friend]/6: A function can be defined in a friend
13072 declaration if the function name is unqualified. */
13073 if (funcdef_flag && in_namespace)
13075 if (in_namespace == global_namespace)
13076 error_at (declarator->id_loc,
13077 "friend function definition %qs cannot have "
13078 "a name qualified with %<::%>", name);
13079 else
13080 error_at (declarator->id_loc,
13081 "friend function definition %qs cannot have "
13082 "a name qualified with %<%D::%>", name,
13083 in_namespace);
13086 else if (ctype && sfk == sfk_conversion)
13088 if (explicitp == 1)
13090 maybe_warn_cpp0x (CPP0X_EXPLICIT_CONVERSION);
13091 explicitp = 2;
13094 else if (sfk == sfk_deduction_guide)
13096 if (explicitp == 1)
13097 explicitp = 2;
13100 tree pushed_scope = NULL_TREE;
13101 if (funcdecl_p
13102 && decl_context != FIELD
13103 && inner_declarator->u.id.qualifying_scope
13104 && CLASS_TYPE_P (inner_declarator->u.id.qualifying_scope))
13105 pushed_scope
13106 = push_scope (inner_declarator->u.id.qualifying_scope);
13108 arg_types = grokparms (declarator->u.function.parameters, &parms);
13110 if (pushed_scope)
13111 pop_scope (pushed_scope);
13113 if (inner_declarator
13114 && inner_declarator->kind == cdk_id
13115 && inner_declarator->u.id.sfk == sfk_destructor
13116 && arg_types != void_list_node)
13118 error_at (declarator->id_loc,
13119 "destructors may not have parameters");
13120 arg_types = void_list_node;
13121 parms = NULL_TREE;
13124 type = build_function_type (type, arg_types);
13126 tree attrs = declarator->std_attributes;
13127 if (tx_qual)
13129 tree att = build_tree_list (tx_qual, NULL_TREE);
13130 /* transaction_safe applies to the type, but
13131 transaction_safe_dynamic applies to the function. */
13132 if (is_attribute_p ("transaction_safe", tx_qual))
13133 attrs = attr_chainon (attrs, att);
13134 else
13135 returned_attrs = attr_chainon (returned_attrs, att);
13137 if (attrs)
13138 /* [dcl.fct]/2:
13140 The optional attribute-specifier-seq appertains to
13141 the function type. */
13142 cplus_decl_attributes (&type, attrs, 0);
13144 if (raises)
13145 type = build_exception_variant (type, raises);
13147 break;
13149 case cdk_pointer:
13150 case cdk_reference:
13151 case cdk_ptrmem:
13152 /* Filter out pointers-to-references and references-to-references.
13153 We can get these if a TYPE_DECL is used. */
13155 if (TYPE_REF_P (type))
13157 if (declarator->kind != cdk_reference)
13159 error ("cannot declare pointer to %q#T", type);
13160 type = TREE_TYPE (type);
13163 /* In C++0x, we allow reference to reference declarations
13164 that occur indirectly through typedefs [7.1.3/8 dcl.typedef]
13165 and template type arguments [14.3.1/4 temp.arg.type]. The
13166 check for direct reference to reference declarations, which
13167 are still forbidden, occurs below. Reasoning behind the change
13168 can be found in DR106, DR540, and the rvalue reference
13169 proposals. */
13170 else if (cxx_dialect == cxx98)
13172 error ("cannot declare reference to %q#T", type);
13173 type = TREE_TYPE (type);
13176 else if (VOID_TYPE_P (type))
13178 if (declarator->kind == cdk_reference)
13179 error ("cannot declare reference to %q#T", type);
13180 else if (declarator->kind == cdk_ptrmem)
13181 error ("cannot declare pointer to %q#T member", type);
13184 /* We now know that the TYPE_QUALS don't apply to the decl,
13185 but to the target of the pointer. */
13186 type_quals = TYPE_UNQUALIFIED;
13188 /* This code used to handle METHOD_TYPE, but I don't think it's
13189 possible to get it here anymore. */
13190 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
13191 if (declarator->kind == cdk_ptrmem
13192 && TREE_CODE (type) == FUNCTION_TYPE)
13194 memfn_quals |= type_memfn_quals (type);
13195 type = build_memfn_type (type,
13196 declarator->u.pointer.class_type,
13197 memfn_quals,
13198 rqual);
13199 if (type == error_mark_node)
13200 return error_mark_node;
13202 rqual = REF_QUAL_NONE;
13203 memfn_quals = TYPE_UNQUALIFIED;
13206 if (TREE_CODE (type) == FUNCTION_TYPE
13207 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
13208 || type_memfn_rqual (type) != REF_QUAL_NONE))
13209 error (declarator->kind == cdk_reference
13210 ? G_("cannot declare reference to qualified function type %qT")
13211 : G_("cannot declare pointer to qualified function type %qT"),
13212 type);
13214 /* When the pointed-to type involves components of variable size,
13215 care must be taken to ensure that the size evaluation code is
13216 emitted early enough to dominate all the possible later uses
13217 and late enough for the variables on which it depends to have
13218 been assigned.
13220 This is expected to happen automatically when the pointed-to
13221 type has a name/declaration of it's own, but special attention
13222 is required if the type is anonymous.
13224 We handle the NORMAL and FIELD contexts here by inserting a
13225 dummy statement that just evaluates the size at a safe point
13226 and ensures it is not deferred until e.g. within a deeper
13227 conditional context (c++/43555).
13229 We expect nothing to be needed here for PARM or TYPENAME.
13230 Evaluating the size at this point for TYPENAME would
13231 actually be incorrect, as we might be in the middle of an
13232 expression with side effects on the pointed-to type size
13233 "arguments" prior to the pointer declaration point and the
13234 size evaluation could end up prior to the side effects. */
13236 if (!TYPE_NAME (type)
13237 && (decl_context == NORMAL || decl_context == FIELD)
13238 && at_function_scope_p ()
13239 && variably_modified_type_p (type, NULL_TREE))
13241 TYPE_NAME (type) = build_decl (UNKNOWN_LOCATION, TYPE_DECL,
13242 NULL_TREE, type);
13243 add_decl_expr (TYPE_NAME (type));
13246 if (declarator->kind == cdk_reference)
13248 /* In C++0x, the type we are creating a reference to might be
13249 a typedef which is itself a reference type. In that case,
13250 we follow the reference collapsing rules in
13251 [7.1.3/8 dcl.typedef] to create the final reference type:
13253 "If a typedef TD names a type that is a reference to a type
13254 T, an attempt to create the type 'lvalue reference to cv TD'
13255 creates the type 'lvalue reference to T,' while an attempt
13256 to create the type "rvalue reference to cv TD' creates the
13257 type TD."
13259 if (VOID_TYPE_P (type))
13260 /* We already gave an error. */;
13261 else if (TYPE_REF_P (type))
13263 if (declarator->u.reference.rvalue_ref)
13264 /* Leave type alone. */;
13265 else
13266 type = cp_build_reference_type (TREE_TYPE (type), false);
13268 else
13269 type = cp_build_reference_type
13270 (type, declarator->u.reference.rvalue_ref);
13272 /* In C++0x, we need this check for direct reference to
13273 reference declarations, which are forbidden by
13274 [8.3.2/5 dcl.ref]. Reference to reference declarations
13275 are only allowed indirectly through typedefs and template
13276 type arguments. Example:
13278 void foo(int & &); // invalid ref-to-ref decl
13280 typedef int & int_ref;
13281 void foo(int_ref &); // valid ref-to-ref decl
13283 if (inner_declarator && inner_declarator->kind == cdk_reference)
13284 error ("cannot declare reference to %q#T, which is not "
13285 "a typedef or a template type argument", type);
13287 else if (TREE_CODE (type) == METHOD_TYPE)
13288 type = build_ptrmemfunc_type (build_pointer_type (type));
13289 else if (declarator->kind == cdk_ptrmem)
13291 gcc_assert (TREE_CODE (declarator->u.pointer.class_type)
13292 != NAMESPACE_DECL);
13293 if (declarator->u.pointer.class_type == error_mark_node)
13294 /* We will already have complained. */
13295 type = error_mark_node;
13296 else
13297 type = build_ptrmem_type (declarator->u.pointer.class_type,
13298 type);
13300 else
13301 type = build_pointer_type (type);
13303 /* Process a list of type modifier keywords (such as
13304 const or volatile) that were given inside the `*' or `&'. */
13306 if (declarator->u.pointer.qualifiers)
13308 type
13309 = cp_build_qualified_type (type,
13310 declarator->u.pointer.qualifiers);
13311 type_quals = cp_type_quals (type);
13314 /* Apply C++11 attributes to the pointer, and not to the
13315 type pointed to. This is unlike what is done for GNU
13316 attributes above. It is to comply with [dcl.ptr]/1:
13318 [the optional attribute-specifier-seq (7.6.1) appertains
13319 to the pointer and not to the object pointed to]. */
13320 if (declarator->std_attributes)
13321 decl_attributes (&type, declarator->std_attributes,
13324 ctype = NULL_TREE;
13325 break;
13327 case cdk_error:
13328 break;
13330 default:
13331 gcc_unreachable ();
13335 id_loc = declarator ? declarator->id_loc : input_location;
13337 if (innermost_code != cdk_function
13338 /* Don't check this if it can be the artifical decltype(auto)
13339 we created when building a constraint in a compound-requirement:
13340 that the type-constraint is plain is going to be checked in
13341 cp_parser_compound_requirement. */
13342 && decl_context != TYPENAME
13343 && check_decltype_auto (id_loc, type))
13344 return error_mark_node;
13346 /* A `constexpr' specifier used in an object declaration declares
13347 the object as `const'. */
13348 if (constexpr_p && innermost_code != cdk_function)
13350 /* DR1688 says that a `constexpr' specifier in combination with
13351 `volatile' is valid. */
13353 if (!TYPE_REF_P (type))
13355 type_quals |= TYPE_QUAL_CONST;
13356 type = cp_build_qualified_type (type, type_quals);
13360 if (unqualified_id && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR
13361 && !FUNC_OR_METHOD_TYPE_P (type)
13362 && !variable_template_p (TREE_OPERAND (unqualified_id, 0)))
13364 error ("template-id %qD used as a declarator",
13365 unqualified_id);
13366 unqualified_id = dname;
13369 /* If TYPE is a FUNCTION_TYPE, but the function name was explicitly
13370 qualified with a class-name, turn it into a METHOD_TYPE, unless
13371 we know that the function is static. We take advantage of this
13372 opportunity to do other processing that pertains to entities
13373 explicitly declared to be class members. Note that if DECLARATOR
13374 is non-NULL, we know it is a cdk_id declarator; otherwise, we
13375 would not have exited the loop above. */
13376 if (declarator
13377 && declarator->kind == cdk_id
13378 && declarator->u.id.qualifying_scope
13379 && MAYBE_CLASS_TYPE_P (declarator->u.id.qualifying_scope))
13381 ctype = declarator->u.id.qualifying_scope;
13382 ctype = TYPE_MAIN_VARIANT (ctype);
13383 template_count = num_template_headers_for_class (ctype);
13385 if (ctype == current_class_type)
13387 if (friendp)
13389 permerror (declspecs->locations[ds_friend],
13390 "member functions are implicitly "
13391 "friends of their class");
13392 friendp = 0;
13394 else
13395 permerror (id_loc, "extra qualification %<%T::%> on member %qs",
13396 ctype, name);
13398 else if (/* If the qualifying type is already complete, then we
13399 can skip the following checks. */
13400 !COMPLETE_TYPE_P (ctype)
13401 && (/* If the function is being defined, then
13402 qualifying type must certainly be complete. */
13403 funcdef_flag
13404 /* A friend declaration of "T::f" is OK, even if
13405 "T" is a template parameter. But, if this
13406 function is not a friend, the qualifying type
13407 must be a class. */
13408 || (!friendp && !CLASS_TYPE_P (ctype))
13409 /* For a declaration, the type need not be
13410 complete, if either it is dependent (since there
13411 is no meaningful definition of complete in that
13412 case) or the qualifying class is currently being
13413 defined. */
13414 || !(dependent_type_p (ctype)
13415 || currently_open_class (ctype)))
13416 /* Check that the qualifying type is complete. */
13417 && !complete_type_or_else (ctype, NULL_TREE))
13418 return error_mark_node;
13419 else if (TREE_CODE (type) == FUNCTION_TYPE)
13421 if (current_class_type
13422 && (!friendp || funcdef_flag || initialized))
13424 error_at (id_loc, funcdef_flag || initialized
13425 ? G_("cannot define member function %<%T::%s%> "
13426 "within %qT")
13427 : G_("cannot declare member function %<%T::%s%> "
13428 "within %qT"),
13429 ctype, name, current_class_type);
13430 return error_mark_node;
13433 else if (typedef_p && current_class_type)
13435 error_at (id_loc, "cannot declare member %<%T::%s%> within %qT",
13436 ctype, name, current_class_type);
13437 return error_mark_node;
13441 if (ctype == NULL_TREE && decl_context == FIELD && friendp == 0)
13442 ctype = current_class_type;
13444 /* Now TYPE has the actual type. */
13446 if (returned_attrs)
13448 if (attrlist)
13449 *attrlist = attr_chainon (returned_attrs, *attrlist);
13450 else
13451 attrlist = &returned_attrs;
13454 if (declarator
13455 && declarator->kind == cdk_id
13456 && declarator->std_attributes
13457 && attrlist != NULL)
13459 /* [dcl.meaning]/1: The optional attribute-specifier-seq following
13460 a declarator-id appertains to the entity that is declared. */
13461 if (declarator->std_attributes != error_mark_node)
13462 *attrlist = attr_chainon (*attrlist, declarator->std_attributes);
13463 else
13464 /* We should have already diagnosed the issue (c++/78344). */
13465 gcc_assert (seen_error ());
13468 /* Handle parameter packs. */
13469 if (parameter_pack_p)
13471 if (decl_context == PARM)
13472 /* Turn the type into a pack expansion.*/
13473 type = make_pack_expansion (type);
13474 else
13475 error ("non-parameter %qs cannot be a parameter pack", name);
13478 if ((decl_context == FIELD || decl_context == PARM)
13479 && !processing_template_decl
13480 && variably_modified_type_p (type, NULL_TREE))
13482 if (decl_context == FIELD)
13483 error_at (id_loc,
13484 "data member may not have variably modified type %qT", type);
13485 else
13486 error_at (id_loc,
13487 "parameter may not have variably modified type %qT", type);
13488 type = error_mark_node;
13491 if (explicitp == 1 || (explicitp && friendp))
13493 /* [dcl.fct.spec] (C++11) The explicit specifier shall be used only
13494 in the declaration of a constructor or conversion function within
13495 a class definition. */
13496 if (!current_class_type)
13497 error_at (declspecs->locations[ds_explicit],
13498 "%<explicit%> outside class declaration");
13499 else if (friendp)
13500 error_at (declspecs->locations[ds_explicit],
13501 "%<explicit%> in friend declaration");
13502 else
13503 error_at (declspecs->locations[ds_explicit],
13504 "only declarations of constructors and conversion operators "
13505 "can be %<explicit%>");
13506 explicitp = 0;
13509 if (storage_class == sc_mutable)
13511 location_t sloc = declspecs->locations[ds_storage_class];
13512 if (decl_context != FIELD || friendp)
13514 error_at (sloc, "non-member %qs cannot be declared %<mutable%>",
13515 name);
13516 storage_class = sc_none;
13518 else if (decl_context == TYPENAME || typedef_p)
13520 error_at (sloc,
13521 "non-object member %qs cannot be declared %<mutable%>",
13522 name);
13523 storage_class = sc_none;
13525 else if (FUNC_OR_METHOD_TYPE_P (type))
13527 error_at (sloc, "function %qs cannot be declared %<mutable%>",
13528 name);
13529 storage_class = sc_none;
13531 else if (staticp)
13533 error_at (sloc, "%<static%> %qs cannot be declared %<mutable%>",
13534 name);
13535 storage_class = sc_none;
13537 else if (type_quals & TYPE_QUAL_CONST)
13539 error_at (sloc, "%<const%> %qs cannot be declared %<mutable%>",
13540 name);
13541 storage_class = sc_none;
13543 else if (TYPE_REF_P (type))
13545 permerror (sloc, "reference %qs cannot be declared %<mutable%>",
13546 name);
13547 storage_class = sc_none;
13551 /* If this is declaring a typedef name, return a TYPE_DECL. */
13552 if (typedef_p && decl_context != TYPENAME)
13554 bool alias_p = decl_spec_seq_has_spec_p (declspecs, ds_alias);
13555 tree decl;
13557 if (funcdef_flag)
13559 if (decl_context == NORMAL)
13560 error_at (id_loc,
13561 "typedef may not be a function definition");
13562 else
13563 error_at (id_loc,
13564 "typedef may not be a member function definition");
13565 return error_mark_node;
13568 /* This declaration:
13570 typedef void f(int) const;
13572 declares a function type which is not a member of any
13573 particular class, but which is cv-qualified; for
13574 example "f S::*" declares a pointer to a const-qualified
13575 member function of S. We record the cv-qualification in the
13576 function type. */
13577 if ((rqual || memfn_quals) && TREE_CODE (type) == FUNCTION_TYPE)
13579 type = apply_memfn_quals (type, memfn_quals, rqual);
13581 /* We have now dealt with these qualifiers. */
13582 memfn_quals = TYPE_UNQUALIFIED;
13583 rqual = REF_QUAL_NONE;
13586 if (type_uses_auto (type))
13588 if (alias_p)
13589 error_at (declspecs->locations[ds_type_spec],
13590 "%<auto%> not allowed in alias declaration");
13591 else
13592 error_at (declspecs->locations[ds_type_spec],
13593 "typedef declared %<auto%>");
13594 type = error_mark_node;
13597 if (reqs)
13598 error_at (location_of (reqs), "requires-clause on typedef");
13600 if (id_declarator && declarator->u.id.qualifying_scope)
13602 error_at (id_loc, "typedef name may not be a nested-name-specifier");
13603 type = error_mark_node;
13606 if (decl_context == FIELD)
13607 decl = build_lang_decl_loc (id_loc, TYPE_DECL, unqualified_id, type);
13608 else
13609 decl = build_decl (id_loc, TYPE_DECL, unqualified_id, type);
13611 if (decl_context != FIELD)
13613 if (!current_function_decl)
13614 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
13615 else if (DECL_MAYBE_IN_CHARGE_CDTOR_P (current_function_decl))
13616 /* The TYPE_DECL is "abstract" because there will be
13617 clones of this constructor/destructor, and there will
13618 be copies of this TYPE_DECL generated in those
13619 clones. The decloning optimization (for space) may
13620 revert this subsequently if it determines that
13621 the clones should share a common implementation. */
13622 DECL_ABSTRACT_P (decl) = true;
13624 set_originating_module (decl);
13626 else if (current_class_type
13627 && constructor_name_p (unqualified_id, current_class_type))
13628 permerror (id_loc, "ISO C++ forbids nested type %qD with same name "
13629 "as enclosing class",
13630 unqualified_id);
13632 /* If the user declares "typedef struct {...} foo" then the
13633 struct will have an anonymous name. Fill that name in now.
13634 Nothing can refer to it, so nothing needs know about the name
13635 change. */
13636 if (type != error_mark_node
13637 && unqualified_id
13638 && TYPE_NAME (type)
13639 && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL
13640 && TYPE_UNNAMED_P (type)
13641 && declspecs->type_definition_p
13642 && attributes_naming_typedef_ok (*attrlist)
13643 && cp_type_quals (type) == TYPE_UNQUALIFIED)
13644 name_unnamed_type (type, decl);
13646 if (signed_p
13647 || (typedef_decl && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl)))
13648 C_TYPEDEF_EXPLICITLY_SIGNED (decl) = 1;
13650 bad_specifiers (decl, BSP_TYPE, virtualp,
13651 memfn_quals != TYPE_UNQUALIFIED,
13652 inlinep, friendp, raises != NULL_TREE,
13653 declspecs->locations);
13655 if (alias_p)
13656 /* Acknowledge that this was written:
13657 `using analias = atype;'. */
13658 TYPE_DECL_ALIAS_P (decl) = 1;
13660 return decl;
13663 /* Detect the case of an array type of unspecified size
13664 which came, as such, direct from a typedef name.
13665 We must copy the type, so that the array's domain can be
13666 individually set by the object's initializer. */
13668 if (type && typedef_type
13669 && TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type)
13670 && TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (typedef_type))
13671 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
13673 /* Detect where we're using a typedef of function type to declare a
13674 function. PARMS will not be set, so we must create it now. */
13676 if (type == typedef_type && TREE_CODE (type) == FUNCTION_TYPE)
13678 tree decls = NULL_TREE;
13679 tree args;
13681 for (args = TYPE_ARG_TYPES (type);
13682 args && args != void_list_node;
13683 args = TREE_CHAIN (args))
13685 tree decl = cp_build_parm_decl (NULL_TREE, NULL_TREE,
13686 TREE_VALUE (args));
13688 DECL_CHAIN (decl) = decls;
13689 decls = decl;
13692 parms = nreverse (decls);
13694 if (decl_context != TYPENAME)
13696 /* The qualifiers on the function type become the qualifiers on
13697 the non-static member function. */
13698 memfn_quals |= type_memfn_quals (type);
13699 rqual = type_memfn_rqual (type);
13700 type_quals = TYPE_UNQUALIFIED;
13701 raises = TYPE_RAISES_EXCEPTIONS (type);
13705 /* If this is a type name (such as, in a cast or sizeof),
13706 compute the type and return it now. */
13708 if (decl_context == TYPENAME)
13710 /* Note that here we don't care about type_quals. */
13712 /* Special case: "friend class foo" looks like a TYPENAME context. */
13713 if (friendp)
13715 if (inlinep)
13717 error ("%<inline%> specified for friend class declaration");
13718 inlinep = 0;
13721 if (!current_aggr)
13723 /* Don't allow friend declaration without a class-key. */
13724 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
13725 permerror (input_location, "template parameters cannot be friends");
13726 else if (TREE_CODE (type) == TYPENAME_TYPE)
13727 permerror (input_location, "friend declaration requires class-key, "
13728 "i.e. %<friend class %T::%D%>",
13729 TYPE_CONTEXT (type), TYPENAME_TYPE_FULLNAME (type));
13730 else
13731 permerror (input_location, "friend declaration requires class-key, "
13732 "i.e. %<friend %#T%>",
13733 type);
13736 /* Only try to do this stuff if we didn't already give up. */
13737 if (type != integer_type_node)
13739 /* A friendly class? */
13740 if (current_class_type)
13741 make_friend_class (current_class_type, TYPE_MAIN_VARIANT (type),
13742 /*complain=*/true);
13743 else
13744 error ("trying to make class %qT a friend of global scope",
13745 type);
13747 type = void_type_node;
13750 else if (memfn_quals || rqual)
13752 if (ctype == NULL_TREE
13753 && TREE_CODE (type) == METHOD_TYPE)
13754 ctype = TYPE_METHOD_BASETYPE (type);
13756 if (ctype)
13757 type = build_memfn_type (type, ctype, memfn_quals, rqual);
13758 /* Core issue #547: need to allow this in template type args.
13759 Allow it in general in C++11 for alias-declarations. */
13760 else if ((template_type_arg || cxx_dialect >= cxx11)
13761 && TREE_CODE (type) == FUNCTION_TYPE)
13762 type = apply_memfn_quals (type, memfn_quals, rqual);
13763 else
13764 error ("invalid qualifiers on non-member function type");
13767 if (reqs)
13768 error_at (location_of (reqs), "requires-clause on type-id");
13770 return type;
13772 else if (unqualified_id == NULL_TREE && decl_context != PARM
13773 && decl_context != CATCHPARM
13774 && TREE_CODE (type) != UNION_TYPE
13775 && ! bitfield
13776 && innermost_code != cdk_decomp)
13778 error ("abstract declarator %qT used as declaration", type);
13779 return error_mark_node;
13782 if (!FUNC_OR_METHOD_TYPE_P (type))
13784 /* Only functions may be declared using an operator-function-id. */
13785 if (dname && IDENTIFIER_ANY_OP_P (dname))
13787 error_at (id_loc, "declaration of %qD as non-function", dname);
13788 return error_mark_node;
13791 if (reqs)
13792 error_at (location_of (reqs),
13793 "requires-clause on declaration of non-function type %qT",
13794 type);
13797 /* We don't check parameter types here because we can emit a better
13798 error message later. */
13799 if (decl_context != PARM)
13801 type = check_var_type (unqualified_id, type, id_loc);
13802 if (type == error_mark_node)
13803 return error_mark_node;
13806 /* Now create the decl, which may be a VAR_DECL, a PARM_DECL
13807 or a FUNCTION_DECL, depending on DECL_CONTEXT and TYPE. */
13809 if (decl_context == PARM || decl_context == CATCHPARM)
13811 if (ctype || in_namespace)
13812 error ("cannot use %<::%> in parameter declaration");
13814 tree auto_node = type_uses_auto (type);
13815 if (auto_node && !(cxx_dialect >= cxx17 && template_parm_flag))
13817 if (cxx_dialect >= cxx14)
13819 if (decl_context == PARM && AUTO_IS_DECLTYPE (auto_node))
13820 error_at (typespec_loc,
13821 "cannot declare a parameter with %<decltype(auto)%>");
13822 else if (tree c = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
13824 auto_diagnostic_group g;
13825 error_at (typespec_loc,
13826 "class template placeholder %qE not permitted "
13827 "in this context", c);
13828 if (decl_context == PARM && cxx_dialect >= cxx20)
13829 inform (typespec_loc, "use %<auto%> for an "
13830 "abbreviated function template");
13832 else
13833 error_at (typespec_loc,
13834 "%<auto%> parameter not permitted in this context");
13836 else
13837 error_at (typespec_loc, "parameter declared %<auto%>");
13838 type = error_mark_node;
13841 /* A parameter declared as an array of T is really a pointer to T.
13842 One declared as a function is really a pointer to a function.
13843 One declared as a member is really a pointer to member. */
13845 if (TREE_CODE (type) == ARRAY_TYPE)
13847 /* Transfer const-ness of array into that of type pointed to. */
13848 type = build_pointer_type (TREE_TYPE (type));
13849 type_quals = TYPE_UNQUALIFIED;
13850 array_parameter_p = true;
13852 else if (TREE_CODE (type) == FUNCTION_TYPE)
13853 type = build_pointer_type (type);
13856 if (ctype && TREE_CODE (type) == FUNCTION_TYPE && staticp < 2
13857 && !(unqualified_id
13858 && identifier_p (unqualified_id)
13859 && IDENTIFIER_NEWDEL_OP_P (unqualified_id)))
13861 cp_cv_quals real_quals = memfn_quals;
13862 if (cxx_dialect < cxx14 && constexpr_p
13863 && sfk != sfk_constructor && sfk != sfk_destructor)
13864 real_quals |= TYPE_QUAL_CONST;
13865 type = build_memfn_type (type, ctype, real_quals, rqual);
13869 tree decl = NULL_TREE;
13871 if (decl_context == PARM)
13873 decl = cp_build_parm_decl (NULL_TREE, unqualified_id, type);
13874 DECL_ARRAY_PARAMETER_P (decl) = array_parameter_p;
13876 bad_specifiers (decl, BSP_PARM, virtualp,
13877 memfn_quals != TYPE_UNQUALIFIED,
13878 inlinep, friendp, raises != NULL_TREE,
13879 declspecs->locations);
13881 else if (decl_context == FIELD)
13883 if (!staticp && !friendp && !FUNC_OR_METHOD_TYPE_P (type))
13884 if (tree auto_node = type_uses_auto (type))
13886 location_t tloc = declspecs->locations[ds_type_spec];
13887 if (CLASS_PLACEHOLDER_TEMPLATE (auto_node))
13888 error_at (tloc, "invalid use of template-name %qE without an "
13889 "argument list",
13890 CLASS_PLACEHOLDER_TEMPLATE (auto_node));
13891 else
13892 error_at (tloc, "non-static data member declared with "
13893 "placeholder %qT", auto_node);
13894 type = error_mark_node;
13897 /* The C99 flexible array extension. */
13898 if (!staticp && TREE_CODE (type) == ARRAY_TYPE
13899 && TYPE_DOMAIN (type) == NULL_TREE)
13901 if (ctype
13902 && (TREE_CODE (ctype) == UNION_TYPE
13903 || TREE_CODE (ctype) == QUAL_UNION_TYPE))
13905 error_at (id_loc, "flexible array member in union");
13906 type = error_mark_node;
13908 else
13910 /* Array is a flexible member. */
13911 if (name)
13912 pedwarn (id_loc, OPT_Wpedantic,
13913 "ISO C++ forbids flexible array member %qs", name);
13914 else
13915 pedwarn (input_location, OPT_Wpedantic,
13916 "ISO C++ forbids flexible array members");
13918 /* Flexible array member has a null domain. */
13919 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
13923 if (type == error_mark_node)
13925 /* Happens when declaring arrays of sizes which
13926 are error_mark_node, for example. */
13927 decl = NULL_TREE;
13929 else if (in_namespace && !friendp)
13931 /* Something like struct S { int N::j; }; */
13932 error_at (id_loc, "invalid use of %<::%>");
13933 return error_mark_node;
13935 else if (FUNC_OR_METHOD_TYPE_P (type) && unqualified_id)
13937 int publicp = 0;
13938 tree function_context;
13940 if (friendp == 0)
13942 /* This should never happen in pure C++ (the check
13943 could be an assert). It could happen in
13944 Objective-C++ if someone writes invalid code that
13945 uses a function declaration for an instance
13946 variable or property (instance variables and
13947 properties are parsed as FIELD_DECLs, but they are
13948 part of an Objective-C class, not a C++ class).
13949 That code is invalid and is caught by this
13950 check. */
13951 if (!ctype)
13953 error ("declaration of function %qD in invalid context",
13954 unqualified_id);
13955 return error_mark_node;
13958 /* ``A union may [ ... ] not [ have ] virtual functions.''
13959 ARM 9.5 */
13960 if (virtualp && TREE_CODE (ctype) == UNION_TYPE)
13962 error_at (declspecs->locations[ds_virtual],
13963 "function %qD declared %<virtual%> inside a union",
13964 unqualified_id);
13965 return error_mark_node;
13968 if (virtualp
13969 && identifier_p (unqualified_id)
13970 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
13972 error_at (declspecs->locations[ds_virtual],
13973 "%qD cannot be declared %<virtual%>, since it "
13974 "is always static", unqualified_id);
13975 virtualp = 0;
13979 /* Check that the name used for a destructor makes sense. */
13980 if (sfk == sfk_destructor)
13982 tree uqname = id_declarator->u.id.unqualified_name;
13984 if (!ctype)
13986 gcc_assert (friendp);
13987 error_at (id_loc, "expected qualified name in friend "
13988 "declaration for destructor %qD", uqname);
13989 return error_mark_node;
13992 if (!check_dtor_name (ctype, TREE_OPERAND (uqname, 0)))
13994 error_at (id_loc, "declaration of %qD as member of %qT",
13995 uqname, ctype);
13996 return error_mark_node;
13998 if (concept_p)
14000 error_at (declspecs->locations[ds_concept],
14001 "a destructor cannot be %qs", "concept");
14002 return error_mark_node;
14004 if (constexpr_p && cxx_dialect < cxx20)
14006 error_at (declspecs->locations[ds_constexpr],
14007 "%<constexpr%> destructors only available"
14008 " with %<-std=c++20%> or %<-std=gnu++20%>");
14009 return error_mark_node;
14011 if (consteval_p)
14013 error_at (declspecs->locations[ds_consteval],
14014 "a destructor cannot be %qs", "consteval");
14015 return error_mark_node;
14018 else if (sfk == sfk_constructor && friendp && !ctype)
14020 error ("expected qualified name in friend declaration "
14021 "for constructor %qD",
14022 id_declarator->u.id.unqualified_name);
14023 return error_mark_node;
14025 if (sfk == sfk_constructor)
14026 if (concept_p)
14028 error_at (declspecs->locations[ds_concept],
14029 "a constructor cannot be %<concept%>");
14030 return error_mark_node;
14032 if (concept_p)
14034 error_at (declspecs->locations[ds_concept],
14035 "a concept cannot be a member function");
14036 concept_p = false;
14038 else if (consteval_p
14039 && identifier_p (unqualified_id)
14040 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14042 error_at (declspecs->locations[ds_consteval],
14043 "%qD cannot be %qs", unqualified_id, "consteval");
14044 consteval_p = false;
14047 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14049 tree tmpl = TREE_OPERAND (unqualified_id, 0);
14050 if (variable_template_p (tmpl))
14052 error_at (id_loc, "specialization of variable template "
14053 "%qD declared as function", tmpl);
14054 inform (DECL_SOURCE_LOCATION (tmpl),
14055 "variable template declared here");
14056 return error_mark_node;
14060 /* Tell grokfndecl if it needs to set TREE_PUBLIC on the node. */
14061 function_context
14062 = (ctype != NULL_TREE
14063 ? decl_function_context (TYPE_MAIN_DECL (ctype)) : NULL_TREE);
14064 publicp = ((! friendp || ! staticp)
14065 && function_context == NULL_TREE);
14067 decl = grokfndecl (ctype, type,
14068 TREE_CODE (unqualified_id) != TEMPLATE_ID_EXPR
14069 ? unqualified_id : dname,
14070 parms,
14071 unqualified_id,
14072 declspecs,
14073 reqs,
14074 virtualp, flags, memfn_quals, rqual, raises,
14075 friendp ? -1 : 0, friendp, publicp,
14076 inlinep | (2 * constexpr_p) | (4 * concept_p)
14077 | (8 * consteval_p),
14078 initialized == SD_DELETED, sfk,
14079 funcdef_flag, late_return_type_p,
14080 template_count, in_namespace,
14081 attrlist, id_loc);
14082 decl = set_virt_specifiers (decl, virt_specifiers);
14083 if (decl == NULL_TREE)
14084 return error_mark_node;
14085 #if 0
14086 /* This clobbers the attrs stored in `decl' from `attrlist'. */
14087 /* The decl and setting of decl_attr is also turned off. */
14088 decl = build_decl_attribute_variant (decl, decl_attr);
14089 #endif
14091 /* [class.conv.ctor]
14093 A constructor declared without the function-specifier
14094 explicit that can be called with a single parameter
14095 specifies a conversion from the type of its first
14096 parameter to the type of its class. Such a constructor
14097 is called a converting constructor. */
14098 if (explicitp == 2)
14099 DECL_NONCONVERTING_P (decl) = 1;
14101 if (declspecs->explicit_specifier)
14102 store_explicit_specifier (decl, declspecs->explicit_specifier);
14104 else if (!staticp
14105 && ((current_class_type
14106 && same_type_p (type, current_class_type))
14107 || (!dependent_type_p (type)
14108 && !COMPLETE_TYPE_P (complete_type (type))
14109 && (!complete_or_array_type_p (type)
14110 || initialized == SD_UNINITIALIZED))))
14112 if (TREE_CODE (type) != ARRAY_TYPE
14113 || !COMPLETE_TYPE_P (TREE_TYPE (type)))
14115 if (unqualified_id)
14117 error_at (id_loc, "field %qD has incomplete type %qT",
14118 unqualified_id, type);
14119 cxx_incomplete_type_inform (strip_array_types (type));
14121 else
14122 error ("name %qT has incomplete type", type);
14124 type = error_mark_node;
14125 decl = NULL_TREE;
14128 else if (!verify_type_context (input_location,
14129 staticp
14130 ? TCTX_STATIC_STORAGE
14131 : TCTX_FIELD, type))
14133 type = error_mark_node;
14134 decl = NULL_TREE;
14136 else
14138 if (friendp)
14140 if (unqualified_id)
14141 error_at (id_loc,
14142 "%qE is neither function nor member function; "
14143 "cannot be declared friend", unqualified_id);
14144 else
14145 error ("unnamed field is neither function nor member "
14146 "function; cannot be declared friend");
14147 return error_mark_node;
14149 decl = NULL_TREE;
14152 if (friendp)
14154 /* Packages tend to use GNU attributes on friends, so we only
14155 warn for standard attributes. */
14156 if (attrlist && !funcdef_flag && cxx11_attribute_p (*attrlist))
14158 *attrlist = NULL_TREE;
14159 if (warning_at (id_loc, OPT_Wattributes, "attribute ignored"))
14160 inform (id_loc, "an attribute that appertains to a friend "
14161 "declaration that is not a definition is ignored");
14163 /* Friends are treated specially. */
14164 if (ctype == current_class_type)
14165 ; /* We already issued a permerror. */
14166 else if (decl && DECL_NAME (decl))
14168 set_originating_module (decl, true);
14170 if (initialized)
14171 /* Kludge: We need funcdef_flag to be true in do_friend for
14172 in-class defaulted functions, but that breaks grokfndecl.
14173 So set it here. */
14174 funcdef_flag = true;
14176 decl = do_friend (ctype, unqualified_id, decl,
14177 flags, funcdef_flag);
14178 return decl;
14180 else
14181 return error_mark_node;
14184 /* Structure field. It may not be a function, except for C++. */
14186 if (decl == NULL_TREE)
14188 if (staticp)
14190 /* C++ allows static class members. All other work
14191 for this is done by grokfield. */
14192 decl = build_lang_decl_loc (id_loc, VAR_DECL,
14193 unqualified_id, type);
14194 set_linkage_for_static_data_member (decl);
14195 if (concept_p)
14196 error_at (declspecs->locations[ds_concept],
14197 "static data member %qE declared %qs",
14198 unqualified_id, "concept");
14199 else if (constexpr_p && !initialized)
14201 error_at (DECL_SOURCE_LOCATION (decl),
14202 "%<constexpr%> static data member %qD must "
14203 "have an initializer", decl);
14204 constexpr_p = false;
14206 if (consteval_p)
14207 error_at (declspecs->locations[ds_consteval],
14208 "static data member %qE declared %qs",
14209 unqualified_id, "consteval");
14211 if (inlinep)
14212 mark_inline_variable (decl, declspecs->locations[ds_inline]);
14214 if (!DECL_VAR_DECLARED_INLINE_P (decl)
14215 && !(cxx_dialect >= cxx17 && constexpr_p))
14216 /* Even if there is an in-class initialization, DECL
14217 is considered undefined until an out-of-class
14218 definition is provided, unless this is an inline
14219 variable. */
14220 DECL_EXTERNAL (decl) = 1;
14222 if (thread_p)
14224 CP_DECL_THREAD_LOCAL_P (decl) = true;
14225 if (!processing_template_decl)
14226 set_decl_tls_model (decl, decl_default_tls_model (decl));
14227 if (declspecs->gnu_thread_keyword_p)
14228 SET_DECL_GNU_TLS_P (decl);
14231 /* Set the constraints on the declaration. */
14232 bool memtmpl = (current_template_depth
14233 > template_class_depth (current_class_type));
14234 if (memtmpl)
14236 tree ci = current_template_constraints ();
14237 set_constraints (decl, ci);
14240 else
14242 if (concept_p)
14244 error_at (declspecs->locations[ds_concept],
14245 "non-static data member %qE declared %qs",
14246 unqualified_id, "concept");
14247 concept_p = false;
14248 constexpr_p = false;
14250 else if (constexpr_p)
14252 error_at (declspecs->locations[ds_constexpr],
14253 "non-static data member %qE declared %qs",
14254 unqualified_id, "constexpr");
14255 constexpr_p = false;
14257 if (constinit_p)
14259 error_at (declspecs->locations[ds_constinit],
14260 "non-static data member %qE declared %qs",
14261 unqualified_id, "constinit");
14262 constinit_p = false;
14264 if (consteval_p)
14266 error_at (declspecs->locations[ds_consteval],
14267 "non-static data member %qE declared %qs",
14268 unqualified_id, "consteval");
14269 consteval_p = false;
14271 decl = build_decl (id_loc, FIELD_DECL, unqualified_id, type);
14272 DECL_NONADDRESSABLE_P (decl) = bitfield;
14273 if (bitfield && !unqualified_id)
14274 DECL_PADDING_P (decl) = 1;
14276 if (storage_class == sc_mutable)
14278 DECL_MUTABLE_P (decl) = 1;
14279 storage_class = sc_none;
14282 if (initialized)
14284 /* An attempt is being made to initialize a non-static
14285 member. This is new in C++11. */
14286 maybe_warn_cpp0x (CPP0X_NSDMI, init_loc);
14288 /* If this has been parsed with static storage class, but
14289 errors forced staticp to be cleared, ensure NSDMI is
14290 not present. */
14291 if (declspecs->storage_class == sc_static)
14292 DECL_INITIAL (decl) = error_mark_node;
14296 bad_specifiers (decl, BSP_FIELD, virtualp,
14297 memfn_quals != TYPE_UNQUALIFIED,
14298 staticp ? false : inlinep, friendp,
14299 raises != NULL_TREE,
14300 declspecs->locations);
14303 else if (FUNC_OR_METHOD_TYPE_P (type))
14305 tree original_name;
14306 int publicp = 0;
14308 if (!unqualified_id)
14309 return error_mark_node;
14311 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14312 original_name = dname;
14313 else
14314 original_name = unqualified_id;
14315 // FIXME:gcc_assert (original_name == dname);
14317 if (storage_class == sc_auto)
14318 error_at (declspecs->locations[ds_storage_class],
14319 "storage class %<auto%> invalid for function %qs", name);
14320 else if (storage_class == sc_register)
14321 error_at (declspecs->locations[ds_storage_class],
14322 "storage class %<register%> invalid for function %qs",
14323 name);
14324 else if (thread_p)
14326 if (declspecs->gnu_thread_keyword_p)
14327 error_at (declspecs->locations[ds_thread],
14328 "storage class %<__thread%> invalid for function %qs",
14329 name);
14330 else
14331 error_at (declspecs->locations[ds_thread],
14332 "storage class %<thread_local%> invalid for "
14333 "function %qs", name);
14336 if (virt_specifiers)
14337 error ("virt-specifiers in %qs not allowed outside a class "
14338 "definition", name);
14339 /* Function declaration not at top level.
14340 Storage classes other than `extern' are not allowed
14341 and `extern' makes no difference. */
14342 if (! toplevel_bindings_p ()
14343 && (storage_class == sc_static
14344 || decl_spec_seq_has_spec_p (declspecs, ds_inline))
14345 && pedantic)
14347 if (storage_class == sc_static)
14348 pedwarn (declspecs->locations[ds_storage_class], OPT_Wpedantic,
14349 "%<static%> specifier invalid for function %qs "
14350 "declared out of global scope", name);
14351 else
14352 pedwarn (declspecs->locations[ds_inline], OPT_Wpedantic,
14353 "%<inline%> specifier invalid for function %qs "
14354 "declared out of global scope", name);
14357 if (ctype == NULL_TREE)
14359 if (virtualp)
14361 error ("virtual non-class function %qs", name);
14362 virtualp = 0;
14364 else if (sfk == sfk_constructor
14365 || sfk == sfk_destructor)
14367 error (funcdef_flag
14368 ? G_("%qs defined in a non-class scope")
14369 : G_("%qs declared in a non-class scope"), name);
14370 sfk = sfk_none;
14373 if (consteval_p
14374 && identifier_p (unqualified_id)
14375 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14377 error_at (declspecs->locations[ds_consteval],
14378 "%qD cannot be %qs", unqualified_id, "consteval");
14379 consteval_p = false;
14382 /* Record whether the function is public. */
14383 publicp = (ctype != NULL_TREE
14384 || storage_class != sc_static);
14386 decl = grokfndecl (ctype, type, original_name, parms, unqualified_id,
14387 declspecs,
14388 reqs, virtualp, flags, memfn_quals, rqual, raises,
14389 1, friendp,
14390 publicp,
14391 inlinep | (2 * constexpr_p) | (4 * concept_p)
14392 | (8 * consteval_p),
14393 initialized == SD_DELETED,
14394 sfk,
14395 funcdef_flag,
14396 late_return_type_p,
14397 template_count, in_namespace, attrlist,
14398 id_loc);
14399 if (decl == NULL_TREE)
14400 return error_mark_node;
14402 if (explicitp == 2)
14403 DECL_NONCONVERTING_P (decl) = 1;
14404 if (staticp == 1)
14406 int invalid_static = 0;
14408 /* Don't allow a static member function in a class, and forbid
14409 declaring main to be static. */
14410 if (TREE_CODE (type) == METHOD_TYPE)
14412 permerror (input_location, "cannot declare member function %qD to have "
14413 "static linkage", decl);
14414 invalid_static = 1;
14416 else if (current_function_decl)
14418 /* 7.1.1: There can be no static function declarations within a
14419 block. */
14420 error_at (declspecs->locations[ds_storage_class],
14421 "cannot declare static function inside another function");
14422 invalid_static = 1;
14425 if (invalid_static)
14427 staticp = 0;
14428 storage_class = sc_none;
14431 if (declspecs->explicit_specifier)
14432 store_explicit_specifier (decl, declspecs->explicit_specifier);
14434 else
14436 /* It's a variable. */
14438 /* An uninitialized decl with `extern' is a reference. */
14439 decl = grokvardecl (type, dname, unqualified_id,
14440 declspecs,
14441 initialized,
14442 type_quals,
14443 inlinep,
14444 concept_p,
14445 template_count,
14446 ctype ? ctype : in_namespace,
14447 id_loc);
14448 if (decl == NULL_TREE)
14449 return error_mark_node;
14451 bad_specifiers (decl, BSP_VAR, virtualp,
14452 memfn_quals != TYPE_UNQUALIFIED,
14453 inlinep, friendp, raises != NULL_TREE,
14454 declspecs->locations);
14456 if (ctype)
14458 DECL_CONTEXT (decl) = ctype;
14459 if (staticp == 1)
14461 permerror (declspecs->locations[ds_storage_class],
14462 "%<static%> may not be used when defining "
14463 "(as opposed to declaring) a static data member");
14464 staticp = 0;
14465 storage_class = sc_none;
14467 if (storage_class == sc_register && TREE_STATIC (decl))
14469 error ("static member %qD declared %<register%>", decl);
14470 storage_class = sc_none;
14472 if (storage_class == sc_extern && pedantic)
14474 pedwarn (input_location, OPT_Wpedantic,
14475 "cannot explicitly declare member %q#D to have "
14476 "extern linkage", decl);
14477 storage_class = sc_none;
14480 else if (constexpr_p && DECL_EXTERNAL (decl))
14482 error_at (DECL_SOURCE_LOCATION (decl),
14483 "declaration of %<constexpr%> variable %qD "
14484 "is not a definition", decl);
14485 constexpr_p = false;
14487 if (consteval_p)
14489 error_at (DECL_SOURCE_LOCATION (decl),
14490 "a variable cannot be declared %<consteval%>");
14491 consteval_p = false;
14494 if (inlinep)
14495 mark_inline_variable (decl, declspecs->locations[ds_inline]);
14496 if (innermost_code == cdk_decomp)
14498 gcc_assert (declarator && declarator->kind == cdk_decomp);
14499 DECL_SOURCE_LOCATION (decl) = id_loc;
14500 DECL_ARTIFICIAL (decl) = 1;
14501 fit_decomposition_lang_decl (decl, NULL_TREE);
14505 if (VAR_P (decl) && !initialized)
14506 if (tree auto_node = type_uses_auto (type))
14507 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14509 location_t loc = declspecs->locations[ds_type_spec];
14510 error_at (loc, "declaration of %q#D has no initializer", decl);
14511 TREE_TYPE (decl) = error_mark_node;
14514 if (storage_class == sc_extern && initialized && !funcdef_flag)
14516 if (toplevel_bindings_p ())
14518 /* It's common practice (and completely valid) to have a const
14519 be initialized and declared extern. */
14520 if (!(type_quals & TYPE_QUAL_CONST))
14521 warning_at (DECL_SOURCE_LOCATION (decl), 0,
14522 "%qs initialized and declared %<extern%>", name);
14524 else
14526 error_at (DECL_SOURCE_LOCATION (decl),
14527 "%qs has both %<extern%> and initializer", name);
14528 return error_mark_node;
14532 /* Record `register' declaration for warnings on &
14533 and in case doing stupid register allocation. */
14535 if (storage_class == sc_register)
14537 DECL_REGISTER (decl) = 1;
14538 /* Warn about register storage specifiers on PARM_DECLs. */
14539 if (TREE_CODE (decl) == PARM_DECL)
14541 if (cxx_dialect >= cxx17)
14542 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
14543 "ISO C++17 does not allow %<register%> storage "
14544 "class specifier");
14545 else
14546 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
14547 "%<register%> storage class specifier used");
14550 else if (storage_class == sc_extern)
14551 DECL_THIS_EXTERN (decl) = 1;
14552 else if (storage_class == sc_static)
14553 DECL_THIS_STATIC (decl) = 1;
14555 if (VAR_P (decl))
14557 /* Set constexpr flag on vars (functions got it in grokfndecl). */
14558 if (constexpr_p)
14559 DECL_DECLARED_CONSTEXPR_P (decl) = true;
14560 /* And the constinit flag (which only applies to variables). */
14561 else if (constinit_p)
14562 DECL_DECLARED_CONSTINIT_P (decl) = true;
14565 /* Record constancy and volatility on the DECL itself . There's
14566 no need to do this when processing a template; we'll do this
14567 for the instantiated declaration based on the type of DECL. */
14568 if (!processing_template_decl)
14569 cp_apply_type_quals_to_decl (type_quals, decl);
14571 return decl;
14575 /* Subroutine of start_function. Ensure that each of the parameter
14576 types (as listed in PARMS) is complete, as is required for a
14577 function definition. */
14579 static void
14580 require_complete_types_for_parms (tree parms)
14582 for (; parms; parms = DECL_CHAIN (parms))
14584 if (dependent_type_p (TREE_TYPE (parms)))
14585 continue;
14586 if (!VOID_TYPE_P (TREE_TYPE (parms))
14587 && complete_type_or_else (TREE_TYPE (parms), parms))
14589 relayout_decl (parms);
14590 DECL_ARG_TYPE (parms) = type_passed_as (TREE_TYPE (parms));
14592 abstract_virtuals_error (parms, TREE_TYPE (parms));
14593 maybe_warn_parm_abi (TREE_TYPE (parms),
14594 DECL_SOURCE_LOCATION (parms));
14596 else
14597 /* grokparms or complete_type_or_else will have already issued
14598 an error. */
14599 TREE_TYPE (parms) = error_mark_node;
14603 /* Returns nonzero if T is a local variable. */
14606 local_variable_p (const_tree t)
14608 if ((VAR_P (t)
14609 && (DECL_LOCAL_DECL_P (t)
14610 || !DECL_CONTEXT (t)
14611 || TREE_CODE (DECL_CONTEXT (t)) == FUNCTION_DECL))
14612 || (TREE_CODE (t) == PARM_DECL))
14613 return 1;
14615 return 0;
14618 /* Like local_variable_p, but suitable for use as a tree-walking
14619 function. */
14621 static tree
14622 local_variable_p_walkfn (tree *tp, int *walk_subtrees,
14623 void * /*data*/)
14625 if (unevaluated_p (TREE_CODE (*tp)))
14627 /* DR 2082 permits local variables in unevaluated contexts
14628 within a default argument. */
14629 *walk_subtrees = 0;
14630 return NULL_TREE;
14633 if (local_variable_p (*tp)
14634 && (!DECL_ARTIFICIAL (*tp) || DECL_NAME (*tp) == this_identifier))
14635 return *tp;
14636 else if (TYPE_P (*tp))
14637 *walk_subtrees = 0;
14639 return NULL_TREE;
14642 /* Check that ARG, which is a default-argument expression for a
14643 parameter DECL, is valid. Returns ARG, or ERROR_MARK_NODE, if
14644 something goes wrong. DECL may also be a _TYPE node, rather than a
14645 DECL, if there is no DECL available. */
14647 tree
14648 check_default_argument (tree decl, tree arg, tsubst_flags_t complain)
14650 tree var;
14651 tree decl_type;
14653 if (TREE_CODE (arg) == DEFERRED_PARSE)
14654 /* We get a DEFERRED_PARSE when looking at an in-class declaration
14655 with a default argument. Ignore the argument for now; we'll
14656 deal with it after the class is complete. */
14657 return arg;
14659 if (TYPE_P (decl))
14661 decl_type = decl;
14662 decl = NULL_TREE;
14664 else
14665 decl_type = TREE_TYPE (decl);
14667 if (arg == error_mark_node
14668 || decl == error_mark_node
14669 || TREE_TYPE (arg) == error_mark_node
14670 || decl_type == error_mark_node)
14671 /* Something already went wrong. There's no need to check
14672 further. */
14673 return error_mark_node;
14675 /* [dcl.fct.default]
14677 A default argument expression is implicitly converted to the
14678 parameter type. */
14679 ++cp_unevaluated_operand;
14680 /* Avoid digest_init clobbering the initializer. */
14681 tree carg = BRACE_ENCLOSED_INITIALIZER_P (arg) ? unshare_expr (arg): arg;
14682 perform_implicit_conversion_flags (decl_type, carg, complain,
14683 LOOKUP_IMPLICIT);
14684 --cp_unevaluated_operand;
14686 /* Avoid redundant -Wzero-as-null-pointer-constant warnings at
14687 the call sites. */
14688 if (TYPE_PTR_OR_PTRMEM_P (decl_type)
14689 && null_ptr_cst_p (arg)
14690 /* Don't lose side-effects as in PR90473. */
14691 && !TREE_SIDE_EFFECTS (arg))
14692 return nullptr_node;
14694 /* [dcl.fct.default]
14696 Local variables shall not be used in default argument
14697 expressions.
14699 The keyword `this' shall not be used in a default argument of a
14700 member function. */
14701 var = cp_walk_tree_without_duplicates (&arg, local_variable_p_walkfn, NULL);
14702 if (var)
14704 if (complain & tf_warning_or_error)
14706 if (DECL_NAME (var) == this_identifier)
14707 permerror (input_location, "default argument %qE uses %qD",
14708 arg, var);
14709 else
14710 error ("default argument %qE uses local variable %qD", arg, var);
14712 return error_mark_node;
14715 /* All is well. */
14716 return arg;
14719 /* Returns a deprecated type used within TYPE, or NULL_TREE if none. */
14721 static tree
14722 type_is_deprecated (tree type)
14724 enum tree_code code;
14725 if (TREE_DEPRECATED (type))
14726 return type;
14727 if (TYPE_NAME (type))
14729 if (TREE_DEPRECATED (TYPE_NAME (type)))
14730 return type;
14731 else
14733 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
14734 return NULL_TREE;
14738 /* Do warn about using typedefs to a deprecated class. */
14739 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
14740 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
14742 code = TREE_CODE (type);
14744 if (code == POINTER_TYPE || code == REFERENCE_TYPE
14745 || code == OFFSET_TYPE || code == FUNCTION_TYPE
14746 || code == METHOD_TYPE || code == ARRAY_TYPE)
14747 return type_is_deprecated (TREE_TYPE (type));
14749 if (TYPE_PTRMEMFUNC_P (type))
14750 return type_is_deprecated
14751 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
14753 return NULL_TREE;
14756 /* Returns an unavailable type used within TYPE, or NULL_TREE if none. */
14758 static tree
14759 type_is_unavailable (tree type)
14761 enum tree_code code;
14762 if (TREE_UNAVAILABLE (type))
14763 return type;
14764 if (TYPE_NAME (type))
14766 if (TREE_UNAVAILABLE (TYPE_NAME (type)))
14767 return type;
14768 else
14770 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
14771 return NULL_TREE;
14775 /* Do warn about using typedefs to a deprecated class. */
14776 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
14777 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
14779 code = TREE_CODE (type);
14781 if (code == POINTER_TYPE || code == REFERENCE_TYPE
14782 || code == OFFSET_TYPE || code == FUNCTION_TYPE
14783 || code == METHOD_TYPE || code == ARRAY_TYPE)
14784 return type_is_unavailable (TREE_TYPE (type));
14786 if (TYPE_PTRMEMFUNC_P (type))
14787 return type_is_unavailable
14788 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
14790 return NULL_TREE;
14793 /* Decode the list of parameter types for a function type.
14794 Given the list of things declared inside the parens,
14795 return a list of types.
14797 If this parameter does not end with an ellipsis, we append
14798 void_list_node.
14800 *PARMS is set to the chain of PARM_DECLs created. */
14802 tree
14803 grokparms (tree parmlist, tree *parms)
14805 tree result = NULL_TREE;
14806 tree decls = NULL_TREE;
14807 tree parm;
14808 int any_error = 0;
14810 for (parm = parmlist; parm != NULL_TREE; parm = TREE_CHAIN (parm))
14812 tree type = NULL_TREE;
14813 tree init = TREE_PURPOSE (parm);
14814 tree decl = TREE_VALUE (parm);
14816 if (parm == void_list_node || parm == explicit_void_list_node)
14817 break;
14819 if (! decl || TREE_TYPE (decl) == error_mark_node)
14821 any_error = 1;
14822 continue;
14825 type = TREE_TYPE (decl);
14826 if (VOID_TYPE_P (type))
14828 if (same_type_p (type, void_type_node)
14829 && !init
14830 && !DECL_NAME (decl) && !result
14831 && TREE_CHAIN (parm) == void_list_node)
14832 /* DR 577: A parameter list consisting of a single
14833 unnamed parameter of non-dependent type 'void'. */
14834 break;
14835 else if (cv_qualified_p (type))
14836 error_at (DECL_SOURCE_LOCATION (decl),
14837 "invalid use of cv-qualified type %qT in "
14838 "parameter declaration", type);
14839 else
14840 error_at (DECL_SOURCE_LOCATION (decl),
14841 "invalid use of type %<void%> in parameter "
14842 "declaration");
14843 /* It's not a good idea to actually create parameters of
14844 type `void'; other parts of the compiler assume that a
14845 void type terminates the parameter list. */
14846 type = error_mark_node;
14847 TREE_TYPE (decl) = error_mark_node;
14850 if (type != error_mark_node)
14852 if (deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
14854 tree unavailtype = type_is_unavailable (type);
14855 if (unavailtype)
14856 cp_handle_deprecated_or_unavailable (unavailtype);
14858 if (deprecated_state != DEPRECATED_SUPPRESS
14859 && deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
14861 tree deptype = type_is_deprecated (type);
14862 if (deptype)
14863 cp_handle_deprecated_or_unavailable (deptype);
14866 /* [dcl.fct] "A parameter with volatile-qualified type is
14867 deprecated." */
14868 if (CP_TYPE_VOLATILE_P (type))
14869 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wvolatile,
14870 "%<volatile%>-qualified parameter is "
14871 "deprecated");
14873 /* Top-level qualifiers on the parameters are
14874 ignored for function types. */
14875 type = cp_build_qualified_type (type, 0);
14876 if (TREE_CODE (type) == METHOD_TYPE)
14878 error ("parameter %qD invalidly declared method type", decl);
14879 type = build_pointer_type (type);
14880 TREE_TYPE (decl) = type;
14882 else if (cxx_dialect < cxx17 && INDIRECT_TYPE_P (type))
14884 /* Before C++17 DR 393:
14885 [dcl.fct]/6, parameter types cannot contain pointers
14886 (references) to arrays of unknown bound. */
14887 tree t = TREE_TYPE (type);
14888 int ptr = TYPE_PTR_P (type);
14890 while (1)
14892 if (TYPE_PTR_P (t))
14893 ptr = 1;
14894 else if (TREE_CODE (t) != ARRAY_TYPE)
14895 break;
14896 else if (!TYPE_DOMAIN (t))
14897 break;
14898 t = TREE_TYPE (t);
14900 if (TREE_CODE (t) == ARRAY_TYPE)
14901 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
14903 ? G_("parameter %qD includes pointer to array of "
14904 "unknown bound %qT")
14905 : G_("parameter %qD includes reference to array of "
14906 "unknown bound %qT"),
14907 decl, t);
14910 if (init && !processing_template_decl)
14911 init = check_default_argument (decl, init, tf_warning_or_error);
14914 DECL_CHAIN (decl) = decls;
14915 decls = decl;
14916 result = tree_cons (init, type, result);
14918 decls = nreverse (decls);
14919 result = nreverse (result);
14920 if (parm)
14921 result = chainon (result, void_list_node);
14922 *parms = decls;
14923 if (any_error)
14924 result = NULL_TREE;
14926 if (any_error)
14927 /* We had parm errors, recover by giving the function (...) type. */
14928 result = NULL_TREE;
14930 return result;
14934 /* D is a constructor or overloaded `operator='.
14936 Let T be the class in which D is declared. Then, this function
14937 returns:
14939 -1 if D's is an ill-formed constructor or copy assignment operator
14940 whose first parameter is of type `T'.
14941 0 if D is not a copy constructor or copy assignment
14942 operator.
14943 1 if D is a copy constructor or copy assignment operator whose
14944 first parameter is a reference to non-const qualified T.
14945 2 if D is a copy constructor or copy assignment operator whose
14946 first parameter is a reference to const qualified T.
14948 This function can be used as a predicate. Positive values indicate
14949 a copy constructor and nonzero values indicate a copy assignment
14950 operator. */
14953 copy_fn_p (const_tree d)
14955 tree args;
14956 tree arg_type;
14957 int result = 1;
14959 gcc_assert (DECL_FUNCTION_MEMBER_P (d));
14961 if (TREE_CODE (d) == TEMPLATE_DECL
14962 || (DECL_TEMPLATE_INFO (d)
14963 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
14964 /* Instantiations of template member functions are never copy
14965 functions. Note that member functions of templated classes are
14966 represented as template functions internally, and we must
14967 accept those as copy functions. */
14968 return 0;
14970 if (!DECL_CONSTRUCTOR_P (d)
14971 && DECL_NAME (d) != assign_op_identifier)
14972 return 0;
14974 args = FUNCTION_FIRST_USER_PARMTYPE (d);
14975 if (!args)
14976 return 0;
14978 arg_type = TREE_VALUE (args);
14979 if (arg_type == error_mark_node)
14980 return 0;
14982 if (TYPE_MAIN_VARIANT (arg_type) == DECL_CONTEXT (d))
14984 /* Pass by value copy assignment operator. */
14985 result = -1;
14987 else if (TYPE_REF_P (arg_type)
14988 && !TYPE_REF_IS_RVALUE (arg_type)
14989 && TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)) == DECL_CONTEXT (d))
14991 if (CP_TYPE_CONST_P (TREE_TYPE (arg_type)))
14992 result = 2;
14994 else
14995 return 0;
14997 args = TREE_CHAIN (args);
14999 if (args && args != void_list_node && !TREE_PURPOSE (args))
15000 /* There are more non-optional args. */
15001 return 0;
15003 return result;
15006 /* D is a constructor or overloaded `operator='.
15008 Let T be the class in which D is declared. Then, this function
15009 returns true when D is a move constructor or move assignment
15010 operator, false otherwise. */
15012 bool
15013 move_fn_p (const_tree d)
15015 gcc_assert (DECL_FUNCTION_MEMBER_P (d));
15017 if (cxx_dialect == cxx98)
15018 /* There are no move constructors if we are in C++98 mode. */
15019 return false;
15021 if (TREE_CODE (d) == TEMPLATE_DECL
15022 || (DECL_TEMPLATE_INFO (d)
15023 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
15024 /* Instantiations of template member functions are never move
15025 functions. Note that member functions of templated classes are
15026 represented as template functions internally, and we must
15027 accept those as move functions. */
15028 return 0;
15030 return move_signature_fn_p (d);
15033 /* D is a constructor or overloaded `operator='.
15035 Then, this function returns true when D has the same signature as a move
15036 constructor or move assignment operator (because either it is such a
15037 ctor/op= or it is a template specialization with the same signature),
15038 false otherwise. */
15040 bool
15041 move_signature_fn_p (const_tree d)
15043 tree args;
15044 tree arg_type;
15045 bool result = false;
15047 if (!DECL_CONSTRUCTOR_P (d)
15048 && DECL_NAME (d) != assign_op_identifier)
15049 return 0;
15051 args = FUNCTION_FIRST_USER_PARMTYPE (d);
15052 if (!args)
15053 return 0;
15055 arg_type = TREE_VALUE (args);
15056 if (arg_type == error_mark_node)
15057 return 0;
15059 if (TYPE_REF_P (arg_type)
15060 && TYPE_REF_IS_RVALUE (arg_type)
15061 && same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)),
15062 DECL_CONTEXT (d)))
15063 result = true;
15065 args = TREE_CHAIN (args);
15067 if (args && args != void_list_node && !TREE_PURPOSE (args))
15068 /* There are more non-optional args. */
15069 return false;
15071 return result;
15074 /* Remember any special properties of member function DECL. */
15076 void
15077 grok_special_member_properties (tree decl)
15079 tree class_type;
15081 if (TREE_CODE (decl) == USING_DECL
15082 || !DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
15083 return;
15085 class_type = DECL_CONTEXT (decl);
15086 if (IDENTIFIER_CTOR_P (DECL_NAME (decl)))
15088 int ctor = copy_fn_p (decl);
15090 if (!DECL_ARTIFICIAL (decl))
15091 TYPE_HAS_USER_CONSTRUCTOR (class_type) = 1;
15093 if (ctor > 0)
15095 /* [class.copy]
15097 A non-template constructor for class X is a copy
15098 constructor if its first parameter is of type X&, const
15099 X&, volatile X& or const volatile X&, and either there
15100 are no other parameters or else all other parameters have
15101 default arguments. */
15102 TYPE_HAS_COPY_CTOR (class_type) = 1;
15103 if (ctor > 1)
15104 TYPE_HAS_CONST_COPY_CTOR (class_type) = 1;
15107 if (sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (decl)))
15108 TYPE_HAS_DEFAULT_CONSTRUCTOR (class_type) = 1;
15110 if (is_list_ctor (decl))
15111 TYPE_HAS_LIST_CTOR (class_type) = 1;
15113 if (maybe_constexpr_fn (decl)
15114 && !ctor && !move_fn_p (decl))
15115 TYPE_HAS_CONSTEXPR_CTOR (class_type) = 1;
15117 else if (DECL_NAME (decl) == assign_op_identifier)
15119 /* [class.copy]
15121 A non-template assignment operator for class X is a copy
15122 assignment operator if its parameter is of type X, X&, const
15123 X&, volatile X& or const volatile X&. */
15125 int assop = copy_fn_p (decl);
15127 if (assop)
15129 TYPE_HAS_COPY_ASSIGN (class_type) = 1;
15130 if (assop != 1)
15131 TYPE_HAS_CONST_COPY_ASSIGN (class_type) = 1;
15134 else if (IDENTIFIER_CONV_OP_P (DECL_NAME (decl)))
15135 TYPE_HAS_CONVERSION (class_type) = true;
15137 /* Destructors are handled in check_methods. */
15140 /* Check a constructor DECL has the correct form. Complains
15141 if the class has a constructor of the form X(X). */
15143 bool
15144 grok_ctor_properties (const_tree ctype, const_tree decl)
15146 int ctor_parm = copy_fn_p (decl);
15148 if (ctor_parm < 0)
15150 /* [class.copy]
15152 A declaration of a constructor for a class X is ill-formed if
15153 its first parameter is of type (optionally cv-qualified) X
15154 and either there are no other parameters or else all other
15155 parameters have default arguments.
15157 We *don't* complain about member template instantiations that
15158 have this form, though; they can occur as we try to decide
15159 what constructor to use during overload resolution. Since
15160 overload resolution will never prefer such a constructor to
15161 the non-template copy constructor (which is either explicitly
15162 or implicitly defined), there's no need to worry about their
15163 existence. Theoretically, they should never even be
15164 instantiated, but that's hard to forestall. */
15165 error_at (DECL_SOURCE_LOCATION (decl),
15166 "invalid constructor; you probably meant %<%T (const %T&)%>",
15167 ctype, ctype);
15168 return false;
15171 return true;
15174 /* DECL is a declaration for an overloaded or conversion operator. If
15175 COMPLAIN is true, errors are issued for invalid declarations. */
15177 bool
15178 grok_op_properties (tree decl, bool complain)
15180 tree argtypes = TYPE_ARG_TYPES (TREE_TYPE (decl));
15181 bool methodp = TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE;
15182 tree name = DECL_NAME (decl);
15183 location_t loc = DECL_SOURCE_LOCATION (decl);
15185 tree class_type = DECL_CONTEXT (decl);
15186 if (class_type && !CLASS_TYPE_P (class_type))
15187 class_type = NULL_TREE;
15189 tree_code operator_code;
15190 unsigned op_flags;
15191 if (IDENTIFIER_CONV_OP_P (name))
15193 /* Conversion operators are TYPE_EXPR for the purposes of this
15194 function. */
15195 operator_code = TYPE_EXPR;
15196 op_flags = OVL_OP_FLAG_UNARY;
15198 else
15200 const ovl_op_info_t *ovl_op = IDENTIFIER_OVL_OP_INFO (name);
15202 operator_code = ovl_op->tree_code;
15203 op_flags = ovl_op->flags;
15204 gcc_checking_assert (operator_code != ERROR_MARK);
15205 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
15208 if (op_flags & OVL_OP_FLAG_ALLOC)
15210 /* operator new and operator delete are quite special. */
15211 if (class_type)
15212 switch (op_flags)
15214 case OVL_OP_FLAG_ALLOC:
15215 TYPE_HAS_NEW_OPERATOR (class_type) = 1;
15216 break;
15218 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE:
15219 TYPE_GETS_DELETE (class_type) |= 1;
15220 break;
15222 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_VEC:
15223 TYPE_HAS_ARRAY_NEW_OPERATOR (class_type) = 1;
15224 break;
15226 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE | OVL_OP_FLAG_VEC:
15227 TYPE_GETS_DELETE (class_type) |= 2;
15228 break;
15230 default:
15231 gcc_unreachable ();
15234 /* [basic.std.dynamic.allocation]/1:
15236 A program is ill-formed if an allocation function is declared
15237 in a namespace scope other than global scope or declared
15238 static in global scope.
15240 The same also holds true for deallocation functions. */
15241 if (DECL_NAMESPACE_SCOPE_P (decl))
15243 if (CP_DECL_CONTEXT (decl) != global_namespace)
15245 error_at (loc, "%qD may not be declared within a namespace",
15246 decl);
15247 return false;
15250 if (!TREE_PUBLIC (decl))
15252 error_at (loc, "%qD may not be declared as static", decl);
15253 return false;
15257 if (op_flags & OVL_OP_FLAG_DELETE)
15259 DECL_SET_IS_OPERATOR_DELETE (decl, true);
15260 coerce_delete_type (decl, loc);
15262 else
15264 DECL_SET_IS_OPERATOR_NEW (decl, true);
15265 TREE_TYPE (decl) = coerce_new_type (TREE_TYPE (decl), loc);
15268 return true;
15271 /* An operator function must either be a non-static member function
15272 or have at least one parameter of a class, a reference to a class,
15273 an enumeration, or a reference to an enumeration. 13.4.0.6 */
15274 if (! methodp || DECL_STATIC_FUNCTION_P (decl))
15276 if (operator_code == TYPE_EXPR
15277 || operator_code == CALL_EXPR
15278 || operator_code == COMPONENT_REF
15279 || operator_code == ARRAY_REF
15280 || operator_code == NOP_EXPR)
15282 error_at (loc, "%qD must be a non-static member function", decl);
15283 return false;
15286 if (DECL_STATIC_FUNCTION_P (decl))
15288 error_at (loc, "%qD must be either a non-static member "
15289 "function or a non-member function", decl);
15290 return false;
15293 for (tree arg = argtypes; ; arg = TREE_CHAIN (arg))
15295 if (!arg || arg == void_list_node)
15297 if (complain)
15298 error_at(loc, "%qD must have an argument of class or "
15299 "enumerated type", decl);
15300 return false;
15303 tree type = non_reference (TREE_VALUE (arg));
15304 if (type == error_mark_node)
15305 return false;
15307 /* MAYBE_CLASS_TYPE_P, rather than CLASS_TYPE_P, is used
15308 because these checks are performed even on template
15309 functions. */
15310 if (MAYBE_CLASS_TYPE_P (type)
15311 || TREE_CODE (type) == ENUMERAL_TYPE)
15312 break;
15316 if (operator_code == CALL_EXPR)
15317 /* There are no further restrictions on the arguments to an overloaded
15318 "operator ()". */
15319 return true;
15321 if (operator_code == COND_EXPR)
15323 /* 13.4.0.3 */
15324 error_at (loc, "ISO C++ prohibits overloading %<operator ?:%>");
15325 return false;
15328 /* Count the number of arguments and check for ellipsis. */
15329 int arity = 0;
15330 for (tree arg = argtypes; arg != void_list_node; arg = TREE_CHAIN (arg))
15332 if (!arg)
15334 /* Variadic. */
15335 if (operator_code == ARRAY_REF && cxx_dialect >= cxx23)
15336 break;
15338 error_at (loc, "%qD must not have variable number of arguments",
15339 decl);
15340 return false;
15342 ++arity;
15345 /* Verify correct number of arguments. */
15346 switch (op_flags)
15348 case OVL_OP_FLAG_AMBIARY:
15349 if (arity == 1)
15351 /* We have a unary instance of an ambi-ary op. Remap to the
15352 unary one. */
15353 unsigned alt = ovl_op_alternate[ovl_op_mapping [operator_code]];
15354 const ovl_op_info_t *ovl_op = &ovl_op_info[false][alt];
15355 gcc_checking_assert (ovl_op->flags == OVL_OP_FLAG_UNARY);
15356 operator_code = ovl_op->tree_code;
15357 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
15359 else if (arity != 2)
15361 /* This was an ambiguous operator but is invalid. */
15362 error_at (loc,
15363 methodp
15364 ? G_("%qD must have either zero or one argument")
15365 : G_("%qD must have either one or two arguments"), decl);
15366 return false;
15368 else if ((operator_code == POSTINCREMENT_EXPR
15369 || operator_code == POSTDECREMENT_EXPR)
15370 && ! processing_template_decl
15371 /* x++ and x--'s second argument must be an int. */
15372 && ! same_type_p (TREE_VALUE (TREE_CHAIN (argtypes)),
15373 integer_type_node))
15375 error_at (loc,
15376 methodp
15377 ? G_("postfix %qD must have %<int%> as its argument")
15378 : G_("postfix %qD must have %<int%> as its second argument"),
15379 decl);
15380 return false;
15382 break;
15384 case OVL_OP_FLAG_UNARY:
15385 if (arity != 1)
15387 error_at (loc,
15388 methodp
15389 ? G_("%qD must have no arguments")
15390 : G_("%qD must have exactly one argument"), decl);
15391 return false;
15393 break;
15395 case OVL_OP_FLAG_BINARY:
15396 if (arity != 2)
15398 if (operator_code == ARRAY_REF && cxx_dialect >= cxx23)
15399 break;
15400 error_at (loc,
15401 methodp
15402 ? G_("%qD must have exactly one argument")
15403 : G_("%qD must have exactly two arguments"), decl);
15404 return false;
15406 break;
15408 default:
15409 gcc_unreachable ();
15412 /* There can be no default arguments. */
15413 for (tree arg = argtypes; arg && arg != void_list_node;
15414 arg = TREE_CHAIN (arg))
15415 if (TREE_PURPOSE (arg))
15417 TREE_PURPOSE (arg) = NULL_TREE;
15418 error_at (loc, "%qD cannot have default arguments", decl);
15419 return false;
15422 /* At this point the declaration is well-formed. It may not be
15423 sensible though. */
15425 /* Check member function warnings only on the in-class declaration.
15426 There's no point warning on an out-of-class definition. */
15427 if (class_type && class_type != current_class_type)
15428 return true;
15430 /* Warn about conversion operators that will never be used. */
15431 if (IDENTIFIER_CONV_OP_P (name)
15432 && ! DECL_TEMPLATE_INFO (decl)
15433 && warn_class_conversion)
15435 tree t = TREE_TYPE (name);
15436 int ref = TYPE_REF_P (t);
15438 if (ref)
15439 t = TYPE_MAIN_VARIANT (TREE_TYPE (t));
15441 if (VOID_TYPE_P (t))
15442 warning_at (loc, OPT_Wclass_conversion, "converting %qT to %<void%> "
15443 "will never use a type conversion operator", class_type);
15444 else if (class_type)
15446 if (same_type_ignoring_top_level_qualifiers_p (t, class_type))
15447 warning_at (loc, OPT_Wclass_conversion,
15449 ? G_("converting %qT to a reference to the same type "
15450 "will never use a type conversion operator")
15451 : G_("converting %qT to the same type "
15452 "will never use a type conversion operator"),
15453 class_type);
15454 /* Don't force t to be complete here. */
15455 else if (MAYBE_CLASS_TYPE_P (t)
15456 && COMPLETE_TYPE_P (t)
15457 && DERIVED_FROM_P (t, class_type))
15458 warning_at (loc, OPT_Wclass_conversion,
15460 ? G_("converting %qT to a reference to a base class "
15461 "%qT will never use a type conversion operator")
15462 : G_("converting %qT to a base class %qT "
15463 "will never use a type conversion operator"),
15464 class_type, t);
15468 if (!warn_ecpp)
15469 return true;
15471 /* Effective C++ rules below. */
15473 /* More Effective C++ rule 7. */
15474 if (operator_code == TRUTH_ANDIF_EXPR
15475 || operator_code == TRUTH_ORIF_EXPR
15476 || operator_code == COMPOUND_EXPR)
15477 warning_at (loc, OPT_Weffc__,
15478 "user-defined %qD always evaluates both arguments", decl);
15480 /* More Effective C++ rule 6. */
15481 if (operator_code == POSTINCREMENT_EXPR
15482 || operator_code == POSTDECREMENT_EXPR
15483 || operator_code == PREINCREMENT_EXPR
15484 || operator_code == PREDECREMENT_EXPR)
15486 tree arg = TREE_VALUE (argtypes);
15487 tree ret = TREE_TYPE (TREE_TYPE (decl));
15488 if (methodp || TYPE_REF_P (arg))
15489 arg = TREE_TYPE (arg);
15490 arg = TYPE_MAIN_VARIANT (arg);
15492 if (operator_code == PREINCREMENT_EXPR
15493 || operator_code == PREDECREMENT_EXPR)
15495 if (!TYPE_REF_P (ret)
15496 || !same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (ret)), arg))
15497 warning_at (loc, OPT_Weffc__, "prefix %qD should return %qT", decl,
15498 build_reference_type (arg));
15500 else
15502 if (!same_type_p (TYPE_MAIN_VARIANT (ret), arg))
15503 warning_at (loc, OPT_Weffc__,
15504 "postfix %qD should return %qT", decl, arg);
15508 /* Effective C++ rule 23. */
15509 if (!DECL_ASSIGNMENT_OPERATOR_P (decl)
15510 && (operator_code == PLUS_EXPR
15511 || operator_code == MINUS_EXPR
15512 || operator_code == TRUNC_DIV_EXPR
15513 || operator_code == MULT_EXPR
15514 || operator_code == TRUNC_MOD_EXPR)
15515 && TYPE_REF_P (TREE_TYPE (TREE_TYPE (decl))))
15516 warning_at (loc, OPT_Weffc__, "%qD should return by value", decl);
15518 return true;
15521 /* Return a string giving the keyword associate with CODE. */
15523 static const char *
15524 tag_name (enum tag_types code)
15526 switch (code)
15528 case record_type:
15529 return "struct";
15530 case class_type:
15531 return "class";
15532 case union_type:
15533 return "union";
15534 case enum_type:
15535 return "enum";
15536 case typename_type:
15537 return "typename";
15538 default:
15539 gcc_unreachable ();
15543 /* Name lookup in an elaborated-type-specifier (after the keyword
15544 indicated by TAG_CODE) has found the TYPE_DECL DECL. If the
15545 elaborated-type-specifier is invalid, issue a diagnostic and return
15546 error_mark_node; otherwise, return the *_TYPE to which it referred.
15547 If ALLOW_TEMPLATE_P is true, TYPE may be a class template. */
15549 tree
15550 check_elaborated_type_specifier (enum tag_types tag_code,
15551 tree decl,
15552 bool allow_template_p)
15554 tree type;
15556 /* In the case of:
15558 struct S { struct S *p; };
15560 name lookup will find the TYPE_DECL for the implicit "S::S"
15561 typedef. Adjust for that here. */
15562 if (DECL_SELF_REFERENCE_P (decl))
15563 decl = TYPE_NAME (TREE_TYPE (decl));
15565 type = TREE_TYPE (decl);
15567 /* Check TEMPLATE_TYPE_PARM first because DECL_IMPLICIT_TYPEDEF_P
15568 is false for this case as well. */
15569 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
15571 error ("using template type parameter %qT after %qs",
15572 type, tag_name (tag_code));
15573 return error_mark_node;
15575 /* Accept template template parameters. */
15576 else if (allow_template_p
15577 && (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
15578 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM))
15580 /* [dcl.type.elab]
15582 If the identifier resolves to a typedef-name or the
15583 simple-template-id resolves to an alias template
15584 specialization, the elaborated-type-specifier is ill-formed.
15586 In other words, the only legitimate declaration to use in the
15587 elaborated type specifier is the implicit typedef created when
15588 the type is declared. */
15589 else if (!DECL_IMPLICIT_TYPEDEF_P (decl)
15590 && !DECL_SELF_REFERENCE_P (decl)
15591 && tag_code != typename_type)
15593 if (alias_template_specialization_p (type, nt_opaque))
15594 error ("using alias template specialization %qT after %qs",
15595 type, tag_name (tag_code));
15596 else
15597 error ("using typedef-name %qD after %qs", decl, tag_name (tag_code));
15598 inform (DECL_SOURCE_LOCATION (decl),
15599 "%qD has a previous declaration here", decl);
15600 return error_mark_node;
15602 else if (TREE_CODE (type) != RECORD_TYPE
15603 && TREE_CODE (type) != UNION_TYPE
15604 && tag_code != enum_type
15605 && tag_code != typename_type)
15607 error ("%qT referred to as %qs", type, tag_name (tag_code));
15608 inform (location_of (type), "%qT has a previous declaration here", type);
15609 return error_mark_node;
15611 else if (TREE_CODE (type) != ENUMERAL_TYPE
15612 && tag_code == enum_type)
15614 error ("%qT referred to as enum", type);
15615 inform (location_of (type), "%qT has a previous declaration here", type);
15616 return error_mark_node;
15618 else if (!allow_template_p
15619 && TREE_CODE (type) == RECORD_TYPE
15620 && CLASSTYPE_IS_TEMPLATE (type))
15622 /* If a class template appears as elaborated type specifier
15623 without a template header such as:
15625 template <class T> class C {};
15626 void f(class C); // No template header here
15628 then the required template argument is missing. */
15629 error ("template argument required for %<%s %T%>",
15630 tag_name (tag_code),
15631 DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)));
15632 return error_mark_node;
15635 return type;
15638 /* Lookup NAME of an elaborated type specifier according to SCOPE and
15639 issue diagnostics if necessary. Return *_TYPE node upon success,
15640 NULL_TREE when the NAME is not found, and ERROR_MARK_NODE for type
15641 error. */
15643 static tree
15644 lookup_and_check_tag (enum tag_types tag_code, tree name,
15645 TAG_how how, bool template_header_p)
15647 tree decl;
15648 if (how == TAG_how::GLOBAL)
15650 /* First try ordinary name lookup, ignoring hidden class name
15651 injected via friend declaration. */
15652 decl = lookup_name (name, LOOK_want::TYPE);
15653 decl = strip_using_decl (decl);
15654 /* If that fails, the name will be placed in the smallest
15655 non-class, non-function-prototype scope according to 3.3.1/5.
15656 We may already have a hidden name declared as friend in this
15657 scope. So lookup again but not ignoring hidden names.
15658 If we find one, that name will be made visible rather than
15659 creating a new tag. */
15660 if (!decl)
15661 decl = lookup_elaborated_type (name, TAG_how::INNERMOST_NON_CLASS);
15663 else
15664 decl = lookup_elaborated_type (name, how);
15666 if (!decl)
15667 /* We found nothing. */
15668 return NULL_TREE;
15670 if (TREE_CODE (decl) == TREE_LIST)
15672 error ("reference to %qD is ambiguous", name);
15673 print_candidates (decl);
15674 return error_mark_node;
15677 if (DECL_CLASS_TEMPLATE_P (decl)
15678 && !template_header_p
15679 && how == TAG_how::CURRENT_ONLY)
15681 error ("class template %qD redeclared as non-template", name);
15682 inform (location_of (decl), "previous declaration here");
15683 CLASSTYPE_ERRONEOUS (TREE_TYPE (decl)) = true;
15684 return error_mark_node;
15687 if (DECL_CLASS_TEMPLATE_P (decl)
15688 /* If scope is TAG_how::CURRENT_ONLY we're defining a class,
15689 so ignore a template template parameter. */
15690 || (how != TAG_how::CURRENT_ONLY && DECL_TEMPLATE_TEMPLATE_PARM_P (decl)))
15691 decl = DECL_TEMPLATE_RESULT (decl);
15693 if (TREE_CODE (decl) != TYPE_DECL)
15694 /* Found not-a-type. */
15695 return NULL_TREE;
15697 /* Look for invalid nested type:
15698 class C {
15699 class C {};
15700 }; */
15701 if (how == TAG_how::CURRENT_ONLY && DECL_SELF_REFERENCE_P (decl))
15703 error ("%qD has the same name as the class in which it is "
15704 "declared", decl);
15705 return error_mark_node;
15708 /* Two cases we need to consider when deciding if a class
15709 template is allowed as an elaborated type specifier:
15710 1. It is a self reference to its own class.
15711 2. It comes with a template header.
15713 For example:
15715 template <class T> class C {
15716 class C *c1; // DECL_SELF_REFERENCE_P is true
15717 class D;
15719 template <class U> class C; // template_header_p is true
15720 template <class T> class C<T>::D {
15721 class C *c2; // DECL_SELF_REFERENCE_P is true
15722 }; */
15724 tree t = check_elaborated_type_specifier (tag_code, decl,
15725 template_header_p
15726 | DECL_SELF_REFERENCE_P (decl));
15727 if (template_header_p && t && CLASS_TYPE_P (t)
15728 && (!CLASSTYPE_TEMPLATE_INFO (t)
15729 || (!PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))))
15731 error ("%qT is not a template", t);
15732 inform (location_of (t), "previous declaration here");
15733 if (TYPE_CLASS_SCOPE_P (t)
15734 && CLASSTYPE_TEMPLATE_INFO (TYPE_CONTEXT (t)))
15735 inform (input_location,
15736 "perhaps you want to explicitly add %<%T::%>",
15737 TYPE_CONTEXT (t));
15738 return error_mark_node;
15741 return t;
15744 /* Get the struct, enum or union (TAG_CODE says which) with tag NAME.
15745 Define the tag as a forward-reference if it is not defined.
15747 If a declaration is given, process it here, and report an error if
15748 multiple declarations are not identical.
15750 SCOPE is TS_CURRENT when this is also a definition. Only look in
15751 the current frame for the name (since C++ allows new names in any
15752 scope.) It is TS_WITHIN_ENCLOSING_NON_CLASS if this is a friend
15753 declaration. Only look beginning from the current scope outward up
15754 till the nearest non-class scope. Otherwise it is TS_GLOBAL.
15756 TEMPLATE_HEADER_P is true when this declaration is preceded by
15757 a set of template parameters. */
15759 tree
15760 xref_tag (enum tag_types tag_code, tree name,
15761 TAG_how how, bool template_header_p)
15763 enum tree_code code;
15764 tree context = NULL_TREE;
15766 auto_cond_timevar tv (TV_NAME_LOOKUP);
15768 gcc_assert (identifier_p (name));
15770 switch (tag_code)
15772 case record_type:
15773 case class_type:
15774 code = RECORD_TYPE;
15775 break;
15776 case union_type:
15777 code = UNION_TYPE;
15778 break;
15779 case enum_type:
15780 code = ENUMERAL_TYPE;
15781 break;
15782 default:
15783 gcc_unreachable ();
15786 /* In case of anonymous name, xref_tag is only called to
15787 make type node and push name. Name lookup is not required. */
15788 tree t = NULL_TREE;
15789 if (!IDENTIFIER_ANON_P (name))
15790 t = lookup_and_check_tag (tag_code, name, how, template_header_p);
15792 if (t == error_mark_node)
15793 return error_mark_node;
15795 if (how != TAG_how::CURRENT_ONLY && t && current_class_type
15796 && template_class_depth (current_class_type)
15797 && template_header_p)
15799 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
15800 return t;
15802 /* Since HOW is not TAG_how::CURRENT_ONLY, we are not looking at
15803 a definition of this tag. Since, in addition, we are
15804 currently processing a (member) template declaration of a
15805 template class, we must be very careful; consider:
15807 template <class X> struct S1
15809 template <class U> struct S2
15811 template <class V> friend struct S1;
15814 Here, the S2::S1 declaration should not be confused with the
15815 outer declaration. In particular, the inner version should
15816 have a template parameter of level 2, not level 1.
15818 On the other hand, when presented with:
15820 template <class T> struct S1
15822 template <class U> struct S2 {};
15823 template <class U> friend struct S2;
15826 the friend must find S1::S2 eventually. We accomplish this
15827 by making sure that the new type we create to represent this
15828 declaration has the right TYPE_CONTEXT. */
15829 context = TYPE_CONTEXT (t);
15830 t = NULL_TREE;
15833 if (! t)
15835 /* If no such tag is yet defined, create a forward-reference node
15836 and record it as the "definition".
15837 When a real declaration of this type is found,
15838 the forward-reference will be altered into a real type. */
15839 if (code == ENUMERAL_TYPE)
15841 error ("use of enum %q#D without previous declaration", name);
15842 return error_mark_node;
15845 t = make_class_type (code);
15846 TYPE_CONTEXT (t) = context;
15847 if (IDENTIFIER_LAMBDA_P (name))
15848 /* Mark it as a lambda type right now. Our caller will
15849 correct the value. */
15850 CLASSTYPE_LAMBDA_EXPR (t) = error_mark_node;
15851 t = pushtag (name, t, how);
15853 else
15855 if (template_header_p && MAYBE_CLASS_TYPE_P (t))
15857 /* Check that we aren't trying to overload a class with different
15858 constraints. */
15859 if (!redeclare_class_template (t, current_template_parms,
15860 current_template_constraints ()))
15861 return error_mark_node;
15863 else if (!processing_template_decl
15864 && CLASS_TYPE_P (t)
15865 && CLASSTYPE_IS_TEMPLATE (t))
15867 error ("redeclaration of %qT as a non-template", t);
15868 inform (location_of (t), "previous declaration %qD", t);
15869 return error_mark_node;
15872 if (modules_p ()
15873 && how == TAG_how::CURRENT_ONLY)
15875 tree decl = TYPE_NAME (t);
15876 if (!module_may_redeclare (decl))
15878 error ("cannot declare %qD in a different module", decl);
15879 inform (DECL_SOURCE_LOCATION (decl), "declared here");
15880 return error_mark_node;
15883 tree maybe_tmpl = decl;
15884 if (CLASS_TYPE_P (t) && CLASSTYPE_IS_TEMPLATE (t))
15885 maybe_tmpl = CLASSTYPE_TI_TEMPLATE (t);
15887 if (DECL_LANG_SPECIFIC (decl)
15888 && DECL_MODULE_IMPORT_P (decl)
15889 && TREE_CODE (CP_DECL_CONTEXT (decl)) == NAMESPACE_DECL)
15891 /* Push it into this TU's symbol slot. */
15892 gcc_checking_assert (current_namespace == CP_DECL_CONTEXT (decl));
15893 if (maybe_tmpl != decl)
15894 /* We're in the template parm binding level.
15895 Pushtag has logic to slide under that, but we're
15896 not pushing a *new* type. */
15897 push_nested_namespace (CP_DECL_CONTEXT (decl));
15899 pushdecl (maybe_tmpl);
15900 if (maybe_tmpl != decl)
15901 pop_nested_namespace (CP_DECL_CONTEXT (decl));
15904 set_instantiating_module (maybe_tmpl);
15908 return t;
15911 /* Create the binfo hierarchy for REF with (possibly NULL) base list
15912 BASE_LIST. For each element on BASE_LIST the TREE_PURPOSE is an
15913 access_* node, and the TREE_VALUE is the type of the base-class.
15914 Non-NULL TREE_TYPE indicates virtual inheritance. */
15916 void
15917 xref_basetypes (tree ref, tree base_list)
15919 tree *basep;
15920 tree binfo, base_binfo;
15921 unsigned max_vbases = 0; /* Maximum direct & indirect virtual bases. */
15922 unsigned max_bases = 0; /* Maximum direct bases. */
15923 unsigned max_dvbases = 0; /* Maximum direct virtual bases. */
15924 int i;
15925 tree default_access;
15926 tree igo_prev; /* Track Inheritance Graph Order. */
15928 if (ref == error_mark_node)
15929 return;
15931 /* The base of a derived class is private by default, all others are
15932 public. */
15933 default_access = (TREE_CODE (ref) == RECORD_TYPE
15934 && CLASSTYPE_DECLARED_CLASS (ref)
15935 ? access_private_node : access_public_node);
15937 /* First, make sure that any templates in base-classes are
15938 instantiated. This ensures that if we call ourselves recursively
15939 we do not get confused about which classes are marked and which
15940 are not. */
15941 basep = &base_list;
15942 while (*basep)
15944 tree basetype = TREE_VALUE (*basep);
15946 /* The dependent_type_p call below should really be dependent_scope_p
15947 so that we give a hard error about using an incomplete type as a
15948 base, but we allow it with a pedwarn for backward
15949 compatibility. */
15950 if (processing_template_decl
15951 && CLASS_TYPE_P (basetype) && TYPE_BEING_DEFINED (basetype))
15952 cxx_incomplete_type_diagnostic (NULL_TREE, basetype, DK_PEDWARN);
15953 if (!dependent_type_p (basetype)
15954 && !complete_type_or_else (basetype, NULL))
15955 /* An incomplete type. Remove it from the list. */
15956 *basep = TREE_CHAIN (*basep);
15957 else
15959 max_bases++;
15960 if (TREE_TYPE (*basep))
15961 max_dvbases++;
15962 if (CLASS_TYPE_P (basetype))
15963 max_vbases += vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
15964 basep = &TREE_CHAIN (*basep);
15967 max_vbases += max_dvbases;
15969 TYPE_MARKED_P (ref) = 1;
15971 /* The binfo slot should be empty, unless this is an (ill-formed)
15972 redefinition. */
15973 gcc_assert (!TYPE_BINFO (ref) || TYPE_SIZE (ref));
15975 gcc_assert (TYPE_MAIN_VARIANT (ref) == ref);
15977 binfo = make_tree_binfo (max_bases);
15979 TYPE_BINFO (ref) = binfo;
15980 BINFO_OFFSET (binfo) = size_zero_node;
15981 BINFO_TYPE (binfo) = ref;
15983 /* Apply base-class info set up to the variants of this type. */
15984 fixup_type_variants (ref);
15986 if (max_bases)
15988 vec_alloc (BINFO_BASE_ACCESSES (binfo), max_bases);
15989 /* A C++98 POD cannot have base classes. */
15990 CLASSTYPE_NON_LAYOUT_POD_P (ref) = true;
15992 if (TREE_CODE (ref) == UNION_TYPE)
15994 error ("derived union %qT invalid", ref);
15995 return;
15999 if (max_bases > 1)
16000 warning (OPT_Wmultiple_inheritance,
16001 "%qT defined with multiple direct bases", ref);
16003 if (max_vbases)
16005 /* An aggregate can't have virtual base classes. */
16006 CLASSTYPE_NON_AGGREGATE (ref) = true;
16008 vec_alloc (CLASSTYPE_VBASECLASSES (ref), max_vbases);
16010 if (max_dvbases)
16011 warning (OPT_Wvirtual_inheritance,
16012 "%qT defined with direct virtual base", ref);
16015 for (igo_prev = binfo; base_list; base_list = TREE_CHAIN (base_list))
16017 tree access = TREE_PURPOSE (base_list);
16018 int via_virtual = TREE_TYPE (base_list) != NULL_TREE;
16019 tree basetype = TREE_VALUE (base_list);
16021 if (access == access_default_node)
16022 access = default_access;
16024 /* Before C++17, an aggregate cannot have base classes. In C++17, an
16025 aggregate can't have virtual, private, or protected base classes. */
16026 if (cxx_dialect < cxx17
16027 || access != access_public_node
16028 || via_virtual)
16029 CLASSTYPE_NON_AGGREGATE (ref) = true;
16031 if (PACK_EXPANSION_P (basetype))
16032 basetype = PACK_EXPANSION_PATTERN (basetype);
16033 if (TREE_CODE (basetype) == TYPE_DECL)
16034 basetype = TREE_TYPE (basetype);
16035 if (!MAYBE_CLASS_TYPE_P (basetype) || TREE_CODE (basetype) == UNION_TYPE)
16037 error ("base type %qT fails to be a struct or class type",
16038 basetype);
16039 goto dropped_base;
16042 base_binfo = NULL_TREE;
16043 if (CLASS_TYPE_P (basetype) && !dependent_scope_p (basetype))
16045 base_binfo = TYPE_BINFO (basetype);
16046 /* The original basetype could have been a typedef'd type. */
16047 basetype = BINFO_TYPE (base_binfo);
16049 /* Inherit flags from the base. */
16050 TYPE_HAS_NEW_OPERATOR (ref)
16051 |= TYPE_HAS_NEW_OPERATOR (basetype);
16052 TYPE_HAS_ARRAY_NEW_OPERATOR (ref)
16053 |= TYPE_HAS_ARRAY_NEW_OPERATOR (basetype);
16054 TYPE_GETS_DELETE (ref) |= TYPE_GETS_DELETE (basetype);
16055 TYPE_HAS_CONVERSION (ref) |= TYPE_HAS_CONVERSION (basetype);
16056 CLASSTYPE_DIAMOND_SHAPED_P (ref)
16057 |= CLASSTYPE_DIAMOND_SHAPED_P (basetype);
16058 CLASSTYPE_REPEATED_BASE_P (ref)
16059 |= CLASSTYPE_REPEATED_BASE_P (basetype);
16062 /* We must do this test after we've seen through a typedef
16063 type. */
16064 if (TYPE_MARKED_P (basetype))
16066 if (basetype == ref)
16067 error ("recursive type %qT undefined", basetype);
16068 else
16069 error ("duplicate base type %qT invalid", basetype);
16070 goto dropped_base;
16073 if (PACK_EXPANSION_P (TREE_VALUE (base_list)))
16074 /* Regenerate the pack expansion for the bases. */
16075 basetype = make_pack_expansion (basetype);
16077 TYPE_MARKED_P (basetype) = 1;
16079 base_binfo = copy_binfo (base_binfo, basetype, ref,
16080 &igo_prev, via_virtual);
16081 if (!BINFO_INHERITANCE_CHAIN (base_binfo))
16082 BINFO_INHERITANCE_CHAIN (base_binfo) = binfo;
16084 BINFO_BASE_APPEND (binfo, base_binfo);
16085 BINFO_BASE_ACCESS_APPEND (binfo, access);
16086 continue;
16088 dropped_base:
16089 /* Update max_vbases to reflect the reality that we are dropping
16090 this base: if it reaches zero we want to undo the vec_alloc
16091 above to avoid inconsistencies during error-recovery: eg, in
16092 build_special_member_call, CLASSTYPE_VBASECLASSES non null
16093 and vtt null (c++/27952). */
16094 if (via_virtual)
16095 max_vbases--;
16096 if (CLASS_TYPE_P (basetype))
16097 max_vbases
16098 -= vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
16101 if (CLASSTYPE_VBASECLASSES (ref)
16102 && max_vbases == 0)
16103 vec_free (CLASSTYPE_VBASECLASSES (ref));
16105 if (vec_safe_length (CLASSTYPE_VBASECLASSES (ref)) < max_vbases)
16106 /* If we didn't get max_vbases vbases, we must have shared at
16107 least one of them, and are therefore diamond shaped. */
16108 CLASSTYPE_DIAMOND_SHAPED_P (ref) = 1;
16110 /* Unmark all the types. */
16111 for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
16112 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
16113 TYPE_MARKED_P (ref) = 0;
16115 /* Now see if we have a repeated base type. */
16116 if (!CLASSTYPE_REPEATED_BASE_P (ref))
16118 for (base_binfo = binfo; base_binfo;
16119 base_binfo = TREE_CHAIN (base_binfo))
16121 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
16123 CLASSTYPE_REPEATED_BASE_P (ref) = 1;
16124 break;
16126 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 1;
16128 for (base_binfo = binfo; base_binfo;
16129 base_binfo = TREE_CHAIN (base_binfo))
16130 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
16131 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
16132 else
16133 break;
16138 /* Copies the enum-related properties from type SRC to type DST.
16139 Used with the underlying type of an enum and the enum itself. */
16140 static void
16141 copy_type_enum (tree dst, tree src)
16143 tree t;
16144 for (t = dst; t; t = TYPE_NEXT_VARIANT (t))
16146 TYPE_MIN_VALUE (t) = TYPE_MIN_VALUE (src);
16147 TYPE_MAX_VALUE (t) = TYPE_MAX_VALUE (src);
16148 TYPE_SIZE (t) = TYPE_SIZE (src);
16149 TYPE_SIZE_UNIT (t) = TYPE_SIZE_UNIT (src);
16150 SET_TYPE_MODE (dst, TYPE_MODE (src));
16151 TYPE_PRECISION (t) = TYPE_PRECISION (src);
16152 unsigned valign = TYPE_ALIGN (src);
16153 if (TYPE_USER_ALIGN (t))
16154 valign = MAX (valign, TYPE_ALIGN (t));
16155 else
16156 TYPE_USER_ALIGN (t) = TYPE_USER_ALIGN (src);
16157 SET_TYPE_ALIGN (t, valign);
16158 TYPE_UNSIGNED (t) = TYPE_UNSIGNED (src);
16162 /* Begin compiling the definition of an enumeration type.
16163 NAME is its name,
16165 if ENUMTYPE is not NULL_TREE then the type has alredy been found.
16167 UNDERLYING_TYPE is the type that will be used as the storage for
16168 the enumeration type. This should be NULL_TREE if no storage type
16169 was specified.
16171 ATTRIBUTES are any attributes specified after the enum-key.
16173 SCOPED_ENUM_P is true if this is a scoped enumeration type.
16175 if IS_NEW is not NULL, gets TRUE iff a new type is created.
16177 Returns the type object, as yet incomplete.
16178 Also records info about it so that build_enumerator
16179 may be used to declare the individual values as they are read. */
16181 tree
16182 start_enum (tree name, tree enumtype, tree underlying_type,
16183 tree attributes, bool scoped_enum_p, bool *is_new)
16185 tree prevtype = NULL_TREE;
16186 gcc_assert (identifier_p (name));
16188 if (is_new)
16189 *is_new = false;
16190 /* [C++0x dcl.enum]p5:
16192 If not explicitly specified, the underlying type of a scoped
16193 enumeration type is int. */
16194 if (!underlying_type && scoped_enum_p)
16195 underlying_type = integer_type_node;
16197 if (underlying_type)
16198 underlying_type = cv_unqualified (underlying_type);
16200 /* If this is the real definition for a previous forward reference,
16201 fill in the contents in the same object that used to be the
16202 forward reference. */
16203 if (!enumtype)
16204 enumtype = lookup_and_check_tag (enum_type, name,
16205 /*tag_scope=*/TAG_how::CURRENT_ONLY,
16206 /*template_header_p=*/false);
16208 /* In case of a template_decl, the only check that should be deferred
16209 to instantiation time is the comparison of underlying types. */
16210 if (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE)
16212 if (scoped_enum_p != SCOPED_ENUM_P (enumtype))
16214 error_at (input_location, "scoped/unscoped mismatch "
16215 "in enum %q#T", enumtype);
16216 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16217 "previous definition here");
16218 enumtype = error_mark_node;
16220 else if (ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) != !! underlying_type)
16222 error_at (input_location, "underlying type mismatch "
16223 "in enum %q#T", enumtype);
16224 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16225 "previous definition here");
16226 enumtype = error_mark_node;
16228 else if (underlying_type && ENUM_UNDERLYING_TYPE (enumtype)
16229 && !same_type_p (underlying_type,
16230 ENUM_UNDERLYING_TYPE (enumtype)))
16232 error_at (input_location, "different underlying type "
16233 "in enum %q#T", enumtype);
16234 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16235 "previous definition here");
16236 underlying_type = NULL_TREE;
16239 if (modules_p ())
16241 if (!module_may_redeclare (TYPE_NAME (enumtype)))
16243 error ("cannot define %qD in different module",
16244 TYPE_NAME (enumtype));
16245 inform (DECL_SOURCE_LOCATION (TYPE_NAME (enumtype)),
16246 "declared here");
16247 enumtype = error_mark_node;
16249 set_instantiating_module (TYPE_NAME (enumtype));
16253 if (!enumtype || TREE_CODE (enumtype) != ENUMERAL_TYPE
16254 || processing_template_decl)
16256 /* In case of error, make a dummy enum to allow parsing to
16257 continue. */
16258 if (enumtype == error_mark_node)
16260 name = make_anon_name ();
16261 enumtype = NULL_TREE;
16264 /* enumtype may be an ENUMERAL_TYPE if this is a redefinition
16265 of an opaque enum, or an opaque enum of an already defined
16266 enumeration (C++11).
16267 In any other case, it'll be NULL_TREE. */
16268 if (!enumtype)
16270 if (is_new)
16271 *is_new = true;
16273 prevtype = enumtype;
16275 /* Do not push the decl more than once. */
16276 if (!enumtype
16277 || TREE_CODE (enumtype) != ENUMERAL_TYPE)
16279 enumtype = cxx_make_type (ENUMERAL_TYPE);
16280 enumtype = pushtag (name, enumtype);
16282 /* std::byte aliases anything. */
16283 if (enumtype != error_mark_node
16284 && TYPE_CONTEXT (enumtype) == std_node
16285 && !strcmp ("byte", TYPE_NAME_STRING (enumtype)))
16286 TYPE_ALIAS_SET (enumtype) = 0;
16288 else
16289 enumtype = xref_tag (enum_type, name);
16291 if (enumtype == error_mark_node)
16292 return error_mark_node;
16294 /* The enum is considered opaque until the opening '{' of the
16295 enumerator list. */
16296 SET_OPAQUE_ENUM_P (enumtype, true);
16297 ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) = !! underlying_type;
16300 SET_SCOPED_ENUM_P (enumtype, scoped_enum_p);
16302 cplus_decl_attributes (&enumtype, attributes, (int)ATTR_FLAG_TYPE_IN_PLACE);
16304 if (underlying_type)
16306 if (ENUM_UNDERLYING_TYPE (enumtype))
16307 /* We already checked that it matches, don't change it to a different
16308 typedef variant. */;
16309 else if (CP_INTEGRAL_TYPE_P (underlying_type))
16311 copy_type_enum (enumtype, underlying_type);
16312 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
16314 else if (dependent_type_p (underlying_type))
16315 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
16316 else
16317 error ("underlying type %qT of %qT must be an integral type",
16318 underlying_type, enumtype);
16321 /* If into a template class, the returned enum is always the first
16322 declaration (opaque or not) seen. This way all the references to
16323 this type will be to the same declaration. The following ones are used
16324 only to check for definition errors. */
16325 if (prevtype && processing_template_decl)
16326 return prevtype;
16327 else
16328 return enumtype;
16331 /* After processing and defining all the values of an enumeration type,
16332 install their decls in the enumeration type.
16333 ENUMTYPE is the type object. */
16335 void
16336 finish_enum_value_list (tree enumtype)
16338 tree values;
16339 tree underlying_type;
16340 tree decl;
16341 tree value;
16342 tree minnode, maxnode;
16343 tree t;
16345 bool fixed_underlying_type_p
16346 = ENUM_UNDERLYING_TYPE (enumtype) != NULL_TREE;
16348 /* We built up the VALUES in reverse order. */
16349 TYPE_VALUES (enumtype) = nreverse (TYPE_VALUES (enumtype));
16351 /* For an enum defined in a template, just set the type of the values;
16352 all further processing is postponed until the template is
16353 instantiated. We need to set the type so that tsubst of a CONST_DECL
16354 works. */
16355 if (processing_template_decl)
16357 for (values = TYPE_VALUES (enumtype);
16358 values;
16359 values = TREE_CHAIN (values))
16360 TREE_TYPE (TREE_VALUE (values)) = enumtype;
16361 return;
16364 /* Determine the minimum and maximum values of the enumerators. */
16365 if (TYPE_VALUES (enumtype))
16367 minnode = maxnode = NULL_TREE;
16369 for (values = TYPE_VALUES (enumtype);
16370 values;
16371 values = TREE_CHAIN (values))
16373 decl = TREE_VALUE (values);
16375 /* [dcl.enum]: Following the closing brace of an enum-specifier,
16376 each enumerator has the type of its enumeration. Prior to the
16377 closing brace, the type of each enumerator is the type of its
16378 initializing value. */
16379 TREE_TYPE (decl) = enumtype;
16381 /* Update the minimum and maximum values, if appropriate. */
16382 value = DECL_INITIAL (decl);
16383 if (TREE_CODE (value) != INTEGER_CST)
16384 value = integer_zero_node;
16385 /* Figure out what the minimum and maximum values of the
16386 enumerators are. */
16387 if (!minnode)
16388 minnode = maxnode = value;
16389 else if (tree_int_cst_lt (maxnode, value))
16390 maxnode = value;
16391 else if (tree_int_cst_lt (value, minnode))
16392 minnode = value;
16395 else
16396 /* [dcl.enum]
16398 If the enumerator-list is empty, the underlying type is as if
16399 the enumeration had a single enumerator with value 0. */
16400 minnode = maxnode = integer_zero_node;
16402 if (!fixed_underlying_type_p)
16404 /* Compute the number of bits require to represent all values of the
16405 enumeration. We must do this before the type of MINNODE and
16406 MAXNODE are transformed, since tree_int_cst_min_precision relies
16407 on the TREE_TYPE of the value it is passed. */
16408 signop sgn = tree_int_cst_sgn (minnode) >= 0 ? UNSIGNED : SIGNED;
16409 int lowprec = tree_int_cst_min_precision (minnode, sgn);
16410 int highprec = tree_int_cst_min_precision (maxnode, sgn);
16411 int precision = MAX (lowprec, highprec);
16412 unsigned int itk;
16413 bool use_short_enum;
16415 /* Determine the underlying type of the enumeration.
16417 [dcl.enum]
16419 The underlying type of an enumeration is an integral type that
16420 can represent all the enumerator values defined in the
16421 enumeration. It is implementation-defined which integral type is
16422 used as the underlying type for an enumeration except that the
16423 underlying type shall not be larger than int unless the value of
16424 an enumerator cannot fit in an int or unsigned int.
16426 We use "int" or an "unsigned int" as the underlying type, even if
16427 a smaller integral type would work, unless the user has
16428 explicitly requested that we use the smallest possible type. The
16429 user can request that for all enumerations with a command line
16430 flag, or for just one enumeration with an attribute. */
16432 use_short_enum = flag_short_enums
16433 || lookup_attribute ("packed", TYPE_ATTRIBUTES (enumtype));
16435 /* If the precision of the type was specified with an attribute and it
16436 was too small, give an error. Otherwise, use it. */
16437 if (TYPE_PRECISION (enumtype))
16439 if (precision > TYPE_PRECISION (enumtype))
16440 error ("specified mode too small for enumerated values");
16441 else
16443 use_short_enum = true;
16444 precision = TYPE_PRECISION (enumtype);
16448 for (itk = (use_short_enum ? itk_char : itk_int);
16449 itk != itk_none;
16450 itk++)
16452 underlying_type = integer_types[itk];
16453 if (underlying_type != NULL_TREE
16454 && TYPE_PRECISION (underlying_type) >= precision
16455 && TYPE_SIGN (underlying_type) == sgn)
16456 break;
16458 if (itk == itk_none)
16460 /* DR 377
16462 IF no integral type can represent all the enumerator values, the
16463 enumeration is ill-formed. */
16464 error ("no integral type can represent all of the enumerator values "
16465 "for %qT", enumtype);
16466 precision = TYPE_PRECISION (long_long_integer_type_node);
16467 underlying_type = integer_types[itk_unsigned_long_long];
16470 /* [dcl.enum]
16472 The value of sizeof() applied to an enumeration type, an object
16473 of an enumeration type, or an enumerator, is the value of sizeof()
16474 applied to the underlying type. */
16475 copy_type_enum (enumtype, underlying_type);
16477 /* Compute the minimum and maximum values for the type.
16479 [dcl.enum]
16481 For an enumeration where emin is the smallest enumerator and emax
16482 is the largest, the values of the enumeration are the values of the
16483 underlying type in the range bmin to bmax, where bmin and bmax are,
16484 respectively, the smallest and largest values of the smallest bit-
16485 field that can store emin and emax. */
16487 /* The middle-end currently assumes that types with TYPE_PRECISION
16488 narrower than their underlying type are suitably zero or sign
16489 extended to fill their mode. Similarly, it assumes that the front
16490 end assures that a value of a particular type must be within
16491 TYPE_MIN_VALUE and TYPE_MAX_VALUE.
16493 We used to set these fields based on bmin and bmax, but that led
16494 to invalid assumptions like optimizing away bounds checking. So
16495 now we just set the TYPE_PRECISION, TYPE_MIN_VALUE, and
16496 TYPE_MAX_VALUE to the values for the mode above and only restrict
16497 the ENUM_UNDERLYING_TYPE for the benefit of diagnostics. */
16498 ENUM_UNDERLYING_TYPE (enumtype)
16499 = build_distinct_type_copy (underlying_type);
16500 TYPE_PRECISION (ENUM_UNDERLYING_TYPE (enumtype)) = precision;
16501 set_min_and_max_values_for_integral_type
16502 (ENUM_UNDERLYING_TYPE (enumtype), precision, sgn);
16504 /* If -fstrict-enums, still constrain TYPE_MIN/MAX_VALUE. */
16505 if (flag_strict_enums)
16506 set_min_and_max_values_for_integral_type (enumtype, precision, sgn);
16508 else
16509 underlying_type = ENUM_UNDERLYING_TYPE (enumtype);
16511 /* If the enum is exported, mark the consts too. */
16512 bool export_p = (UNSCOPED_ENUM_P (enumtype)
16513 && DECL_MODULE_EXPORT_P (TYPE_STUB_DECL (enumtype))
16514 && at_namespace_scope_p ());
16516 /* Convert each of the enumerators to the type of the underlying
16517 type of the enumeration. */
16518 for (values = TYPE_VALUES (enumtype); values; values = TREE_CHAIN (values))
16520 decl = TREE_VALUE (values);
16521 iloc_sentinel ils (DECL_SOURCE_LOCATION (decl));
16522 if (fixed_underlying_type_p)
16523 /* If the enumeration type has a fixed underlying type, we
16524 already checked all of the enumerator values. */
16525 value = DECL_INITIAL (decl);
16526 else
16527 value = perform_implicit_conversion (underlying_type,
16528 DECL_INITIAL (decl),
16529 tf_warning_or_error);
16530 /* Do not clobber shared ints. */
16531 if (value != error_mark_node)
16533 value = copy_node (value);
16535 TREE_TYPE (value) = enumtype;
16537 DECL_INITIAL (decl) = value;
16538 if (export_p)
16539 DECL_MODULE_EXPORT_P (decl) = true;
16542 /* Fix up all variant types of this enum type. */
16543 for (t = TYPE_MAIN_VARIANT (enumtype); t; t = TYPE_NEXT_VARIANT (t))
16544 TYPE_VALUES (t) = TYPE_VALUES (enumtype);
16546 if (at_class_scope_p ()
16547 && COMPLETE_TYPE_P (current_class_type)
16548 && UNSCOPED_ENUM_P (enumtype))
16550 insert_late_enum_def_bindings (current_class_type, enumtype);
16551 /* TYPE_FIELDS needs fixup. */
16552 fixup_type_variants (current_class_type);
16555 /* Finish debugging output for this type. */
16556 rest_of_type_compilation (enumtype, namespace_bindings_p ());
16558 /* Each enumerator now has the type of its enumeration. Clear the cache
16559 so that this change in types doesn't confuse us later on. */
16560 clear_cv_and_fold_caches ();
16563 /* Finishes the enum type. This is called only the first time an
16564 enumeration is seen, be it opaque or odinary.
16565 ENUMTYPE is the type object. */
16567 void
16568 finish_enum (tree enumtype)
16570 if (processing_template_decl)
16572 if (at_function_scope_p ())
16573 add_stmt (build_min (TAG_DEFN, enumtype));
16574 return;
16577 /* If this is a forward declaration, there should not be any variants,
16578 though we can get a variant in the middle of an enum-specifier with
16579 wacky code like 'enum E { e = sizeof(const E*) };' */
16580 gcc_assert (enumtype == TYPE_MAIN_VARIANT (enumtype)
16581 && (TYPE_VALUES (enumtype)
16582 || !TYPE_NEXT_VARIANT (enumtype)));
16585 /* Build and install a CONST_DECL for an enumeration constant of the
16586 enumeration type ENUMTYPE whose NAME and VALUE (if any) are provided.
16587 Apply ATTRIBUTES if available. LOC is the location of NAME.
16588 Assignment of sequential values by default is handled here. */
16590 tree
16591 build_enumerator (tree name, tree value, tree enumtype, tree attributes,
16592 location_t loc)
16594 tree decl;
16595 tree context;
16596 tree type;
16598 /* scalar_constant_value will pull out this expression, so make sure
16599 it's folded as appropriate. */
16600 if (processing_template_decl)
16601 value = fold_non_dependent_expr (value);
16603 /* If the VALUE was erroneous, pretend it wasn't there; that will
16604 result in the enum being assigned the next value in sequence. */
16605 if (value == error_mark_node)
16606 value = NULL_TREE;
16608 /* Remove no-op casts from the value. */
16609 if (value)
16610 STRIP_TYPE_NOPS (value);
16612 if (! processing_template_decl)
16614 /* Validate and default VALUE. */
16615 if (value != NULL_TREE)
16617 if (!ENUM_UNDERLYING_TYPE (enumtype))
16619 tree tmp_value = build_expr_type_conversion (WANT_INT | WANT_ENUM,
16620 value, true);
16621 if (tmp_value)
16622 value = tmp_value;
16624 else if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
16625 (TREE_TYPE (value)))
16626 value = perform_implicit_conversion_flags
16627 (ENUM_UNDERLYING_TYPE (enumtype), value, tf_warning_or_error,
16628 LOOKUP_IMPLICIT | LOOKUP_NO_NARROWING);
16630 if (value == error_mark_node)
16631 value = NULL_TREE;
16633 if (value != NULL_TREE)
16635 if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
16636 (TREE_TYPE (value)))
16638 error_at (cp_expr_loc_or_input_loc (value),
16639 "enumerator value for %qD must have integral or "
16640 "unscoped enumeration type", name);
16641 value = NULL_TREE;
16643 else
16645 value = cxx_constant_value (value);
16647 if (TREE_CODE (value) != INTEGER_CST)
16649 error ("enumerator value for %qD is not an integer "
16650 "constant", name);
16651 value = NULL_TREE;
16657 /* Default based on previous value. */
16658 if (value == NULL_TREE)
16660 if (TYPE_VALUES (enumtype))
16662 tree prev_value;
16664 /* C++03 7.2/4: If no initializer is specified for the first
16665 enumerator, the type is an unspecified integral
16666 type. Otherwise the type is the same as the type of the
16667 initializing value of the preceding enumerator unless the
16668 incremented value is not representable in that type, in
16669 which case the type is an unspecified integral type
16670 sufficient to contain the incremented value. */
16671 prev_value = DECL_INITIAL (TREE_VALUE (TYPE_VALUES (enumtype)));
16672 if (TREE_CODE (prev_value) != INTEGER_CST)
16673 value = error_mark_node;
16674 else
16676 wi::overflow_type overflowed;
16677 tree type = TREE_TYPE (prev_value);
16678 signop sgn = TYPE_SIGN (type);
16679 widest_int wi = wi::add (wi::to_widest (prev_value), 1, sgn,
16680 &overflowed);
16681 if (!overflowed)
16683 bool pos = !wi::neg_p (wi, sgn);
16684 if (!wi::fits_to_tree_p (wi, type))
16686 unsigned int itk;
16687 for (itk = itk_int; itk != itk_none; itk++)
16689 type = integer_types[itk];
16690 if (type != NULL_TREE
16691 && (pos || !TYPE_UNSIGNED (type))
16692 && wi::fits_to_tree_p (wi, type))
16693 break;
16695 if (type && cxx_dialect < cxx11
16696 && itk > itk_unsigned_long)
16697 pedwarn (input_location, OPT_Wlong_long,
16698 pos ? G_("\
16699 incremented enumerator value is too large for %<unsigned long%>") : G_("\
16700 incremented enumerator value is too large for %<long%>"));
16702 if (type == NULL_TREE)
16703 overflowed = wi::OVF_UNKNOWN;
16704 else
16705 value = wide_int_to_tree (type, wi);
16708 if (overflowed)
16710 error ("overflow in enumeration values at %qD", name);
16711 value = error_mark_node;
16715 else
16716 value = integer_zero_node;
16719 /* Remove no-op casts from the value. */
16720 STRIP_TYPE_NOPS (value);
16722 /* If the underlying type of the enum is fixed, check whether
16723 the enumerator values fits in the underlying type. If it
16724 does not fit, the program is ill-formed [C++0x dcl.enum]. */
16725 if (ENUM_UNDERLYING_TYPE (enumtype)
16726 && value
16727 && TREE_CODE (value) == INTEGER_CST)
16729 if (!int_fits_type_p (value, ENUM_UNDERLYING_TYPE (enumtype)))
16730 error ("enumerator value %qE is outside the range of underlying "
16731 "type %qT", value, ENUM_UNDERLYING_TYPE (enumtype));
16733 /* Convert the value to the appropriate type. */
16734 value = fold_convert (ENUM_UNDERLYING_TYPE (enumtype), value);
16738 /* C++ associates enums with global, function, or class declarations. */
16739 context = current_scope ();
16741 /* Build the actual enumeration constant. Note that the enumeration
16742 constants have the underlying type of the enum (if it is fixed)
16743 or the type of their initializer (if the underlying type of the
16744 enum is not fixed):
16746 [ C++0x dcl.enum ]
16748 If the underlying type is fixed, the type of each enumerator
16749 prior to the closing brace is the underlying type; if the
16750 initializing value of an enumerator cannot be represented by
16751 the underlying type, the program is ill-formed. If the
16752 underlying type is not fixed, the type of each enumerator is
16753 the type of its initializing value.
16755 If the underlying type is not fixed, it will be computed by
16756 finish_enum and we will reset the type of this enumerator. Of
16757 course, if we're processing a template, there may be no value. */
16758 type = value ? TREE_TYPE (value) : NULL_TREE;
16760 decl = build_decl (loc, CONST_DECL, name, type);
16762 DECL_CONTEXT (decl) = enumtype;
16763 TREE_CONSTANT (decl) = 1;
16764 TREE_READONLY (decl) = 1;
16765 DECL_INITIAL (decl) = value;
16767 if (attributes)
16768 cplus_decl_attributes (&decl, attributes, 0);
16770 if (context && context == current_class_type && !SCOPED_ENUM_P (enumtype))
16772 /* In something like `struct S { enum E { i = 7 }; };' we put `i'
16773 on the TYPE_FIELDS list for `S'. (That's so that you can say
16774 things like `S::i' later.) */
16776 /* The enumerator may be getting declared outside of its enclosing
16777 class, like so:
16779 class S { public: enum E : int; }; enum S::E : int { i = 7; };
16781 For which case we need to make sure that the access of `S::i'
16782 matches the access of `S::E'. */
16783 auto cas = make_temp_override (current_access_specifier);
16784 set_current_access_from_decl (TYPE_NAME (enumtype));
16785 finish_member_declaration (decl);
16787 else
16788 pushdecl (decl);
16790 /* Add this enumeration constant to the list for this type. */
16791 TYPE_VALUES (enumtype) = tree_cons (name, decl, TYPE_VALUES (enumtype));
16793 return decl;
16796 /* Look for an enumerator with the given NAME within the enumeration
16797 type ENUMTYPE. This routine is used primarily for qualified name
16798 lookup into an enumerator in C++0x, e.g.,
16800 enum class Color { Red, Green, Blue };
16802 Color color = Color::Red;
16804 Returns the value corresponding to the enumerator, or
16805 NULL_TREE if no such enumerator was found. */
16806 tree
16807 lookup_enumerator (tree enumtype, tree name)
16809 tree e;
16810 gcc_assert (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE);
16812 e = purpose_member (name, TYPE_VALUES (enumtype));
16813 return e? TREE_VALUE (e) : NULL_TREE;
16816 /* Implement LANG_HOOKS_SIMULATE_ENUM_DECL. */
16818 tree
16819 cxx_simulate_enum_decl (location_t loc, const char *name,
16820 vec<string_int_pair> *values)
16822 location_t saved_loc = input_location;
16823 input_location = loc;
16825 tree enumtype = start_enum (get_identifier (name), NULL_TREE, NULL_TREE,
16826 NULL_TREE, false, NULL);
16827 if (!OPAQUE_ENUM_P (enumtype))
16829 error_at (loc, "multiple definition of %q#T", enumtype);
16830 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16831 "previous definition here");
16832 return enumtype;
16834 SET_OPAQUE_ENUM_P (enumtype, false);
16835 DECL_SOURCE_LOCATION (TYPE_NAME (enumtype)) = loc;
16837 for (const string_int_pair &value : values)
16838 build_enumerator (get_identifier (value.first),
16839 build_int_cst (integer_type_node, value.second),
16840 enumtype, NULL_TREE, loc);
16842 finish_enum_value_list (enumtype);
16843 finish_enum (enumtype);
16845 input_location = saved_loc;
16846 return enumtype;
16849 /* Implement LANG_HOOKS_SIMULATE_RECORD_DECL. */
16851 tree
16852 cxx_simulate_record_decl (location_t loc, const char *name,
16853 array_slice<const tree> fields)
16855 iloc_sentinel ils (loc);
16857 tree ident = get_identifier (name);
16858 tree type = xref_tag (/*tag_code=*/record_type, ident);
16859 if (type != error_mark_node
16860 && (TREE_CODE (type) != RECORD_TYPE || COMPLETE_TYPE_P (type)))
16862 error ("redefinition of %q#T", type);
16863 type = error_mark_node;
16865 if (type == error_mark_node)
16866 return lhd_simulate_record_decl (loc, name, fields);
16868 xref_basetypes (type, NULL_TREE);
16869 type = begin_class_definition (type);
16870 if (type == error_mark_node)
16871 return lhd_simulate_record_decl (loc, name, fields);
16873 for (tree field : fields)
16874 finish_member_declaration (field);
16876 type = finish_struct (type, NULL_TREE);
16878 tree decl = build_decl (loc, TYPE_DECL, ident, type);
16879 set_underlying_type (decl);
16880 lang_hooks.decls.pushdecl (decl);
16882 return type;
16885 /* We're defining DECL. Make sure that its type is OK. */
16887 static void
16888 check_function_type (tree decl, tree current_function_parms)
16890 tree fntype = TREE_TYPE (decl);
16891 tree return_type = complete_type (TREE_TYPE (fntype));
16893 /* In a function definition, arg types must be complete. */
16894 require_complete_types_for_parms (current_function_parms);
16896 if (dependent_type_p (return_type)
16897 || type_uses_auto (return_type))
16898 return;
16899 if (!COMPLETE_OR_VOID_TYPE_P (return_type))
16901 tree args = TYPE_ARG_TYPES (fntype);
16903 error ("return type %q#T is incomplete", return_type);
16905 /* Make it return void instead. */
16906 if (TREE_CODE (fntype) == METHOD_TYPE)
16907 fntype = build_method_type_directly (TREE_TYPE (TREE_VALUE (args)),
16908 void_type_node,
16909 TREE_CHAIN (args));
16910 else
16911 fntype = build_function_type (void_type_node, args);
16912 fntype = (cp_build_type_attribute_variant
16913 (fntype, TYPE_ATTRIBUTES (TREE_TYPE (decl))));
16914 fntype = cxx_copy_lang_qualifiers (fntype, TREE_TYPE (decl));
16915 TREE_TYPE (decl) = fntype;
16917 else
16919 abstract_virtuals_error (decl, TREE_TYPE (fntype));
16920 maybe_warn_parm_abi (TREE_TYPE (fntype),
16921 DECL_SOURCE_LOCATION (decl));
16925 /* True iff FN is an implicitly-defined default constructor. */
16927 static bool
16928 implicit_default_ctor_p (tree fn)
16930 return (DECL_CONSTRUCTOR_P (fn)
16931 && !user_provided_p (fn)
16932 && sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (fn)));
16935 /* Clobber the contents of *this to let the back end know that the object
16936 storage is dead when we enter the constructor or leave the destructor. */
16938 static tree
16939 build_clobber_this ()
16941 /* Clobbering an empty base is pointless, and harmful if its one byte
16942 TYPE_SIZE overlays real data. */
16943 if (is_empty_class (current_class_type))
16944 return void_node;
16946 /* If we have virtual bases, clobber the whole object, but only if we're in
16947 charge. If we don't have virtual bases, clobber the as-base type so we
16948 don't mess with tail padding. */
16949 bool vbases = CLASSTYPE_VBASECLASSES (current_class_type);
16951 tree ctype = current_class_type;
16952 if (!vbases)
16953 ctype = CLASSTYPE_AS_BASE (ctype);
16955 tree clobber = build_clobber (ctype);
16957 tree thisref = current_class_ref;
16958 if (ctype != current_class_type)
16960 thisref = build_nop (build_reference_type (ctype), current_class_ptr);
16961 thisref = convert_from_reference (thisref);
16964 tree exprstmt = build2 (MODIFY_EXPR, void_type_node, thisref, clobber);
16965 if (vbases)
16966 exprstmt = build_if_in_charge (exprstmt);
16968 return exprstmt;
16971 /* Create the FUNCTION_DECL for a function definition.
16972 DECLSPECS and DECLARATOR are the parts of the declaration;
16973 they describe the function's name and the type it returns,
16974 but twisted together in a fashion that parallels the syntax of C.
16976 FLAGS is a bitwise or of SF_PRE_PARSED (indicating that the
16977 DECLARATOR is really the DECL for the function we are about to
16978 process and that DECLSPECS should be ignored), SF_INCLASS_INLINE
16979 indicating that the function is an inline defined in-class.
16981 This function creates a binding context for the function body
16982 as well as setting up the FUNCTION_DECL in current_function_decl.
16984 For C++, we must first check whether that datum makes any sense.
16985 For example, "class A local_a(1,2);" means that variable local_a
16986 is an aggregate of type A, which should have a constructor
16987 applied to it with the argument list [1, 2].
16989 On entry, DECL_INITIAL (decl1) should be NULL_TREE or error_mark_node,
16990 or may be a BLOCK if the function has been defined previously
16991 in this translation unit. On exit, DECL_INITIAL (decl1) will be
16992 error_mark_node if the function has never been defined, or
16993 a BLOCK if the function has been defined somewhere. */
16995 bool
16996 start_preparsed_function (tree decl1, tree attrs, int flags)
16998 tree ctype = NULL_TREE;
16999 bool doing_friend = false;
17001 /* Sanity check. */
17002 gcc_assert (VOID_TYPE_P (TREE_VALUE (void_list_node)));
17003 gcc_assert (TREE_CHAIN (void_list_node) == NULL_TREE);
17005 tree fntype = TREE_TYPE (decl1);
17006 if (TREE_CODE (fntype) == METHOD_TYPE)
17007 ctype = TYPE_METHOD_BASETYPE (fntype);
17008 else
17010 ctype = DECL_FRIEND_CONTEXT (decl1);
17012 if (ctype)
17013 doing_friend = true;
17016 if (DECL_DECLARED_INLINE_P (decl1)
17017 && lookup_attribute ("noinline", attrs))
17018 warning_at (DECL_SOURCE_LOCATION (decl1), 0,
17019 "inline function %qD given attribute %qs", decl1, "noinline");
17021 /* Handle gnu_inline attribute. */
17022 if (GNU_INLINE_P (decl1))
17024 DECL_EXTERNAL (decl1) = 1;
17025 DECL_NOT_REALLY_EXTERN (decl1) = 0;
17026 DECL_INTERFACE_KNOWN (decl1) = 1;
17027 DECL_DISREGARD_INLINE_LIMITS (decl1) = 1;
17030 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl1))
17031 /* This is a constructor, we must ensure that any default args
17032 introduced by this definition are propagated to the clones
17033 now. The clones are used directly in overload resolution. */
17034 adjust_clone_args (decl1);
17036 /* Sometimes we don't notice that a function is a static member, and
17037 build a METHOD_TYPE for it. Fix that up now. */
17038 gcc_assert (!(ctype != NULL_TREE && DECL_STATIC_FUNCTION_P (decl1)
17039 && TREE_CODE (TREE_TYPE (decl1)) == METHOD_TYPE));
17041 /* Set up current_class_type, and enter the scope of the class, if
17042 appropriate. */
17043 if (ctype)
17044 push_nested_class (ctype);
17045 else if (DECL_STATIC_FUNCTION_P (decl1))
17046 push_nested_class (DECL_CONTEXT (decl1));
17048 /* Now that we have entered the scope of the class, we must restore
17049 the bindings for any template parameters surrounding DECL1, if it
17050 is an inline member template. (Order is important; consider the
17051 case where a template parameter has the same name as a field of
17052 the class.) It is not until after this point that
17053 PROCESSING_TEMPLATE_DECL is guaranteed to be set up correctly. */
17054 if (flags & SF_INCLASS_INLINE)
17055 maybe_begin_member_template_processing (decl1);
17057 /* Effective C++ rule 15. */
17058 if (warn_ecpp
17059 && DECL_ASSIGNMENT_OPERATOR_P (decl1)
17060 && DECL_OVERLOADED_OPERATOR_IS (decl1, NOP_EXPR)
17061 && VOID_TYPE_P (TREE_TYPE (fntype)))
17062 warning (OPT_Weffc__,
17063 "%<operator=%> should return a reference to %<*this%>");
17065 /* Make the init_value nonzero so pushdecl knows this is not tentative.
17066 error_mark_node is replaced below (in poplevel) with the BLOCK. */
17067 if (!DECL_INITIAL (decl1))
17068 DECL_INITIAL (decl1) = error_mark_node;
17070 /* This function exists in static storage.
17071 (This does not mean `static' in the C sense!) */
17072 TREE_STATIC (decl1) = 1;
17074 /* We must call push_template_decl after current_class_type is set
17075 up. (If we are processing inline definitions after exiting a
17076 class scope, current_class_type will be NULL_TREE until set above
17077 by push_nested_class.) */
17078 if (processing_template_decl)
17080 tree newdecl1 = push_template_decl (decl1, doing_friend);
17081 if (newdecl1 == error_mark_node)
17083 if (ctype || DECL_STATIC_FUNCTION_P (decl1))
17084 pop_nested_class ();
17085 return false;
17087 decl1 = newdecl1;
17090 /* Make sure the parameter and return types are reasonable. When
17091 you declare a function, these types can be incomplete, but they
17092 must be complete when you define the function. */
17093 check_function_type (decl1, DECL_ARGUMENTS (decl1));
17095 /* Build the return declaration for the function. */
17096 tree restype = TREE_TYPE (fntype);
17098 if (DECL_RESULT (decl1) == NULL_TREE)
17100 tree resdecl;
17102 resdecl = build_decl (input_location, RESULT_DECL, 0, restype);
17103 DECL_ARTIFICIAL (resdecl) = 1;
17104 DECL_IGNORED_P (resdecl) = 1;
17105 DECL_RESULT (decl1) = resdecl;
17107 cp_apply_type_quals_to_decl (cp_type_quals (restype), resdecl);
17110 /* Record the decl so that the function name is defined.
17111 If we already have a decl for this name, and it is a FUNCTION_DECL,
17112 use the old decl. */
17113 if (!processing_template_decl && !(flags & SF_PRE_PARSED))
17115 /* A specialization is not used to guide overload resolution. */
17116 if (!DECL_FUNCTION_MEMBER_P (decl1)
17117 && !(DECL_USE_TEMPLATE (decl1) &&
17118 PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl1))))
17120 tree olddecl = pushdecl (decl1);
17122 if (olddecl == error_mark_node)
17123 /* If something went wrong when registering the declaration,
17124 use DECL1; we have to have a FUNCTION_DECL to use when
17125 parsing the body of the function. */
17127 else
17129 /* Otherwise, OLDDECL is either a previous declaration
17130 of the same function or DECL1 itself. */
17132 if (warn_missing_declarations
17133 && olddecl == decl1
17134 && !DECL_MAIN_P (decl1)
17135 && TREE_PUBLIC (decl1)
17136 && !DECL_DECLARED_INLINE_P (decl1))
17138 tree context;
17140 /* Check whether DECL1 is in an anonymous
17141 namespace. */
17142 for (context = DECL_CONTEXT (decl1);
17143 context;
17144 context = DECL_CONTEXT (context))
17146 if (TREE_CODE (context) == NAMESPACE_DECL
17147 && DECL_NAME (context) == NULL_TREE)
17148 break;
17151 if (context == NULL)
17152 warning_at (DECL_SOURCE_LOCATION (decl1),
17153 OPT_Wmissing_declarations,
17154 "no previous declaration for %qD", decl1);
17157 decl1 = olddecl;
17160 else
17162 /* We need to set the DECL_CONTEXT. */
17163 if (!DECL_CONTEXT (decl1) && DECL_TEMPLATE_INFO (decl1))
17164 DECL_CONTEXT (decl1) = DECL_CONTEXT (DECL_TI_TEMPLATE (decl1));
17166 fntype = TREE_TYPE (decl1);
17167 restype = TREE_TYPE (fntype);
17169 /* If #pragma weak applies, mark the decl appropriately now.
17170 The pragma only applies to global functions. Because
17171 determining whether or not the #pragma applies involves
17172 computing the mangled name for the declaration, we cannot
17173 apply the pragma until after we have merged this declaration
17174 with any previous declarations; if the original declaration
17175 has a linkage specification, that specification applies to
17176 the definition as well, and may affect the mangled name. */
17177 if (DECL_FILE_SCOPE_P (decl1))
17178 maybe_apply_pragma_weak (decl1);
17181 /* We are now in the scope of the function being defined. */
17182 current_function_decl = decl1;
17184 /* Save the parm names or decls from this function's declarator
17185 where store_parm_decls will find them. */
17186 tree current_function_parms = DECL_ARGUMENTS (decl1);
17188 /* Let the user know we're compiling this function. */
17189 announce_function (decl1);
17191 gcc_assert (DECL_INITIAL (decl1));
17193 /* This function may already have been parsed, in which case just
17194 return; our caller will skip over the body without parsing. */
17195 if (DECL_INITIAL (decl1) != error_mark_node)
17196 return true;
17198 /* Initialize RTL machinery. We cannot do this until
17199 CURRENT_FUNCTION_DECL and DECL_RESULT are set up. We do this
17200 even when processing a template; this is how we get
17201 CFUN set up, and our per-function variables initialized.
17202 FIXME factor out the non-RTL stuff. */
17203 cp_binding_level *bl = current_binding_level;
17204 allocate_struct_function (decl1, processing_template_decl);
17206 /* Initialize the language data structures. Whenever we start
17207 a new function, we destroy temporaries in the usual way. */
17208 cfun->language = ggc_cleared_alloc<language_function> ();
17209 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
17210 current_binding_level = bl;
17212 /* If we are (erroneously) defining a function that we have already
17213 defined before, wipe out what we knew before. */
17214 gcc_checking_assert (!DECL_PENDING_INLINE_P (decl1));
17215 FNDECL_USED_AUTO (decl1) = false;
17216 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = NULL;
17218 if (!processing_template_decl && type_uses_auto (restype))
17220 FNDECL_USED_AUTO (decl1) = true;
17221 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = restype;
17224 /* Start the statement-tree, start the tree now. */
17225 DECL_SAVED_TREE (decl1) = push_stmt_list ();
17227 if (ctype && !doing_friend && !DECL_STATIC_FUNCTION_P (decl1))
17229 /* We know that this was set up by `grokclassfn'. We do not
17230 wait until `store_parm_decls', since evil parse errors may
17231 never get us to that point. Here we keep the consistency
17232 between `current_class_type' and `current_class_ptr'. */
17233 tree t = DECL_ARGUMENTS (decl1);
17235 gcc_assert (t != NULL_TREE && TREE_CODE (t) == PARM_DECL);
17236 gcc_assert (TYPE_PTR_P (TREE_TYPE (t)));
17238 cp_function_chain->x_current_class_ref
17239 = cp_build_fold_indirect_ref (t);
17240 /* Set this second to avoid shortcut in cp_build_indirect_ref. */
17241 cp_function_chain->x_current_class_ptr = t;
17243 /* Constructors and destructors need to know whether they're "in
17244 charge" of initializing virtual base classes. */
17245 t = DECL_CHAIN (t);
17246 if (DECL_HAS_IN_CHARGE_PARM_P (decl1))
17248 current_in_charge_parm = t;
17249 t = DECL_CHAIN (t);
17251 if (DECL_HAS_VTT_PARM_P (decl1))
17253 gcc_assert (DECL_NAME (t) == vtt_parm_identifier);
17254 current_vtt_parm = t;
17258 bool honor_interface = (!DECL_TEMPLATE_INSTANTIATION (decl1)
17259 /* Implicitly-defined methods (like the
17260 destructor for a class in which no destructor
17261 is explicitly declared) must not be defined
17262 until their definition is needed. So, we
17263 ignore interface specifications for
17264 compiler-generated functions. */
17265 && !DECL_ARTIFICIAL (decl1));
17266 struct c_fileinfo *finfo
17267 = get_fileinfo (LOCATION_FILE (DECL_SOURCE_LOCATION (decl1)));
17269 if (processing_template_decl)
17270 /* Don't mess with interface flags. */;
17271 else if (DECL_INTERFACE_KNOWN (decl1))
17273 tree ctx = decl_function_context (decl1);
17275 if (DECL_NOT_REALLY_EXTERN (decl1))
17276 DECL_EXTERNAL (decl1) = 0;
17278 if (ctx != NULL_TREE && vague_linkage_p (ctx))
17279 /* This is a function in a local class in an extern inline
17280 or template function. */
17281 comdat_linkage (decl1);
17283 /* If this function belongs to an interface, it is public.
17284 If it belongs to someone else's interface, it is also external.
17285 This only affects inlines and template instantiations. */
17286 else if (!finfo->interface_unknown && honor_interface)
17288 if (DECL_DECLARED_INLINE_P (decl1)
17289 || DECL_TEMPLATE_INSTANTIATION (decl1))
17291 DECL_EXTERNAL (decl1)
17292 = (finfo->interface_only
17293 || (DECL_DECLARED_INLINE_P (decl1)
17294 && ! flag_implement_inlines
17295 && !DECL_VINDEX (decl1)));
17297 /* For WIN32 we also want to put these in linkonce sections. */
17298 maybe_make_one_only (decl1);
17300 else
17301 DECL_EXTERNAL (decl1) = 0;
17302 DECL_INTERFACE_KNOWN (decl1) = 1;
17303 /* If this function is in an interface implemented in this file,
17304 make sure that the back end knows to emit this function
17305 here. */
17306 if (!DECL_EXTERNAL (decl1))
17307 mark_needed (decl1);
17309 else if (finfo->interface_unknown && finfo->interface_only
17310 && honor_interface)
17312 /* If MULTIPLE_SYMBOL_SPACES is defined and we saw a #pragma
17313 interface, we will have both finfo->interface_unknown and
17314 finfo->interface_only set. In that case, we don't want to
17315 use the normal heuristics because someone will supply a
17316 #pragma implementation elsewhere, and deducing it here would
17317 produce a conflict. */
17318 comdat_linkage (decl1);
17319 DECL_EXTERNAL (decl1) = 0;
17320 DECL_INTERFACE_KNOWN (decl1) = 1;
17321 DECL_DEFER_OUTPUT (decl1) = 1;
17323 else
17325 /* This is a definition, not a reference.
17326 So clear DECL_EXTERNAL, unless this is a GNU extern inline. */
17327 if (!GNU_INLINE_P (decl1))
17328 DECL_EXTERNAL (decl1) = 0;
17330 if ((DECL_DECLARED_INLINE_P (decl1)
17331 || DECL_TEMPLATE_INSTANTIATION (decl1))
17332 && ! DECL_INTERFACE_KNOWN (decl1))
17333 DECL_DEFER_OUTPUT (decl1) = 1;
17334 else
17335 DECL_INTERFACE_KNOWN (decl1) = 1;
17338 /* Determine the ELF visibility attribute for the function. We must not
17339 do this before calling "pushdecl", as we must allow "duplicate_decls"
17340 to merge any attributes appropriately. We also need to wait until
17341 linkage is set. */
17342 if (!DECL_CLONED_FUNCTION_P (decl1))
17343 determine_visibility (decl1);
17345 if (!processing_template_decl)
17346 maybe_instantiate_noexcept (decl1);
17348 begin_scope (sk_function_parms, decl1);
17350 ++function_depth;
17352 start_fname_decls ();
17354 store_parm_decls (current_function_parms);
17356 if (!processing_template_decl
17357 && (flag_lifetime_dse > 1)
17358 && DECL_CONSTRUCTOR_P (decl1)
17359 && !DECL_CLONED_FUNCTION_P (decl1)
17360 /* Clobbering an empty base is harmful if it overlays real data. */
17361 && !is_empty_class (current_class_type)
17362 /* We can't clobber safely for an implicitly-defined default constructor
17363 because part of the initialization might happen before we enter the
17364 constructor, via AGGR_INIT_ZERO_FIRST (c++/68006). */
17365 && !implicit_default_ctor_p (decl1))
17366 finish_expr_stmt (build_clobber_this ());
17368 if (!processing_template_decl
17369 && DECL_CONSTRUCTOR_P (decl1)
17370 && sanitize_flags_p (SANITIZE_VPTR)
17371 && !DECL_CLONED_FUNCTION_P (decl1)
17372 && !implicit_default_ctor_p (decl1))
17373 cp_ubsan_maybe_initialize_vtbl_ptrs (current_class_ptr);
17375 if (!DECL_OMP_DECLARE_REDUCTION_P (decl1))
17376 start_lambda_scope (decl1);
17378 return true;
17382 /* Like start_preparsed_function, except that instead of a
17383 FUNCTION_DECL, this function takes DECLSPECS and DECLARATOR.
17385 Returns true on success. If the DECLARATOR is not suitable
17386 for a function, we return false, which tells the parser to
17387 skip the entire function. */
17389 bool
17390 start_function (cp_decl_specifier_seq *declspecs,
17391 const cp_declarator *declarator,
17392 tree attrs)
17394 tree decl1;
17396 decl1 = grokdeclarator (declarator, declspecs, FUNCDEF, 1, &attrs);
17397 invoke_plugin_callbacks (PLUGIN_START_PARSE_FUNCTION, decl1);
17398 if (decl1 == error_mark_node)
17399 return false;
17401 if (DECL_MAIN_P (decl1))
17402 /* main must return int. grokfndecl should have corrected it
17403 (and issued a diagnostic) if the user got it wrong. */
17404 gcc_assert (same_type_p (TREE_TYPE (TREE_TYPE (decl1)),
17405 integer_type_node));
17407 return start_preparsed_function (decl1, attrs, /*flags=*/SF_DEFAULT);
17410 /* Returns true iff an EH_SPEC_BLOCK should be created in the body of
17411 FN. */
17413 static bool
17414 use_eh_spec_block (tree fn)
17416 return (flag_exceptions && flag_enforce_eh_specs
17417 && !processing_template_decl
17418 /* We insert the EH_SPEC_BLOCK only in the original
17419 function; then, it is copied automatically to the
17420 clones. */
17421 && !DECL_CLONED_FUNCTION_P (fn)
17422 /* Implicitly-generated constructors and destructors have
17423 exception specifications. However, those specifications
17424 are the union of the possible exceptions specified by the
17425 constructors/destructors for bases and members, so no
17426 unallowed exception will ever reach this function. By
17427 not creating the EH_SPEC_BLOCK we save a little memory,
17428 and we avoid spurious warnings about unreachable
17429 code. */
17430 && !DECL_DEFAULTED_FN (fn)
17431 && !type_throw_all_p (TREE_TYPE (fn)));
17434 /* Helper function to push ARGS into the current lexical scope. DECL
17435 is the function declaration. NONPARMS is used to handle enum
17436 constants. */
17438 void
17439 do_push_parm_decls (tree decl, tree args, tree *nonparms)
17441 /* If we're doing semantic analysis, then we'll call pushdecl
17442 for each of these. We must do them in reverse order so that
17443 they end in the correct forward order. */
17444 args = nreverse (args);
17446 tree next;
17447 for (tree parm = args; parm; parm = next)
17449 next = DECL_CHAIN (parm);
17450 if (TREE_CODE (parm) == PARM_DECL)
17451 pushdecl (parm);
17452 else if (nonparms)
17454 /* If we find an enum constant or a type tag, put it aside for
17455 the moment. */
17456 TREE_CHAIN (parm) = NULL_TREE;
17457 *nonparms = chainon (*nonparms, parm);
17461 /* Get the decls in their original chain order and record in the
17462 function. This is all and only the PARM_DECLs that were
17463 pushed into scope by the loop above. */
17464 DECL_ARGUMENTS (decl) = get_local_decls ();
17467 /* Store the parameter declarations into the current function declaration.
17468 This is called after parsing the parameter declarations, before
17469 digesting the body of the function.
17471 Also install to binding contour return value identifier, if any. */
17473 static void
17474 store_parm_decls (tree current_function_parms)
17476 tree fndecl = current_function_decl;
17478 /* This is a chain of any other decls that came in among the parm
17479 declarations. If a parm is declared with enum {foo, bar} x;
17480 then CONST_DECLs for foo and bar are put here. */
17481 tree nonparms = NULL_TREE;
17483 if (current_function_parms)
17485 /* This case is when the function was defined with an ANSI prototype.
17486 The parms already have decls, so we need not do anything here
17487 except record them as in effect
17488 and complain if any redundant old-style parm decls were written. */
17490 tree specparms = current_function_parms;
17492 /* Must clear this because it might contain TYPE_DECLs declared
17493 at class level. */
17494 current_binding_level->names = NULL;
17496 do_push_parm_decls (fndecl, specparms, &nonparms);
17498 else
17499 DECL_ARGUMENTS (fndecl) = NULL_TREE;
17501 /* Now store the final chain of decls for the arguments
17502 as the decl-chain of the current lexical scope.
17503 Put the enumerators in as well, at the front so that
17504 DECL_ARGUMENTS is not modified. */
17505 current_binding_level->names = chainon (nonparms, DECL_ARGUMENTS (fndecl));
17507 if (use_eh_spec_block (current_function_decl))
17508 current_eh_spec_block = begin_eh_spec_block ();
17512 /* Set the return value of the [cd]tor if the ABI wants that. */
17514 void
17515 maybe_return_this (void)
17517 if (targetm.cxx.cdtor_returns_this ())
17519 /* Return the address of the object. */
17520 tree val = DECL_ARGUMENTS (current_function_decl);
17521 suppress_warning (val, OPT_Wuse_after_free);
17522 val = fold_convert (TREE_TYPE (DECL_RESULT (current_function_decl)), val);
17523 val = build2 (MODIFY_EXPR, TREE_TYPE (val),
17524 DECL_RESULT (current_function_decl), val);
17525 tree exprstmt = build_stmt (input_location, RETURN_EXPR, val);
17526 add_stmt (exprstmt);
17530 /* Do all the processing for the beginning of a destructor; set up the
17531 vtable pointers and cleanups for bases and members. */
17533 static void
17534 begin_destructor_body (void)
17536 tree compound_stmt;
17538 /* If the CURRENT_CLASS_TYPE is incomplete, we will have already
17539 issued an error message. We still want to try to process the
17540 body of the function, but initialize_vtbl_ptrs will crash if
17541 TYPE_BINFO is NULL. */
17542 if (COMPLETE_TYPE_P (current_class_type))
17544 compound_stmt = begin_compound_stmt (0);
17545 /* Make all virtual function table pointers in non-virtual base
17546 classes point to CURRENT_CLASS_TYPE's virtual function
17547 tables. */
17548 initialize_vtbl_ptrs (current_class_ptr);
17549 finish_compound_stmt (compound_stmt);
17551 if (flag_lifetime_dse
17552 /* Clobbering an empty base is harmful if it overlays real data. */
17553 && !is_empty_class (current_class_type))
17555 if (sanitize_flags_p (SANITIZE_VPTR)
17556 && (flag_sanitize_recover & SANITIZE_VPTR) == 0
17557 && TYPE_CONTAINS_VPTR_P (current_class_type))
17559 tree binfo = TYPE_BINFO (current_class_type);
17560 tree ref
17561 = cp_build_fold_indirect_ref (current_class_ptr);
17563 tree vtbl_ptr = build_vfield_ref (ref, TREE_TYPE (binfo));
17564 tree vtbl = build_zero_cst (TREE_TYPE (vtbl_ptr));
17565 tree stmt = cp_build_modify_expr (input_location, vtbl_ptr,
17566 NOP_EXPR, vtbl,
17567 tf_warning_or_error);
17568 /* If the vptr is shared with some virtual nearly empty base,
17569 don't clear it if not in charge, the dtor of the virtual
17570 nearly empty base will do that later. */
17571 if (CLASSTYPE_VBASECLASSES (current_class_type))
17573 tree c = current_class_type;
17574 while (CLASSTYPE_PRIMARY_BINFO (c))
17576 if (BINFO_VIRTUAL_P (CLASSTYPE_PRIMARY_BINFO (c)))
17578 stmt = convert_to_void (stmt, ICV_STATEMENT,
17579 tf_warning_or_error);
17580 stmt = build_if_in_charge (stmt);
17581 break;
17583 c = BINFO_TYPE (CLASSTYPE_PRIMARY_BINFO (c));
17586 finish_decl_cleanup (NULL_TREE, stmt);
17588 else
17589 finish_decl_cleanup (NULL_TREE, build_clobber_this ());
17592 /* And insert cleanups for our bases and members so that they
17593 will be properly destroyed if we throw. */
17594 push_base_cleanups ();
17598 /* Do the necessary processing for the beginning of a function body, which
17599 in this case includes member-initializers, but not the catch clauses of
17600 a function-try-block. Currently, this means opening a binding level
17601 for the member-initializers (in a ctor), member cleanups (in a dtor),
17602 and capture proxies (in a lambda operator()). */
17604 tree
17605 begin_function_body (void)
17607 if (! FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
17608 return NULL_TREE;
17610 if (processing_template_decl)
17611 /* Do nothing now. */;
17612 else
17613 /* Always keep the BLOCK node associated with the outermost pair of
17614 curly braces of a function. These are needed for correct
17615 operation of dwarfout.c. */
17616 keep_next_level (true);
17618 tree stmt = begin_compound_stmt (BCS_FN_BODY);
17620 if (processing_template_decl)
17621 /* Do nothing now. */;
17622 else if (DECL_DESTRUCTOR_P (current_function_decl))
17623 begin_destructor_body ();
17625 return stmt;
17628 /* Do the processing for the end of a function body. Currently, this means
17629 closing out the cleanups for fully-constructed bases and members, and in
17630 the case of the destructor, deleting the object if desired. Again, this
17631 is only meaningful for [cd]tors, since they are the only functions where
17632 there is a significant distinction between the main body and any
17633 function catch clauses. Handling, say, main() return semantics here
17634 would be wrong, as flowing off the end of a function catch clause for
17635 main() would also need to return 0. */
17637 void
17638 finish_function_body (tree compstmt)
17640 if (compstmt == NULL_TREE)
17641 return;
17643 /* Close the block. */
17644 finish_compound_stmt (compstmt);
17646 if (processing_template_decl)
17647 /* Do nothing now. */;
17648 else if (DECL_CONSTRUCTOR_P (current_function_decl)
17649 || DECL_DESTRUCTOR_P (current_function_decl))
17650 maybe_return_this ();
17653 /* Given a function, returns the BLOCK corresponding to the outermost level
17654 of curly braces, skipping the artificial block created for constructor
17655 initializers. */
17657 tree
17658 outer_curly_brace_block (tree fndecl)
17660 tree block = DECL_INITIAL (fndecl);
17661 if (BLOCK_OUTER_CURLY_BRACE_P (block))
17662 return block;
17663 block = BLOCK_SUBBLOCKS (block);
17664 if (BLOCK_OUTER_CURLY_BRACE_P (block))
17665 return block;
17666 block = BLOCK_SUBBLOCKS (block);
17667 gcc_assert (BLOCK_OUTER_CURLY_BRACE_P (block));
17668 return block;
17671 /* If FNDECL is a class's key method, add the class to the list of
17672 keyed classes that should be emitted. */
17674 static void
17675 record_key_method_defined (tree fndecl)
17677 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
17678 && DECL_VIRTUAL_P (fndecl)
17679 && !processing_template_decl)
17681 tree fnclass = DECL_CONTEXT (fndecl);
17682 if (fndecl == CLASSTYPE_KEY_METHOD (fnclass))
17683 vec_safe_push (keyed_classes, fnclass);
17687 /* Attempt to add a fix-it hint to RICHLOC suggesting the insertion
17688 of "return *this;" immediately before its location, using FNDECL's
17689 first statement (if any) to give the indentation, if appropriate. */
17691 static void
17692 add_return_star_this_fixit (gcc_rich_location *richloc, tree fndecl)
17694 location_t indent = UNKNOWN_LOCATION;
17695 tree stmts = expr_first (DECL_SAVED_TREE (fndecl));
17696 if (stmts)
17697 indent = EXPR_LOCATION (stmts);
17698 richloc->add_fixit_insert_formatted ("return *this;",
17699 richloc->get_loc (),
17700 indent);
17703 /* This function carries out the subset of finish_function operations needed
17704 to emit the compiler-generated outlined helper functions used by the
17705 coroutines implementation. */
17707 static void
17708 emit_coro_helper (tree helper)
17710 /* This is a partial set of the operations done by finish_function()
17711 plus emitting the result. */
17712 set_cfun (NULL);
17713 current_function_decl = helper;
17714 begin_scope (sk_function_parms, NULL);
17715 store_parm_decls (DECL_ARGUMENTS (helper));
17716 announce_function (helper);
17717 allocate_struct_function (helper, false);
17718 cfun->language = ggc_cleared_alloc<language_function> ();
17719 poplevel (1, 0, 1);
17720 maybe_save_constexpr_fundef (helper);
17721 /* We must start each function with a clear fold cache. */
17722 clear_fold_cache ();
17723 cp_fold_function (helper);
17724 DECL_CONTEXT (DECL_RESULT (helper)) = helper;
17725 BLOCK_SUPERCONTEXT (DECL_INITIAL (helper)) = helper;
17726 /* This function has coroutine IFNs that we should handle in middle
17727 end lowering. */
17728 cfun->coroutine_component = true;
17729 cp_genericize (helper);
17730 expand_or_defer_fn (helper);
17733 /* Finish up a function declaration and compile that function
17734 all the way to assembler language output. The free the storage
17735 for the function definition. INLINE_P is TRUE if we just
17736 finished processing the body of an in-class inline function
17737 definition. (This processing will have taken place after the
17738 class definition is complete.) */
17740 tree
17741 finish_function (bool inline_p)
17743 tree fndecl = current_function_decl;
17744 tree fntype, ctype = NULL_TREE;
17745 tree resumer = NULL_TREE, destroyer = NULL_TREE;
17746 bool coro_p = flag_coroutines
17747 && !processing_template_decl
17748 && DECL_COROUTINE_P (fndecl);
17749 bool coro_emit_helpers = false;
17751 /* When we get some parse errors, we can end up without a
17752 current_function_decl, so cope. */
17753 if (fndecl == NULL_TREE)
17754 return error_mark_node;
17756 if (!DECL_OMP_DECLARE_REDUCTION_P (fndecl))
17757 finish_lambda_scope ();
17759 if (c_dialect_objc ())
17760 objc_finish_function ();
17762 record_key_method_defined (fndecl);
17764 fntype = TREE_TYPE (fndecl);
17766 /* TREE_READONLY (fndecl) = 1;
17767 This caused &foo to be of type ptr-to-const-function
17768 which then got a warning when stored in a ptr-to-function variable. */
17770 gcc_assert (building_stmt_list_p ());
17771 /* The current function is being defined, so its DECL_INITIAL should
17772 be set, and unless there's a multiple definition, it should be
17773 error_mark_node. */
17774 gcc_assert (DECL_INITIAL (fndecl) == error_mark_node);
17776 if (coro_p)
17778 /* Only try to emit the coroutine outlined helper functions if the
17779 transforms succeeded. Otherwise, treat errors in the same way as
17780 a regular function. */
17781 coro_emit_helpers = morph_fn_to_coro (fndecl, &resumer, &destroyer);
17783 /* We should handle coroutine IFNs in middle end lowering. */
17784 cfun->coroutine_component = true;
17786 /* Do not try to process the ramp's EH unless outlining succeeded. */
17787 if (coro_emit_helpers && use_eh_spec_block (fndecl))
17788 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
17789 (TREE_TYPE (fndecl)),
17790 current_eh_spec_block);
17792 else
17793 /* For a cloned function, we've already got all the code we need;
17794 there's no need to add any extra bits. */
17795 if (!DECL_CLONED_FUNCTION_P (fndecl))
17797 /* Make it so that `main' always returns 0 by default. */
17798 if (DECL_MAIN_P (current_function_decl))
17799 finish_return_stmt (integer_zero_node);
17801 if (use_eh_spec_block (current_function_decl))
17802 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
17803 (TREE_TYPE (current_function_decl)),
17804 current_eh_spec_block);
17807 /* If we're saving up tree structure, tie off the function now. */
17808 DECL_SAVED_TREE (fndecl) = pop_stmt_list (DECL_SAVED_TREE (fndecl));
17810 finish_fname_decls ();
17812 /* If this function can't throw any exceptions, remember that. */
17813 if (!processing_template_decl
17814 && !cp_function_chain->can_throw
17815 && !flag_non_call_exceptions
17816 && !decl_replaceable_p (fndecl,
17817 opt_for_fn (fndecl, flag_semantic_interposition)))
17818 TREE_NOTHROW (fndecl) = 1;
17820 /* This must come after expand_function_end because cleanups might
17821 have declarations (from inline functions) that need to go into
17822 this function's blocks. */
17824 /* If the current binding level isn't the outermost binding level
17825 for this function, either there is a bug, or we have experienced
17826 syntax errors and the statement tree is malformed. */
17827 if (current_binding_level->kind != sk_function_parms)
17829 /* Make sure we have already experienced errors. */
17830 gcc_assert (errorcount);
17832 /* Throw away the broken statement tree and extra binding
17833 levels. */
17834 DECL_SAVED_TREE (fndecl) = alloc_stmt_list ();
17836 while (current_binding_level->kind != sk_function_parms)
17838 if (current_binding_level->kind == sk_class)
17839 pop_nested_class ();
17840 else
17841 poplevel (0, 0, 0);
17844 poplevel (1, 0, 1);
17846 /* Statements should always be full-expressions at the outermost set
17847 of curly braces for a function. */
17848 gcc_assert (stmts_are_full_exprs_p ());
17850 /* If there are no return statements in a function with auto return type,
17851 the return type is void. But if the declared type is something like
17852 auto*, this is an error. */
17853 if (!processing_template_decl && FNDECL_USED_AUTO (fndecl)
17854 && TREE_TYPE (fntype) == DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
17856 if (is_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
17857 && !current_function_returns_value
17858 && !current_function_returns_null)
17860 /* We haven't applied return type deduction because we haven't
17861 seen any return statements. Do that now. */
17862 tree node = type_uses_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
17863 do_auto_deduction (DECL_SAVED_AUTO_RETURN_TYPE (fndecl),
17864 void_node, node, tf_warning_or_error,
17865 adc_return_type);
17867 apply_deduced_return_type (fndecl, void_type_node);
17868 fntype = TREE_TYPE (fndecl);
17870 else if (!current_function_returns_value
17871 && !current_function_returns_null)
17873 error ("no return statements in function returning %qT",
17874 DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
17875 inform (input_location, "only plain %<auto%> return type can be "
17876 "deduced to %<void%>");
17880 /* Remember that we were in class scope. */
17881 if (current_class_name)
17882 ctype = current_class_type;
17884 if (DECL_DELETED_FN (fndecl))
17886 DECL_INITIAL (fndecl) = error_mark_node;
17887 DECL_SAVED_TREE (fndecl) = NULL_TREE;
17888 goto cleanup;
17891 // If this is a concept, check that the definition is reasonable.
17892 if (DECL_DECLARED_CONCEPT_P (fndecl))
17893 check_function_concept (fndecl);
17895 if (flag_openmp)
17896 if (tree attr = lookup_attribute ("omp declare variant base",
17897 DECL_ATTRIBUTES (fndecl)))
17898 omp_declare_variant_finalize (fndecl, attr);
17900 /* Complain if there's just no return statement. */
17901 if ((warn_return_type
17902 || (cxx_dialect >= cxx14
17903 && DECL_DECLARED_CONSTEXPR_P (fndecl)))
17904 && !VOID_TYPE_P (TREE_TYPE (fntype))
17905 && !dependent_type_p (TREE_TYPE (fntype))
17906 && !current_function_returns_value && !current_function_returns_null
17907 /* Don't complain if we abort or throw. */
17908 && !current_function_returns_abnormally
17909 /* Don't complain if there's an infinite loop. */
17910 && !current_function_infinite_loop
17911 /* Don't complain if we are declared noreturn. */
17912 && !TREE_THIS_VOLATILE (fndecl)
17913 && !DECL_NAME (DECL_RESULT (fndecl))
17914 && !warning_suppressed_p (fndecl, OPT_Wreturn_type)
17915 /* Structor return values (if any) are set by the compiler. */
17916 && !DECL_CONSTRUCTOR_P (fndecl)
17917 && !DECL_DESTRUCTOR_P (fndecl)
17918 && targetm.warn_func_return (fndecl))
17920 gcc_rich_location richloc (input_location);
17921 /* Potentially add a "return *this;" fix-it hint for
17922 assignment operators. */
17923 if (IDENTIFIER_ASSIGN_OP_P (DECL_NAME (fndecl)))
17925 tree valtype = TREE_TYPE (DECL_RESULT (fndecl));
17926 if (TREE_CODE (valtype) == REFERENCE_TYPE
17927 && current_class_ref
17928 && same_type_ignoring_top_level_qualifiers_p
17929 (TREE_TYPE (valtype), TREE_TYPE (current_class_ref))
17930 && global_dc->option_enabled (OPT_Wreturn_type,
17931 global_dc->lang_mask,
17932 global_dc->option_state))
17933 add_return_star_this_fixit (&richloc, fndecl);
17935 if (cxx_dialect >= cxx14
17936 && DECL_DECLARED_CONSTEXPR_P (fndecl))
17937 error_at (&richloc, "no return statement in %<constexpr%> function "
17938 "returning non-void");
17939 else if (warning_at (&richloc, OPT_Wreturn_type,
17940 "no return statement in function returning "
17941 "non-void"))
17942 suppress_warning (fndecl, OPT_Wreturn_type);
17945 /* Lambda closure members are implicitly constexpr if possible. */
17946 if (cxx_dialect >= cxx17
17947 && LAMBDA_TYPE_P (CP_DECL_CONTEXT (fndecl)))
17948 DECL_DECLARED_CONSTEXPR_P (fndecl)
17949 = ((processing_template_decl
17950 || is_valid_constexpr_fn (fndecl, /*complain*/false))
17951 && potential_constant_expression (DECL_SAVED_TREE (fndecl)));
17953 /* Save constexpr function body before it gets munged by
17954 the NRV transformation. */
17955 maybe_save_constexpr_fundef (fndecl);
17957 /* Invoke the pre-genericize plugin before we start munging things. */
17958 if (!processing_template_decl)
17959 invoke_plugin_callbacks (PLUGIN_PRE_GENERICIZE, fndecl);
17961 /* Perform delayed folding before NRV transformation. */
17962 if (!processing_template_decl
17963 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
17964 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
17965 cp_fold_function (fndecl);
17967 /* Set up the named return value optimization, if we can. Candidate
17968 variables are selected in check_return_expr. */
17969 if (current_function_return_value)
17971 tree r = current_function_return_value;
17972 tree outer;
17974 if (r != error_mark_node
17975 /* This is only worth doing for fns that return in memory--and
17976 simpler, since we don't have to worry about promoted modes. */
17977 && aggregate_value_p (TREE_TYPE (TREE_TYPE (fndecl)), fndecl)
17978 /* Only allow this for variables declared in the outer scope of
17979 the function so we know that their lifetime always ends with a
17980 return; see g++.dg/opt/nrv6.C. We could be more flexible if
17981 we were to do this optimization in tree-ssa. */
17982 && (outer = outer_curly_brace_block (fndecl))
17983 && chain_member (r, BLOCK_VARS (outer)))
17984 finalize_nrv (&DECL_SAVED_TREE (fndecl), r, DECL_RESULT (fndecl));
17986 current_function_return_value = NULL_TREE;
17989 /* Must mark the RESULT_DECL as being in this function. */
17990 DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
17992 /* Set the BLOCK_SUPERCONTEXT of the outermost function scope to point
17993 to the FUNCTION_DECL node itself. */
17994 BLOCK_SUPERCONTEXT (DECL_INITIAL (fndecl)) = fndecl;
17996 /* Store the end of the function, so that we get good line number
17997 info for the epilogue. */
17998 cfun->function_end_locus = input_location;
18000 /* Complain about parameters that are only set, but never otherwise used. */
18001 if (warn_unused_but_set_parameter
18002 && !processing_template_decl
18003 && errorcount == unused_but_set_errorcount
18004 && !DECL_CLONED_FUNCTION_P (fndecl))
18006 tree decl;
18008 for (decl = DECL_ARGUMENTS (fndecl);
18009 decl;
18010 decl = DECL_CHAIN (decl))
18011 if (TREE_USED (decl)
18012 && TREE_CODE (decl) == PARM_DECL
18013 && !DECL_READ_P (decl)
18014 && DECL_NAME (decl)
18015 && !DECL_ARTIFICIAL (decl)
18016 && !warning_suppressed_p (decl,OPT_Wunused_but_set_parameter)
18017 && !DECL_IN_SYSTEM_HEADER (decl)
18018 && TREE_TYPE (decl) != error_mark_node
18019 && !TYPE_REF_P (TREE_TYPE (decl))
18020 && (!CLASS_TYPE_P (TREE_TYPE (decl))
18021 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl))))
18022 warning_at (DECL_SOURCE_LOCATION (decl),
18023 OPT_Wunused_but_set_parameter,
18024 "parameter %qD set but not used", decl);
18025 unused_but_set_errorcount = errorcount;
18028 /* Complain about locally defined typedefs that are not used in this
18029 function. */
18030 maybe_warn_unused_local_typedefs ();
18032 /* Possibly warn about unused parameters. */
18033 if (warn_unused_parameter
18034 && !processing_template_decl
18035 && !DECL_CLONED_FUNCTION_P (fndecl))
18036 do_warn_unused_parameter (fndecl);
18038 /* Genericize before inlining. */
18039 if (!processing_template_decl
18040 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
18041 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18042 cp_genericize (fndecl);
18044 /* Emit the resumer and destroyer functions now, providing that we have
18045 not encountered some fatal error. */
18046 if (coro_emit_helpers)
18048 emit_coro_helper (resumer);
18049 emit_coro_helper (destroyer);
18052 cleanup:
18053 /* We're leaving the context of this function, so zap cfun. It's still in
18054 DECL_STRUCT_FUNCTION, and we'll restore it in tree_rest_of_compilation. */
18055 set_cfun (NULL);
18056 current_function_decl = NULL;
18058 /* If this is an in-class inline definition, we may have to pop the
18059 bindings for the template parameters that we added in
18060 maybe_begin_member_template_processing when start_function was
18061 called. */
18062 if (inline_p)
18063 maybe_end_member_template_processing ();
18065 /* Leave the scope of the class. */
18066 if (ctype)
18067 pop_nested_class ();
18069 --function_depth;
18071 /* Clean up. */
18072 current_function_decl = NULL_TREE;
18074 invoke_plugin_callbacks (PLUGIN_FINISH_PARSE_FUNCTION, fndecl);
18075 return fndecl;
18078 /* Create the FUNCTION_DECL for a function definition.
18079 DECLSPECS and DECLARATOR are the parts of the declaration;
18080 they describe the return type and the name of the function,
18081 but twisted together in a fashion that parallels the syntax of C.
18083 This function creates a binding context for the function body
18084 as well as setting up the FUNCTION_DECL in current_function_decl.
18086 Returns a FUNCTION_DECL on success.
18088 If the DECLARATOR is not suitable for a function (it defines a datum
18089 instead), we return 0, which tells yyparse to report a parse error.
18091 May return void_type_node indicating that this method is actually
18092 a friend. See grokfield for more details.
18094 Came here with a `.pushlevel' .
18096 DO NOT MAKE ANY CHANGES TO THIS CODE WITHOUT MAKING CORRESPONDING
18097 CHANGES TO CODE IN `grokfield'. */
18099 tree
18100 grokmethod (cp_decl_specifier_seq *declspecs,
18101 const cp_declarator *declarator, tree attrlist)
18103 tree fndecl = grokdeclarator (declarator, declspecs, MEMFUNCDEF, 0,
18104 &attrlist);
18106 if (fndecl == error_mark_node)
18107 return error_mark_node;
18109 if (attrlist)
18110 cplus_decl_attributes (&fndecl, attrlist, 0);
18112 /* Pass friends other than inline friend functions back. */
18113 if (fndecl == void_type_node)
18114 return fndecl;
18116 if (DECL_IN_AGGR_P (fndecl))
18118 if (DECL_CLASS_SCOPE_P (fndecl))
18119 error ("%qD is already defined in class %qT", fndecl,
18120 DECL_CONTEXT (fndecl));
18121 return error_mark_node;
18124 check_template_shadow (fndecl);
18126 /* p1779 ABI-Isolation makes inline not a default for in-class
18127 definitions in named module purview. If the user explicitly
18128 made it inline, grokdeclarator will already have done the right
18129 things. */
18130 if ((!named_module_purview_p ()
18131 || flag_module_implicit_inline
18132 /* Lambda's operator function remains inline. */
18133 || LAMBDA_TYPE_P (DECL_CONTEXT (fndecl)))
18134 /* If the user explicitly asked for this to be inline, we don't
18135 need to do more, but more importantly we want to warn if we
18136 can't inline it. */
18137 && !DECL_DECLARED_INLINE_P (fndecl))
18139 if (TREE_PUBLIC (fndecl))
18140 DECL_COMDAT (fndecl) = 1;
18141 DECL_DECLARED_INLINE_P (fndecl) = 1;
18142 /* It's ok if we can't inline this. */
18143 DECL_NO_INLINE_WARNING_P (fndecl) = 1;
18146 /* We process method specializations in finish_struct_1. */
18147 if (processing_template_decl && !DECL_TEMPLATE_SPECIALIZATION (fndecl))
18149 /* Avoid calling decl_spec_seq... until we have to. */
18150 bool friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
18151 fndecl = push_template_decl (fndecl, friendp);
18152 if (fndecl == error_mark_node)
18153 return fndecl;
18156 if (DECL_CHAIN (fndecl) && !decl_spec_seq_has_spec_p (declspecs, ds_friend))
18158 fndecl = copy_node (fndecl);
18159 TREE_CHAIN (fndecl) = NULL_TREE;
18162 cp_finish_decl (fndecl, NULL_TREE, false, NULL_TREE, 0);
18164 DECL_IN_AGGR_P (fndecl) = 1;
18165 return fndecl;
18169 /* VAR is a VAR_DECL. If its type is incomplete, remember VAR so that
18170 we can lay it out later, when and if its type becomes complete.
18172 Also handle constexpr variables where the initializer involves
18173 an unlowered PTRMEM_CST because the class isn't complete yet. */
18175 void
18176 maybe_register_incomplete_var (tree var)
18178 gcc_assert (VAR_P (var));
18180 /* Keep track of variables with incomplete types. */
18181 if (!processing_template_decl && TREE_TYPE (var) != error_mark_node
18182 && DECL_EXTERNAL (var))
18184 tree inner_type = TREE_TYPE (var);
18186 while (TREE_CODE (inner_type) == ARRAY_TYPE)
18187 inner_type = TREE_TYPE (inner_type);
18188 inner_type = TYPE_MAIN_VARIANT (inner_type);
18190 if ((!COMPLETE_TYPE_P (inner_type) && CLASS_TYPE_P (inner_type))
18191 /* RTTI TD entries are created while defining the type_info. */
18192 || (TYPE_LANG_SPECIFIC (inner_type)
18193 && TYPE_BEING_DEFINED (inner_type)))
18195 incomplete_var iv = {var, inner_type};
18196 vec_safe_push (incomplete_vars, iv);
18198 else if (!(DECL_LANG_SPECIFIC (var) && DECL_TEMPLATE_INFO (var))
18199 && decl_constant_var_p (var)
18200 && (TYPE_PTRMEM_P (inner_type) || CLASS_TYPE_P (inner_type)))
18202 /* When the outermost open class is complete we can resolve any
18203 pointers-to-members. */
18204 tree context = outermost_open_class ();
18205 incomplete_var iv = {var, context};
18206 vec_safe_push (incomplete_vars, iv);
18211 /* Called when a class type (given by TYPE) is defined. If there are
18212 any existing VAR_DECLs whose type has been completed by this
18213 declaration, update them now. */
18215 void
18216 complete_vars (tree type)
18218 unsigned ix;
18219 incomplete_var *iv;
18221 for (ix = 0; vec_safe_iterate (incomplete_vars, ix, &iv); )
18223 if (same_type_p (type, iv->incomplete_type))
18225 tree var = iv->decl;
18226 tree type = TREE_TYPE (var);
18228 if (type != error_mark_node
18229 && (TYPE_MAIN_VARIANT (strip_array_types (type))
18230 == iv->incomplete_type))
18232 /* Complete the type of the variable. */
18233 complete_type (type);
18234 cp_apply_type_quals_to_decl (cp_type_quals (type), var);
18235 if (COMPLETE_TYPE_P (type))
18236 layout_var_decl (var);
18239 /* Remove this entry from the list. */
18240 incomplete_vars->unordered_remove (ix);
18242 else
18243 ix++;
18247 /* If DECL is of a type which needs a cleanup, build and return an
18248 expression to perform that cleanup here. Return NULL_TREE if no
18249 cleanup need be done. DECL can also be a _REF when called from
18250 split_nonconstant_init_1. */
18252 tree
18253 cxx_maybe_build_cleanup (tree decl, tsubst_flags_t complain)
18255 tree type;
18256 tree attr;
18257 tree cleanup;
18259 /* Assume no cleanup is required. */
18260 cleanup = NULL_TREE;
18262 if (error_operand_p (decl))
18263 return cleanup;
18265 /* Handle "__attribute__((cleanup))". We run the cleanup function
18266 before the destructor since the destructor is what actually
18267 terminates the lifetime of the object. */
18268 if (DECL_P (decl))
18269 attr = lookup_attribute ("cleanup", DECL_ATTRIBUTES (decl));
18270 else
18271 attr = NULL_TREE;
18272 if (attr)
18274 tree id;
18275 tree fn;
18276 tree arg;
18278 /* Get the name specified by the user for the cleanup function. */
18279 id = TREE_VALUE (TREE_VALUE (attr));
18280 /* Look up the name to find the cleanup function to call. It is
18281 important to use lookup_name here because that is what is
18282 used in c-common.cc:handle_cleanup_attribute when performing
18283 initial checks on the attribute. Note that those checks
18284 include ensuring that the function found is not an overloaded
18285 function, or an object with an overloaded call operator,
18286 etc.; we can rely on the fact that the function found is an
18287 ordinary FUNCTION_DECL. */
18288 fn = lookup_name (id);
18289 arg = build_address (decl);
18290 if (!mark_used (decl, complain) && !(complain & tf_error))
18291 return error_mark_node;
18292 cleanup = cp_build_function_call_nary (fn, complain, arg, NULL_TREE);
18293 if (cleanup == error_mark_node)
18294 return error_mark_node;
18296 /* Handle ordinary C++ destructors. */
18297 type = TREE_TYPE (decl);
18298 if (type_build_dtor_call (type))
18300 int flags = LOOKUP_NORMAL|LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR;
18301 tree addr;
18302 tree call;
18304 if (TREE_CODE (type) == ARRAY_TYPE)
18305 addr = decl;
18306 else
18307 addr = build_address (decl);
18309 call = build_delete (input_location, TREE_TYPE (addr), addr,
18310 sfk_complete_destructor, flags, 0, complain);
18311 if (call == error_mark_node)
18312 cleanup = error_mark_node;
18313 else if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
18314 /* Discard the call. */;
18315 else if (decl_maybe_constant_destruction (decl, type)
18316 && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
18317 cxx_constant_dtor (call, decl);
18318 else if (cleanup)
18319 cleanup = cp_build_compound_expr (cleanup, call, complain);
18320 else
18321 cleanup = call;
18324 /* build_delete sets the location of the destructor call to the
18325 current location, even though the destructor is going to be
18326 called later, at the end of the current scope. This can lead to
18327 a "jumpy" behavior for users of debuggers when they step around
18328 the end of the block. So let's unset the location of the
18329 destructor call instead. */
18330 protected_set_expr_location (cleanup, UNKNOWN_LOCATION);
18331 if (cleanup && CONVERT_EXPR_P (cleanup))
18332 protected_set_expr_location (TREE_OPERAND (cleanup, 0), UNKNOWN_LOCATION);
18334 if (cleanup
18335 && DECL_P (decl)
18336 && !lookup_attribute ("warn_unused", TYPE_ATTRIBUTES (TREE_TYPE (decl)))
18337 /* Treat objects with destructors as used; the destructor may do
18338 something substantive. */
18339 && !mark_used (decl, complain) && !(complain & tf_error))
18340 return error_mark_node;
18342 if (cleanup && cfun && !processing_template_decl
18343 && !expr_noexcept_p (cleanup, tf_none))
18344 cp_function_chain->throwing_cleanup = true;
18346 return cleanup;
18350 /* Return the FUNCTION_TYPE that corresponds to MEMFNTYPE, which can be a
18351 FUNCTION_DECL, METHOD_TYPE, FUNCTION_TYPE, pointer or reference to
18352 METHOD_TYPE or FUNCTION_TYPE, or pointer to member function. */
18354 tree
18355 static_fn_type (tree memfntype)
18357 tree fntype;
18358 tree args;
18360 if (TYPE_PTRMEMFUNC_P (memfntype))
18361 memfntype = TYPE_PTRMEMFUNC_FN_TYPE (memfntype);
18362 if (INDIRECT_TYPE_P (memfntype)
18363 || TREE_CODE (memfntype) == FUNCTION_DECL)
18364 memfntype = TREE_TYPE (memfntype);
18365 if (TREE_CODE (memfntype) == FUNCTION_TYPE)
18366 return memfntype;
18367 gcc_assert (TREE_CODE (memfntype) == METHOD_TYPE);
18368 args = TYPE_ARG_TYPES (memfntype);
18369 fntype = build_function_type (TREE_TYPE (memfntype), TREE_CHAIN (args));
18370 fntype = apply_memfn_quals (fntype, type_memfn_quals (memfntype));
18371 fntype = (cp_build_type_attribute_variant
18372 (fntype, TYPE_ATTRIBUTES (memfntype)));
18373 fntype = cxx_copy_lang_qualifiers (fntype, memfntype);
18374 return fntype;
18377 /* DECL was originally constructed as a non-static member function,
18378 but turned out to be static. Update it accordingly. */
18380 void
18381 revert_static_member_fn (tree decl)
18383 tree stype = static_fn_type (decl);
18384 cp_cv_quals quals = type_memfn_quals (stype);
18385 cp_ref_qualifier rqual = type_memfn_rqual (stype);
18387 if (quals != TYPE_UNQUALIFIED || rqual != REF_QUAL_NONE)
18388 stype = apply_memfn_quals (stype, TYPE_UNQUALIFIED, REF_QUAL_NONE);
18390 TREE_TYPE (decl) = stype;
18392 if (DECL_ARGUMENTS (decl))
18393 DECL_ARGUMENTS (decl) = DECL_CHAIN (DECL_ARGUMENTS (decl));
18394 DECL_STATIC_FUNCTION_P (decl) = 1;
18397 /* Return which tree structure is used by T, or TS_CP_GENERIC if T is
18398 one of the language-independent trees. */
18400 enum cp_tree_node_structure_enum
18401 cp_tree_node_structure (union lang_tree_node * t)
18403 switch (TREE_CODE (&t->generic))
18405 case ARGUMENT_PACK_SELECT: return TS_CP_ARGUMENT_PACK_SELECT;
18406 case BASELINK: return TS_CP_BASELINK;
18407 case CONSTRAINT_INFO: return TS_CP_CONSTRAINT_INFO;
18408 case DEFERRED_NOEXCEPT: return TS_CP_DEFERRED_NOEXCEPT;
18409 case DEFERRED_PARSE: return TS_CP_DEFERRED_PARSE;
18410 case IDENTIFIER_NODE: return TS_CP_IDENTIFIER;
18411 case LAMBDA_EXPR: return TS_CP_LAMBDA_EXPR;
18412 case BINDING_VECTOR: return TS_CP_BINDING_VECTOR;
18413 case OVERLOAD: return TS_CP_OVERLOAD;
18414 case PTRMEM_CST: return TS_CP_PTRMEM;
18415 case STATIC_ASSERT: return TS_CP_STATIC_ASSERT;
18416 case TEMPLATE_DECL: return TS_CP_TEMPLATE_DECL;
18417 case TEMPLATE_INFO: return TS_CP_TEMPLATE_INFO;
18418 case TEMPLATE_PARM_INDEX: return TS_CP_TPI;
18419 case TRAIT_EXPR: return TS_CP_TRAIT_EXPR;
18420 case USERDEF_LITERAL: return TS_CP_USERDEF_LITERAL;
18421 default: return TS_CP_GENERIC;
18425 /* Build the void_list_node (void_type_node having been created). */
18426 tree
18427 build_void_list_node (void)
18429 tree t = build_tree_list (NULL_TREE, void_type_node);
18430 return t;
18433 bool
18434 cp_missing_noreturn_ok_p (tree decl)
18436 /* A missing noreturn is ok for the `main' function. */
18437 return DECL_MAIN_P (decl);
18440 /* Return the decl used to identify the COMDAT group into which DECL should
18441 be placed. */
18443 tree
18444 cxx_comdat_group (tree decl)
18446 /* Virtual tables, construction virtual tables, and virtual table
18447 tables all go in a single COMDAT group, named after the primary
18448 virtual table. */
18449 if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
18450 decl = CLASSTYPE_VTABLES (DECL_CONTEXT (decl));
18451 /* For all other DECLs, the COMDAT group is the mangled name of the
18452 declaration itself. */
18453 else
18455 while (DECL_THUNK_P (decl))
18457 /* If TARGET_USE_LOCAL_THUNK_ALIAS_P, use_thunk puts the thunk
18458 into the same section as the target function. In that case
18459 we must return target's name. */
18460 tree target = THUNK_TARGET (decl);
18461 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (target)
18462 && DECL_SECTION_NAME (target) != NULL
18463 && DECL_ONE_ONLY (target))
18464 decl = target;
18465 else
18466 break;
18470 return decl;
18473 /* Returns the return type for FN as written by the user, which may include
18474 a placeholder for a deduced return type. */
18476 tree
18477 fndecl_declared_return_type (tree fn)
18479 fn = STRIP_TEMPLATE (fn);
18480 if (FNDECL_USED_AUTO (fn))
18481 return DECL_SAVED_AUTO_RETURN_TYPE (fn);
18483 return TREE_TYPE (TREE_TYPE (fn));
18486 /* Returns true iff DECL is a variable or function declared with an auto type
18487 that has not yet been deduced to a real type. */
18489 bool
18490 undeduced_auto_decl (tree decl)
18492 if (cxx_dialect < cxx11)
18493 return false;
18494 STRIP_ANY_LOCATION_WRAPPER (decl);
18495 return ((VAR_OR_FUNCTION_DECL_P (decl)
18496 || TREE_CODE (decl) == TEMPLATE_DECL)
18497 && type_uses_auto (TREE_TYPE (decl)));
18500 /* Complain if DECL has an undeduced return type. */
18502 bool
18503 require_deduced_type (tree decl, tsubst_flags_t complain)
18505 if (undeduced_auto_decl (decl))
18507 if (warning_suppressed_p (decl) && seen_error ())
18508 /* We probably already complained about deduction failure. */;
18509 else if (complain & tf_error)
18510 error ("use of %qD before deduction of %<auto%>", decl);
18511 note_failed_type_completion_for_satisfaction (decl);
18512 return false;
18514 return true;
18517 /* Create a representation of the explicit-specifier with
18518 constant-expression of EXPR. COMPLAIN is as for tsubst. */
18520 tree
18521 build_explicit_specifier (tree expr, tsubst_flags_t complain)
18523 if (check_for_bare_parameter_packs (expr))
18524 return error_mark_node;
18526 if (instantiation_dependent_expression_p (expr))
18527 /* Wait for instantiation, tsubst_function_decl will handle it. */
18528 return expr;
18530 expr = build_converted_constant_bool_expr (expr, complain);
18531 expr = instantiate_non_dependent_expr_sfinae (expr, complain);
18532 expr = cxx_constant_value (expr);
18533 return expr;
18536 #include "gt-cp-decl.h"