c++: result location and explicit inst [PR108496]
[official-gcc.git] / gcc / cp / decl.cc
blobd606b31d7a7afeee1d5bbaf31aa074eb7dea3528
1 /* Process declarations and variables for -*- C++ -*- compiler.
2 Copyright (C) 1988-2023 Free Software Foundation, Inc.
3 Contributed by Michael Tiemann (tiemann@cygnus.com)
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
22 /* Process declarations and symbol lookup for C++ front end.
23 Also constructs types; the standard scalar types at initialization,
24 and structure, union, array and enum types when they are declared. */
26 /* ??? not all decl nodes are given the most useful possible
27 line numbers. For example, the CONST_DECLs for enum values. */
29 #include "config.h"
30 #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;
226 bool in_stmt_expr;
229 #define named_labels cp_function_chain->x_named_labels
231 /* The number of function bodies which we are currently processing.
232 (Zero if we are at namespace scope, one inside the body of a
233 function, two inside the body of a function in a local class, etc.) */
234 int function_depth;
236 /* Whether the exception-specifier is part of a function type (i.e. C++17). */
237 bool flag_noexcept_type;
239 /* States indicating how grokdeclarator() should handle declspecs marked
240 with __attribute__((deprecated)). An object declared as
241 __attribute__((deprecated)) suppresses warnings of uses of other
242 deprecated items. */
243 enum deprecated_states deprecated_state = DEPRECATED_NORMAL;
246 /* A list of VAR_DECLs whose type was incomplete at the time the
247 variable was declared. */
249 struct GTY(()) incomplete_var {
250 tree decl;
251 tree incomplete_type;
255 static GTY(()) vec<incomplete_var, va_gc> *incomplete_vars;
257 /* Returns the kind of template specialization we are currently
258 processing, given that it's declaration contained N_CLASS_SCOPES
259 explicit scope qualifications. */
261 tmpl_spec_kind
262 current_tmpl_spec_kind (int n_class_scopes)
264 int n_template_parm_scopes = 0;
265 int seen_specialization_p = 0;
266 int innermost_specialization_p = 0;
267 cp_binding_level *b;
269 /* Scan through the template parameter scopes. */
270 for (b = current_binding_level;
271 b->kind == sk_template_parms;
272 b = b->level_chain)
274 /* If we see a specialization scope inside a parameter scope,
275 then something is wrong. That corresponds to a declaration
276 like:
278 template <class T> template <> ...
280 which is always invalid since [temp.expl.spec] forbids the
281 specialization of a class member template if the enclosing
282 class templates are not explicitly specialized as well. */
283 if (b->explicit_spec_p)
285 if (n_template_parm_scopes == 0)
286 innermost_specialization_p = 1;
287 else
288 seen_specialization_p = 1;
290 else if (seen_specialization_p == 1)
291 return tsk_invalid_member_spec;
293 ++n_template_parm_scopes;
296 /* Handle explicit instantiations. */
297 if (processing_explicit_instantiation)
299 if (n_template_parm_scopes != 0)
300 /* We've seen a template parameter list during an explicit
301 instantiation. For example:
303 template <class T> template void f(int);
305 This is erroneous. */
306 return tsk_invalid_expl_inst;
307 else
308 return tsk_expl_inst;
311 if (n_template_parm_scopes < n_class_scopes)
312 /* We've not seen enough template headers to match all the
313 specialized classes present. For example:
315 template <class T> void R<T>::S<T>::f(int);
317 This is invalid; there needs to be one set of template
318 parameters for each class. */
319 return tsk_insufficient_parms;
320 else if (n_template_parm_scopes == n_class_scopes)
321 /* We're processing a non-template declaration (even though it may
322 be a member of a template class.) For example:
324 template <class T> void S<T>::f(int);
326 The `class T' matches the `S<T>', leaving no template headers
327 corresponding to the `f'. */
328 return tsk_none;
329 else if (n_template_parm_scopes > n_class_scopes + 1)
330 /* We've got too many template headers. For example:
332 template <> template <class T> void f (T);
334 There need to be more enclosing classes. */
335 return tsk_excessive_parms;
336 else
337 /* This must be a template. It's of the form:
339 template <class T> template <class U> void S<T>::f(U);
341 This is a specialization if the innermost level was a
342 specialization; otherwise it's just a definition of the
343 template. */
344 return innermost_specialization_p ? tsk_expl_spec : tsk_template;
347 /* Exit the current scope. */
349 void
350 finish_scope (void)
352 poplevel (0, 0, 0);
355 /* When a label goes out of scope, check to see if that label was used
356 in a valid manner, and issue any appropriate warnings or errors. */
358 static void
359 check_label_used (tree label)
361 if (!processing_template_decl)
363 if (DECL_INITIAL (label) == NULL_TREE)
365 location_t location;
367 error ("label %q+D used but not defined", label);
368 location = input_location;
369 /* FIXME want (LOCATION_FILE (input_location), (line)0) */
370 /* Avoid crashing later. */
371 define_label (location, DECL_NAME (label));
373 else
374 warn_for_unused_label (label);
378 /* Helper function to sort named label entries in a vector by DECL_UID. */
380 static int
381 sort_labels (const void *a, const void *b)
383 tree label1 = *(tree const *) a;
384 tree label2 = *(tree const *) b;
386 /* DECL_UIDs can never be equal. */
387 return DECL_UID (label1) > DECL_UID (label2) ? -1 : +1;
390 /* At the end of a function, all labels declared within the function
391 go out of scope. BLOCK is the top-level block for the
392 function. */
394 static void
395 pop_labels (tree block)
397 if (!named_labels)
398 return;
400 /* We need to add the labels to the block chain, so debug
401 information is emitted. But, we want the order to be stable so
402 need to sort them first. Otherwise the debug output could be
403 randomly ordered. I guess it's mostly stable, unless the hash
404 table implementation changes. */
405 auto_vec<tree, 32> labels (named_labels->elements ());
406 hash_table<named_label_hash>::iterator end (named_labels->end ());
407 for (hash_table<named_label_hash>::iterator iter
408 (named_labels->begin ()); iter != end; ++iter)
410 named_label_entry *ent = *iter;
412 gcc_checking_assert (!ent->outer);
413 if (ent->label_decl)
414 labels.quick_push (ent->label_decl);
415 ggc_free (ent);
417 named_labels = NULL;
418 labels.qsort (sort_labels);
420 while (labels.length ())
422 tree label = labels.pop ();
424 DECL_CHAIN (label) = BLOCK_VARS (block);
425 BLOCK_VARS (block) = label;
427 check_label_used (label);
431 /* At the end of a block with local labels, restore the outer definition. */
433 static void
434 pop_local_label (tree id, tree label)
436 check_label_used (label);
437 named_label_entry **slot = named_labels->find_slot_with_hash
438 (id, IDENTIFIER_HASH_VALUE (id), NO_INSERT);
439 named_label_entry *ent = *slot;
441 if (ent->outer)
442 ent = ent->outer;
443 else
445 ent = ggc_cleared_alloc<named_label_entry> ();
446 ent->name = id;
448 *slot = ent;
451 /* The following two routines are used to interface to Objective-C++.
452 The binding level is purposely treated as an opaque type. */
454 void *
455 objc_get_current_scope (void)
457 return current_binding_level;
460 /* The following routine is used by the NeXT-style SJLJ exceptions;
461 variables get marked 'volatile' so as to not be clobbered by
462 _setjmp()/_longjmp() calls. All variables in the current scope,
463 as well as parent scopes up to (but not including) ENCLOSING_BLK
464 shall be thusly marked. */
466 void
467 objc_mark_locals_volatile (void *enclosing_blk)
469 cp_binding_level *scope;
471 for (scope = current_binding_level;
472 scope && scope != enclosing_blk;
473 scope = scope->level_chain)
475 tree decl;
477 for (decl = scope->names; decl; decl = TREE_CHAIN (decl))
478 objc_volatilize_decl (decl);
480 /* Do not climb up past the current function. */
481 if (scope->kind == sk_function_parms)
482 break;
486 /* True if B is the level for the condition of a constexpr if. */
488 static bool
489 level_for_constexpr_if (cp_binding_level *b)
491 return (b->kind == sk_cond && b->this_entity
492 && TREE_CODE (b->this_entity) == IF_STMT
493 && IF_STMT_CONSTEXPR_P (b->this_entity));
496 /* True if B is the level for the condition of a consteval if. */
498 static bool
499 level_for_consteval_if (cp_binding_level *b)
501 return (b->kind == sk_cond && b->this_entity
502 && TREE_CODE (b->this_entity) == IF_STMT
503 && IF_STMT_CONSTEVAL_P (b->this_entity));
506 /* Update data for defined and undefined labels when leaving a scope. */
509 poplevel_named_label_1 (named_label_entry **slot, cp_binding_level *bl)
511 named_label_entry *ent = *slot;
512 cp_binding_level *obl = bl->level_chain;
514 if (ent->binding_level == bl)
516 tree decl;
518 /* ENT->NAMES_IN_SCOPE may contain a mixture of DECLs and
519 TREE_LISTs representing OVERLOADs, so be careful. */
520 for (decl = ent->names_in_scope; decl; decl = (DECL_P (decl)
521 ? DECL_CHAIN (decl)
522 : TREE_CHAIN (decl)))
523 if (decl_jump_unsafe (decl))
524 vec_safe_push (ent->bad_decls, decl);
526 ent->binding_level = obl;
527 ent->names_in_scope = obl->names;
528 switch (bl->kind)
530 case sk_try:
531 ent->in_try_scope = true;
532 break;
533 case sk_catch:
534 ent->in_catch_scope = true;
535 break;
536 case sk_omp:
537 ent->in_omp_scope = true;
538 break;
539 case sk_transaction:
540 ent->in_transaction_scope = true;
541 break;
542 case sk_stmt_expr:
543 ent->in_stmt_expr = true;
544 break;
545 case sk_block:
546 if (level_for_constexpr_if (bl->level_chain))
547 ent->in_constexpr_if = true;
548 else if (level_for_consteval_if (bl->level_chain))
549 ent->in_consteval_if = true;
550 break;
551 default:
552 break;
555 else if (ent->uses)
557 struct named_label_use_entry *use;
559 for (use = ent->uses; use ; use = use->next)
560 if (use->binding_level == bl)
562 use->binding_level = obl;
563 use->names_in_scope = obl->names;
564 if (bl->kind == sk_omp)
565 use->in_omp_scope = true;
569 return 1;
572 /* Saved errorcount to avoid -Wunused-but-set-{parameter,variable} warnings
573 when errors were reported, except for -Werror-unused-but-set-*. */
574 static int unused_but_set_errorcount;
576 /* Exit a binding level.
577 Pop the level off, and restore the state of the identifier-decl mappings
578 that were in effect when this level was entered.
580 If KEEP == 1, this level had explicit declarations, so
581 and create a "block" (a BLOCK node) for the level
582 to record its declarations and subblocks for symbol table output.
584 If FUNCTIONBODY is nonzero, this level is the body of a function,
585 so create a block as if KEEP were set and also clear out all
586 label names.
588 If REVERSE is nonzero, reverse the order of decls before putting
589 them into the BLOCK. */
591 tree
592 poplevel (int keep, int reverse, int functionbody)
594 tree link;
595 /* The chain of decls was accumulated in reverse order.
596 Put it into forward order, just for cleanliness. */
597 tree decls;
598 tree subblocks;
599 tree block;
600 tree decl;
601 scope_kind kind;
603 auto_cond_timevar tv (TV_NAME_LOOKUP);
604 restart:
606 block = NULL_TREE;
608 gcc_assert (current_binding_level->kind != sk_class
609 && current_binding_level->kind != sk_namespace);
611 if (current_binding_level->kind == sk_cleanup)
612 functionbody = 0;
613 subblocks = functionbody >= 0 ? current_binding_level->blocks : 0;
615 gcc_assert (!vec_safe_length (current_binding_level->class_shadowed));
617 /* We used to use KEEP == 2 to indicate that the new block should go
618 at the beginning of the list of blocks at this binding level,
619 rather than the end. This hack is no longer used. */
620 gcc_assert (keep == 0 || keep == 1);
622 if (current_binding_level->keep)
623 keep = 1;
625 /* Any uses of undefined labels, and any defined labels, now operate
626 under constraints of next binding contour. */
627 if (cfun && !functionbody && named_labels)
628 named_labels->traverse<cp_binding_level *, poplevel_named_label_1>
629 (current_binding_level);
631 /* Get the decls in the order they were written.
632 Usually current_binding_level->names is in reverse order.
633 But parameter decls were previously put in forward order. */
635 decls = current_binding_level->names;
636 if (reverse)
638 decls = nreverse (decls);
639 current_binding_level->names = decls;
642 /* If there were any declarations or structure tags in that level,
643 or if this level is a function body,
644 create a BLOCK to record them for the life of this function. */
645 block = NULL_TREE;
646 /* Avoid function body block if possible. */
647 if (functionbody && subblocks && BLOCK_CHAIN (subblocks) == NULL_TREE)
648 keep = 0;
649 else if (keep == 1 || functionbody)
650 block = make_node (BLOCK);
651 if (block != NULL_TREE)
653 BLOCK_VARS (block) = decls;
654 BLOCK_SUBBLOCKS (block) = subblocks;
657 /* In each subblock, record that this is its superior. */
658 if (keep >= 0)
659 for (link = subblocks; link; link = BLOCK_CHAIN (link))
660 BLOCK_SUPERCONTEXT (link) = block;
662 /* Before we remove the declarations first check for unused variables. */
663 if ((warn_unused_variable || warn_unused_but_set_variable)
664 && current_binding_level->kind != sk_template_parms
665 && !processing_template_decl)
666 for (tree d = get_local_decls (); d; d = TREE_CHAIN (d))
668 /* There are cases where D itself is a TREE_LIST. See in
669 push_local_binding where the list of decls returned by
670 getdecls is built. */
671 decl = TREE_CODE (d) == TREE_LIST ? TREE_VALUE (d) : d;
673 tree type = TREE_TYPE (decl);
674 if (VAR_P (decl)
675 && (! TREE_USED (decl) || !DECL_READ_P (decl))
676 && ! DECL_IN_SYSTEM_HEADER (decl)
677 /* For structured bindings, consider only real variables, not
678 subobjects. */
679 && (DECL_DECOMPOSITION_P (decl) ? !DECL_DECOMP_BASE (decl)
680 : (DECL_NAME (decl) && !DECL_ARTIFICIAL (decl)))
681 && type != error_mark_node
682 && (!CLASS_TYPE_P (type)
683 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
684 || lookup_attribute ("warn_unused",
685 TYPE_ATTRIBUTES (TREE_TYPE (decl)))))
687 if (! TREE_USED (decl))
689 if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
690 warning_at (DECL_SOURCE_LOCATION (decl),
691 OPT_Wunused_variable,
692 "unused structured binding declaration");
693 else
694 warning_at (DECL_SOURCE_LOCATION (decl),
695 OPT_Wunused_variable, "unused variable %qD", decl);
697 else if (DECL_CONTEXT (decl) == current_function_decl
698 // For -Wunused-but-set-variable leave references alone.
699 && !TYPE_REF_P (TREE_TYPE (decl))
700 && errorcount == unused_but_set_errorcount)
702 if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
703 warning_at (DECL_SOURCE_LOCATION (decl),
704 OPT_Wunused_but_set_variable, "structured "
705 "binding declaration set but not used");
706 else
707 warning_at (DECL_SOURCE_LOCATION (decl),
708 OPT_Wunused_but_set_variable,
709 "variable %qD set but not used", decl);
710 unused_but_set_errorcount = errorcount;
715 /* Remove declarations for all the DECLs in this level. */
716 for (link = decls; link; link = TREE_CHAIN (link))
718 tree name;
719 if (TREE_CODE (link) == TREE_LIST)
721 decl = TREE_VALUE (link);
722 name = TREE_PURPOSE (link);
723 gcc_checking_assert (name);
725 else
727 decl = link;
728 name = DECL_NAME (decl);
731 /* Remove the binding. */
732 if (TREE_CODE (decl) == LABEL_DECL)
733 pop_local_label (name, decl);
734 else
735 pop_local_binding (name, decl);
738 /* Restore the IDENTIFIER_TYPE_VALUEs. */
739 for (link = current_binding_level->type_shadowed;
740 link; link = TREE_CHAIN (link))
741 SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (link), TREE_VALUE (link));
743 /* There may be OVERLOADs (wrapped in TREE_LISTs) on the BLOCK_VARs
744 list if a `using' declaration put them there. The debugging
745 back ends won't understand OVERLOAD, so we remove them here.
746 Because the BLOCK_VARS are (temporarily) shared with
747 CURRENT_BINDING_LEVEL->NAMES we must do this fixup after we have
748 popped all the bindings. Also remove undeduced 'auto' decls,
749 which LTO doesn't understand, and can't have been used by anything. */
750 if (block)
752 tree* d;
754 for (d = &BLOCK_VARS (block); *d; )
756 if (TREE_CODE (*d) == TREE_LIST
757 || (!processing_template_decl
758 && undeduced_auto_decl (*d)))
759 *d = TREE_CHAIN (*d);
760 else
761 d = &DECL_CHAIN (*d);
765 /* If the level being exited is the top level of a function,
766 check over all the labels. */
767 if (functionbody)
769 if (block)
771 /* Since this is the top level block of a function, the vars are
772 the function's parameters. Don't leave them in the BLOCK
773 because they are found in the FUNCTION_DECL instead. */
774 BLOCK_VARS (block) = 0;
775 pop_labels (block);
777 else
778 pop_labels (subblocks);
781 kind = current_binding_level->kind;
782 if (kind == sk_cleanup)
784 tree stmt;
786 /* If this is a temporary binding created for a cleanup, then we'll
787 have pushed a statement list level. Pop that, create a new
788 BIND_EXPR for the block, and insert it into the stream. */
789 stmt = pop_stmt_list (current_binding_level->statement_list);
790 stmt = c_build_bind_expr (input_location, block, stmt);
791 add_stmt (stmt);
794 leave_scope ();
795 if (functionbody)
797 /* The current function is being defined, so its DECL_INITIAL
798 should be error_mark_node. */
799 gcc_assert (DECL_INITIAL (current_function_decl) == error_mark_node);
800 DECL_INITIAL (current_function_decl) = block ? block : subblocks;
801 if (subblocks)
803 if (FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
805 if (BLOCK_SUBBLOCKS (subblocks))
806 BLOCK_OUTER_CURLY_BRACE_P (BLOCK_SUBBLOCKS (subblocks)) = 1;
808 else
809 BLOCK_OUTER_CURLY_BRACE_P (subblocks) = 1;
812 else if (block)
813 current_binding_level->blocks
814 = block_chainon (current_binding_level->blocks, block);
816 /* If we did not make a block for the level just exited,
817 any blocks made for inner levels
818 (since they cannot be recorded as subblocks in that level)
819 must be carried forward so they will later become subblocks
820 of something else. */
821 else if (subblocks)
822 current_binding_level->blocks
823 = block_chainon (current_binding_level->blocks, subblocks);
825 /* Each and every BLOCK node created here in `poplevel' is important
826 (e.g. for proper debugging information) so if we created one
827 earlier, mark it as "used". */
828 if (block)
829 TREE_USED (block) = 1;
831 /* All temporary bindings created for cleanups are popped silently. */
832 if (kind == sk_cleanup)
833 goto restart;
835 return block;
838 /* Call wrapup_globals_declarations for the globals in NAMESPACE. */
839 /* Diagnose odr-used extern inline variables without definitions
840 in the current TU. */
843 wrapup_namespace_globals ()
845 if (vec<tree, va_gc> *statics = static_decls)
847 for (tree decl : *statics)
849 if (warn_unused_function
850 && TREE_CODE (decl) == FUNCTION_DECL
851 && DECL_INITIAL (decl) == 0
852 && DECL_EXTERNAL (decl)
853 && !TREE_PUBLIC (decl)
854 && !DECL_ARTIFICIAL (decl)
855 && !DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
856 && !warning_suppressed_p (decl, OPT_Wunused_function))
857 warning_at (DECL_SOURCE_LOCATION (decl),
858 OPT_Wunused_function,
859 "%qF declared %<static%> but never defined", decl);
861 if (VAR_P (decl)
862 && DECL_EXTERNAL (decl)
863 && DECL_INLINE_VAR_P (decl)
864 && DECL_ODR_USED (decl))
865 error_at (DECL_SOURCE_LOCATION (decl),
866 "odr-used inline variable %qD is not defined", decl);
869 /* Clear out the list, so we don't rescan next time. */
870 static_decls = NULL;
872 /* Write out any globals that need to be output. */
873 return wrapup_global_declarations (statics->address (),
874 statics->length ());
876 return 0;
879 /* In C++, you don't have to write `struct S' to refer to `S'; you
880 can just use `S'. We accomplish this by creating a TYPE_DECL as
881 if the user had written `typedef struct S S'. Create and return
882 the TYPE_DECL for TYPE. */
884 tree
885 create_implicit_typedef (tree name, tree type)
887 tree decl;
889 decl = build_decl (input_location, TYPE_DECL, name, type);
890 DECL_ARTIFICIAL (decl) = 1;
891 /* There are other implicit type declarations, like the one *within*
892 a class that allows you to write `S::S'. We must distinguish
893 amongst these. */
894 SET_DECL_IMPLICIT_TYPEDEF_P (decl);
895 TYPE_NAME (type) = decl;
896 TYPE_STUB_DECL (type) = decl;
898 return decl;
901 /* Function-scope local entities that need discriminators. Each entry
902 is a {decl,name} pair. VAR_DECLs for anon unions get their name
903 smashed, so we cannot rely on DECL_NAME. */
905 static GTY((deletable)) vec<tree, va_gc> *local_entities;
907 /* Determine the mangling discriminator of local DECL. There are
908 generally very few of these in any particular function. */
910 void
911 determine_local_discriminator (tree decl)
913 auto_cond_timevar tv (TV_NAME_LOOKUP);
914 retrofit_lang_decl (decl);
915 tree ctx = DECL_CONTEXT (decl);
916 tree name = (TREE_CODE (decl) == TYPE_DECL
917 && TYPE_UNNAMED_P (TREE_TYPE (decl))
918 ? NULL_TREE : DECL_NAME (decl));
919 size_t nelts = vec_safe_length (local_entities);
920 for (size_t i = 0; i < nelts; i += 2)
922 tree *pair = &(*local_entities)[i];
923 tree d = pair[0];
924 tree n = pair[1];
925 gcc_checking_assert (d != decl);
926 if (name == n
927 && TREE_CODE (decl) == TREE_CODE (d)
928 && ctx == DECL_CONTEXT (d))
930 tree disc = integer_one_node;
931 if (DECL_DISCRIMINATOR (d))
932 disc = build_int_cst (TREE_TYPE (disc),
933 TREE_INT_CST_LOW (DECL_DISCRIMINATOR (d)) + 1);
934 DECL_DISCRIMINATOR (decl) = disc;
935 /* Replace the saved decl. */
936 pair[0] = decl;
937 decl = NULL_TREE;
938 break;
942 if (decl)
944 vec_safe_reserve (local_entities, 2);
945 local_entities->quick_push (decl);
946 local_entities->quick_push (name);
952 /* Returns true if functions FN1 and FN2 have equivalent trailing
953 requires clauses. */
955 static bool
956 function_requirements_equivalent_p (tree newfn, tree oldfn)
958 /* In the concepts TS, the combined constraints are compared. */
959 if (cxx_dialect < cxx20)
961 tree ci1 = get_constraints (oldfn);
962 tree ci2 = get_constraints (newfn);
963 tree req1 = ci1 ? CI_ASSOCIATED_CONSTRAINTS (ci1) : NULL_TREE;
964 tree req2 = ci2 ? CI_ASSOCIATED_CONSTRAINTS (ci2) : NULL_TREE;
965 return cp_tree_equal (req1, req2);
968 /* Compare only trailing requirements. */
969 tree reqs1 = get_trailing_function_requirements (newfn);
970 tree reqs2 = get_trailing_function_requirements (oldfn);
971 if ((reqs1 != NULL_TREE) != (reqs2 != NULL_TREE))
972 return false;
974 /* Substitution is needed when friends are involved. */
975 reqs1 = maybe_substitute_reqs_for (reqs1, newfn);
976 reqs2 = maybe_substitute_reqs_for (reqs2, oldfn);
978 return cp_tree_equal (reqs1, reqs2);
981 /* Two functions of the same name correspond [basic.scope.scope] if
983 + both declare functions with the same non-object-parameter-type-list,
984 equivalent ([temp.over.link]) trailing requires-clauses (if any, except as
985 specified in [temp.friend]), and, if both are non-static members, they have
986 corresponding object parameters, or
988 + both declare function templates with equivalent
989 non-object-parameter-type-lists, return types (if any), template-heads, and
990 trailing requires-clauses (if any), and, if both are non-static members,
991 they have corresponding object parameters.
993 This is a subset of decls_match: it identifies declarations that cannot be
994 overloaded with one another. This function does not consider DECL_NAME. */
996 bool
997 fns_correspond (tree newdecl, tree olddecl)
999 if (TREE_CODE (newdecl) != TREE_CODE (olddecl))
1000 return false;
1002 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1004 if (!template_heads_equivalent_p (newdecl, olddecl))
1005 return 0;
1006 newdecl = DECL_TEMPLATE_RESULT (newdecl);
1007 olddecl = DECL_TEMPLATE_RESULT (olddecl);
1010 tree f1 = TREE_TYPE (newdecl);
1011 tree f2 = TREE_TYPE (olddecl);
1013 int rq1 = type_memfn_rqual (f1);
1014 int rq2 = type_memfn_rqual (f2);
1016 /* If only one is a non-static member function, ignore ref-quals. */
1017 if (TREE_CODE (f1) != TREE_CODE (f2))
1018 rq1 = rq2;
1019 /* Two non-static member functions have corresponding object parameters if:
1020 + exactly one is an implicit object member function with no ref-qualifier
1021 and the types of their object parameters ([dcl.fct]), after removing
1022 top-level references, are the same, or
1023 + their object parameters have the same type. */
1024 /* ??? We treat member functions of different classes as corresponding even
1025 though that means the object parameters have different types. */
1026 else if ((rq1 == REF_QUAL_NONE) != (rq2 == REF_QUAL_NONE))
1027 rq1 = rq2;
1029 bool types_match = rq1 == rq2;
1031 if (types_match)
1033 tree p1 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1034 tree p2 = FUNCTION_FIRST_USER_PARMTYPE (olddecl);
1035 types_match = compparms (p1, p2);
1038 /* Two function declarations match if either has a requires-clause
1039 then both have a requires-clause and their constraints-expressions
1040 are equivalent. */
1041 if (types_match && flag_concepts)
1042 types_match = function_requirements_equivalent_p (newdecl, olddecl);
1044 return types_match;
1047 /* Subroutine of duplicate_decls: return truthvalue of whether
1048 or not types of these decls match.
1050 For C++, we must compare the parameter list so that `int' can match
1051 `int&' in a parameter position, but `int&' is not confused with
1052 `const int&'. */
1055 decls_match (tree newdecl, tree olddecl, bool record_versions /* = true */)
1057 int types_match;
1059 if (newdecl == olddecl)
1060 return 1;
1062 if (TREE_CODE (newdecl) != TREE_CODE (olddecl))
1063 /* If the two DECLs are not even the same kind of thing, we're not
1064 interested in their types. */
1065 return 0;
1067 gcc_assert (DECL_P (newdecl));
1069 if (TREE_CODE (newdecl) == FUNCTION_DECL)
1071 /* Specializations of different templates are different functions
1072 even if they have the same type. */
1073 tree t1 = (DECL_USE_TEMPLATE (newdecl)
1074 ? DECL_TI_TEMPLATE (newdecl)
1075 : NULL_TREE);
1076 tree t2 = (DECL_USE_TEMPLATE (olddecl)
1077 ? DECL_TI_TEMPLATE (olddecl)
1078 : NULL_TREE);
1079 if (t1 != t2)
1080 return 0;
1082 if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1083 && ! (DECL_EXTERN_C_P (newdecl)
1084 && DECL_EXTERN_C_P (olddecl)))
1085 return 0;
1087 /* A new declaration doesn't match a built-in one unless it
1088 is also extern "C". */
1089 if (DECL_IS_UNDECLARED_BUILTIN (olddecl)
1090 && DECL_EXTERN_C_P (olddecl) && !DECL_EXTERN_C_P (newdecl))
1091 return 0;
1093 tree f1 = TREE_TYPE (newdecl);
1094 tree f2 = TREE_TYPE (olddecl);
1095 if (TREE_CODE (f1) != TREE_CODE (f2))
1096 return 0;
1098 /* A declaration with deduced return type should use its pre-deduction
1099 type for declaration matching. */
1100 tree r2 = fndecl_declared_return_type (olddecl);
1101 tree r1 = fndecl_declared_return_type (newdecl);
1103 tree p1 = TYPE_ARG_TYPES (f1);
1104 tree p2 = TYPE_ARG_TYPES (f2);
1106 if (same_type_p (r1, r2))
1108 if (!prototype_p (f2) && DECL_EXTERN_C_P (olddecl)
1109 && fndecl_built_in_p (olddecl))
1111 types_match = self_promoting_args_p (p1);
1112 if (p1 == void_list_node)
1113 TREE_TYPE (newdecl) = TREE_TYPE (olddecl);
1115 else
1116 types_match =
1117 compparms (p1, p2)
1118 && type_memfn_rqual (f1) == type_memfn_rqual (f2)
1119 && (TYPE_ATTRIBUTES (TREE_TYPE (newdecl)) == NULL_TREE
1120 || comp_type_attributes (TREE_TYPE (newdecl),
1121 TREE_TYPE (olddecl)) != 0);
1123 else
1124 types_match = 0;
1126 /* Two function declarations match if either has a requires-clause
1127 then both have a requires-clause and their constraints-expressions
1128 are equivalent. */
1129 if (types_match && flag_concepts)
1130 types_match = function_requirements_equivalent_p (newdecl, olddecl);
1132 /* The decls dont match if they correspond to two different versions
1133 of the same function. Disallow extern "C" functions to be
1134 versions for now. */
1135 if (types_match
1136 && !DECL_EXTERN_C_P (newdecl)
1137 && !DECL_EXTERN_C_P (olddecl)
1138 && targetm.target_option.function_versions (newdecl, olddecl))
1140 if (record_versions)
1141 maybe_version_functions (newdecl, olddecl,
1142 (!DECL_FUNCTION_VERSIONED (newdecl)
1143 || !DECL_FUNCTION_VERSIONED (olddecl)));
1144 return 0;
1147 else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1149 if (!template_heads_equivalent_p (newdecl, olddecl))
1150 return 0;
1152 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1153 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1155 if (TREE_CODE (newres) != TREE_CODE (oldres))
1156 return 0;
1158 /* Two template types match if they are the same. Otherwise, compare
1159 the underlying declarations. */
1160 if (TREE_CODE (newres) == TYPE_DECL)
1161 types_match = same_type_p (TREE_TYPE (newres), TREE_TYPE (oldres));
1162 else
1163 types_match = decls_match (newres, oldres);
1165 else
1167 /* Need to check scope for variable declaration (VAR_DECL).
1168 For typedef (TYPE_DECL), scope is ignored. */
1169 if (VAR_P (newdecl)
1170 && CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1171 /* [dcl.link]
1172 Two declarations for an object with C language linkage
1173 with the same name (ignoring the namespace that qualify
1174 it) that appear in different namespace scopes refer to
1175 the same object. */
1176 && !(DECL_EXTERN_C_P (olddecl) && DECL_EXTERN_C_P (newdecl)))
1177 return 0;
1179 if (TREE_TYPE (newdecl) == error_mark_node)
1180 types_match = TREE_TYPE (olddecl) == error_mark_node;
1181 else if (TREE_TYPE (olddecl) == NULL_TREE)
1182 types_match = TREE_TYPE (newdecl) == NULL_TREE;
1183 else if (TREE_TYPE (newdecl) == NULL_TREE)
1184 types_match = 0;
1185 else
1186 types_match = comptypes (TREE_TYPE (newdecl),
1187 TREE_TYPE (olddecl),
1188 COMPARE_REDECLARATION);
1191 return types_match;
1194 /* Mark DECL as versioned if it isn't already. */
1196 static void
1197 maybe_mark_function_versioned (tree decl)
1199 if (!DECL_FUNCTION_VERSIONED (decl))
1201 DECL_FUNCTION_VERSIONED (decl) = 1;
1202 /* If DECL_ASSEMBLER_NAME has already been set, re-mangle
1203 to include the version marker. */
1204 if (DECL_ASSEMBLER_NAME_SET_P (decl))
1205 mangle_decl (decl);
1209 /* NEWDECL and OLDDECL have identical signatures. If they are
1210 different versions adjust them and return true.
1211 If RECORD is set to true, record function versions. */
1213 bool
1214 maybe_version_functions (tree newdecl, tree olddecl, bool record)
1216 if (!targetm.target_option.function_versions (newdecl, olddecl))
1217 return false;
1219 maybe_mark_function_versioned (olddecl);
1220 if (DECL_LOCAL_DECL_P (olddecl))
1222 olddecl = DECL_LOCAL_DECL_ALIAS (olddecl);
1223 maybe_mark_function_versioned (olddecl);
1226 maybe_mark_function_versioned (newdecl);
1227 if (DECL_LOCAL_DECL_P (newdecl))
1229 /* Unfortunately, we can get here before pushdecl naturally calls
1230 push_local_extern_decl_alias, so we need to call it directly. */
1231 if (!DECL_LOCAL_DECL_ALIAS (newdecl))
1232 push_local_extern_decl_alias (newdecl);
1233 newdecl = DECL_LOCAL_DECL_ALIAS (newdecl);
1234 maybe_mark_function_versioned (newdecl);
1237 if (record)
1238 cgraph_node::record_function_versions (olddecl, newdecl);
1240 return true;
1243 /* If NEWDECL is `static' and an `extern' was seen previously,
1244 warn about it. OLDDECL is the previous declaration.
1246 Note that this does not apply to the C++ case of declaring
1247 a variable `extern const' and then later `const'.
1249 Don't complain about built-in functions, since they are beyond
1250 the user's control. */
1252 void
1253 warn_extern_redeclared_static (tree newdecl, tree olddecl)
1255 if (TREE_CODE (newdecl) == TYPE_DECL
1256 || TREE_CODE (newdecl) == TEMPLATE_DECL
1257 || TREE_CODE (newdecl) == CONST_DECL
1258 || TREE_CODE (newdecl) == NAMESPACE_DECL)
1259 return;
1261 /* Don't get confused by static member functions; that's a different
1262 use of `static'. */
1263 if (TREE_CODE (newdecl) == FUNCTION_DECL
1264 && DECL_STATIC_FUNCTION_P (newdecl))
1265 return;
1267 /* If the old declaration was `static', or the new one isn't, then
1268 everything is OK. */
1269 if (DECL_THIS_STATIC (olddecl) || !DECL_THIS_STATIC (newdecl))
1270 return;
1272 /* It's OK to declare a builtin function as `static'. */
1273 if (TREE_CODE (olddecl) == FUNCTION_DECL
1274 && DECL_ARTIFICIAL (olddecl))
1275 return;
1277 auto_diagnostic_group d;
1278 if (permerror (DECL_SOURCE_LOCATION (newdecl),
1279 "%qD was declared %<extern%> and later %<static%>", newdecl))
1280 inform (DECL_SOURCE_LOCATION (olddecl),
1281 "previous declaration of %qD", olddecl);
1284 /* NEW_DECL is a redeclaration of OLD_DECL; both are functions or
1285 function templates. If their exception specifications do not
1286 match, issue a diagnostic. */
1288 static void
1289 check_redeclaration_exception_specification (tree new_decl,
1290 tree old_decl)
1292 tree new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1293 tree old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1295 /* Two default specs are equivalent, don't force evaluation. */
1296 if (UNEVALUATED_NOEXCEPT_SPEC_P (new_exceptions)
1297 && UNEVALUATED_NOEXCEPT_SPEC_P (old_exceptions))
1298 return;
1300 if (!type_dependent_expression_p (old_decl))
1302 maybe_instantiate_noexcept (new_decl);
1303 maybe_instantiate_noexcept (old_decl);
1305 new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1306 old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1308 /* [except.spec]
1310 If any declaration of a function has an exception-specification,
1311 all declarations, including the definition and an explicit
1312 specialization, of that function shall have an
1313 exception-specification with the same set of type-ids. */
1314 if (!DECL_IS_UNDECLARED_BUILTIN (old_decl)
1315 && !DECL_IS_UNDECLARED_BUILTIN (new_decl)
1316 && !comp_except_specs (new_exceptions, old_exceptions, ce_normal))
1318 const char *const msg
1319 = G_("declaration of %qF has a different exception specifier");
1320 bool complained = true;
1321 location_t new_loc = DECL_SOURCE_LOCATION (new_decl);
1322 auto_diagnostic_group d;
1323 if (DECL_IN_SYSTEM_HEADER (old_decl))
1324 complained = pedwarn (new_loc, OPT_Wsystem_headers, msg, new_decl);
1325 else if (!flag_exceptions)
1326 /* We used to silently permit mismatched eh specs with
1327 -fno-exceptions, so make them a pedwarn now. */
1328 complained = pedwarn (new_loc, OPT_Wpedantic, msg, new_decl);
1329 else
1330 error_at (new_loc, msg, new_decl);
1331 if (complained)
1332 inform (DECL_SOURCE_LOCATION (old_decl),
1333 "from previous declaration %qF", old_decl);
1337 /* Return true if OLD_DECL and NEW_DECL agree on constexprness.
1338 Otherwise issue diagnostics. */
1340 static bool
1341 validate_constexpr_redeclaration (tree old_decl, tree new_decl)
1343 old_decl = STRIP_TEMPLATE (old_decl);
1344 new_decl = STRIP_TEMPLATE (new_decl);
1345 if (!VAR_OR_FUNCTION_DECL_P (old_decl)
1346 || !VAR_OR_FUNCTION_DECL_P (new_decl))
1347 return true;
1348 if (DECL_DECLARED_CONSTEXPR_P (old_decl)
1349 == DECL_DECLARED_CONSTEXPR_P (new_decl))
1351 if (TREE_CODE (old_decl) != FUNCTION_DECL)
1352 return true;
1353 if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1354 == DECL_IMMEDIATE_FUNCTION_P (new_decl))
1355 return true;
1357 if (TREE_CODE (old_decl) == FUNCTION_DECL)
1359 /* With -fimplicit-constexpr, ignore changes in the constexpr
1360 keyword. */
1361 if (flag_implicit_constexpr
1362 && (DECL_IMMEDIATE_FUNCTION_P (new_decl)
1363 == DECL_IMMEDIATE_FUNCTION_P (old_decl)))
1364 return true;
1365 if (fndecl_built_in_p (old_decl))
1367 /* Hide a built-in declaration. */
1368 DECL_DECLARED_CONSTEXPR_P (old_decl)
1369 = DECL_DECLARED_CONSTEXPR_P (new_decl);
1370 if (DECL_IMMEDIATE_FUNCTION_P (new_decl))
1371 SET_DECL_IMMEDIATE_FUNCTION_P (old_decl);
1372 return true;
1374 /* 7.1.5 [dcl.constexpr]
1375 Note: An explicit specialization can differ from the template
1376 declaration with respect to the constexpr specifier. */
1377 if (! DECL_TEMPLATE_SPECIALIZATION (old_decl)
1378 && DECL_TEMPLATE_SPECIALIZATION (new_decl))
1379 return true;
1381 const char *kind = "constexpr";
1382 if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1383 || DECL_IMMEDIATE_FUNCTION_P (new_decl))
1384 kind = "consteval";
1385 error_at (DECL_SOURCE_LOCATION (new_decl),
1386 "redeclaration %qD differs in %qs "
1387 "from previous declaration", new_decl,
1388 kind);
1389 inform (DECL_SOURCE_LOCATION (old_decl),
1390 "previous declaration %qD", old_decl);
1391 return false;
1393 return true;
1396 // If OLDDECL and NEWDECL are concept declarations with the same type
1397 // (i.e., and template parameters), but different requirements,
1398 // emit diagnostics and return true. Otherwise, return false.
1399 static inline bool
1400 check_concept_refinement (tree olddecl, tree newdecl)
1402 if (!DECL_DECLARED_CONCEPT_P (olddecl) || !DECL_DECLARED_CONCEPT_P (newdecl))
1403 return false;
1405 tree d1 = DECL_TEMPLATE_RESULT (olddecl);
1406 tree d2 = DECL_TEMPLATE_RESULT (newdecl);
1407 if (TREE_CODE (d1) != TREE_CODE (d2))
1408 return false;
1410 tree t1 = TREE_TYPE (d1);
1411 tree t2 = TREE_TYPE (d2);
1412 if (TREE_CODE (d1) == FUNCTION_DECL)
1414 if (compparms (TYPE_ARG_TYPES (t1), TYPE_ARG_TYPES (t2))
1415 && comp_template_parms (DECL_TEMPLATE_PARMS (olddecl),
1416 DECL_TEMPLATE_PARMS (newdecl))
1417 && !equivalently_constrained (olddecl, newdecl))
1419 error ("cannot specialize concept %q#D", olddecl);
1420 return true;
1423 return false;
1426 /* DECL is a redeclaration of a function or function template. If
1427 it does have default arguments issue a diagnostic. Note: this
1428 function is used to enforce the requirements in C++11 8.3.6 about
1429 no default arguments in redeclarations. */
1431 static void
1432 check_redeclaration_no_default_args (tree decl)
1434 gcc_assert (DECL_DECLARES_FUNCTION_P (decl));
1436 for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
1437 t && t != void_list_node; t = TREE_CHAIN (t))
1438 if (TREE_PURPOSE (t))
1440 permerror (DECL_SOURCE_LOCATION (decl),
1441 "redeclaration of %q#D may not have default "
1442 "arguments", decl);
1443 return;
1447 /* NEWDECL is a redeclaration of a function or function template OLDDECL,
1448 in any case represented as FUNCTION_DECLs (the DECL_TEMPLATE_RESULTs of
1449 the TEMPLATE_DECLs in case of function templates). This function is used
1450 to enforce the final part of C++17 11.3.6/4, about a single declaration:
1451 "If a friend declaration specifies a default argument expression, that
1452 declaration shall be a definition and shall be the only declaration of
1453 the function or function template in the translation unit." */
1455 static void
1456 check_no_redeclaration_friend_default_args (tree olddecl, tree newdecl)
1458 if (!DECL_UNIQUE_FRIEND_P (olddecl) && !DECL_UNIQUE_FRIEND_P (newdecl))
1459 return;
1461 for (tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl),
1462 t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1463 t1 && t1 != void_list_node;
1464 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1465 if ((DECL_UNIQUE_FRIEND_P (olddecl) && TREE_PURPOSE (t1))
1466 || (DECL_UNIQUE_FRIEND_P (newdecl) && TREE_PURPOSE (t2)))
1468 auto_diagnostic_group d;
1469 if (permerror (DECL_SOURCE_LOCATION (newdecl),
1470 "friend declaration of %q#D specifies default "
1471 "arguments and isn%'t the only declaration", newdecl))
1472 inform (DECL_SOURCE_LOCATION (olddecl),
1473 "previous declaration of %q#D", olddecl);
1474 return;
1478 /* Merge tree bits that correspond to attributes noreturn, nothrow,
1479 const, malloc, and pure from NEWDECL with those of OLDDECL. */
1481 static void
1482 merge_attribute_bits (tree newdecl, tree olddecl)
1484 TREE_THIS_VOLATILE (newdecl) |= TREE_THIS_VOLATILE (olddecl);
1485 TREE_THIS_VOLATILE (olddecl) |= TREE_THIS_VOLATILE (newdecl);
1486 TREE_NOTHROW (newdecl) |= TREE_NOTHROW (olddecl);
1487 TREE_NOTHROW (olddecl) |= TREE_NOTHROW (newdecl);
1488 TREE_READONLY (newdecl) |= TREE_READONLY (olddecl);
1489 TREE_READONLY (olddecl) |= TREE_READONLY (newdecl);
1490 DECL_IS_MALLOC (newdecl) |= DECL_IS_MALLOC (olddecl);
1491 DECL_IS_MALLOC (olddecl) |= DECL_IS_MALLOC (newdecl);
1492 DECL_PURE_P (newdecl) |= DECL_PURE_P (olddecl);
1493 DECL_PURE_P (olddecl) |= DECL_PURE_P (newdecl);
1494 DECL_UNINLINABLE (newdecl) |= DECL_UNINLINABLE (olddecl);
1495 DECL_UNINLINABLE (olddecl) |= DECL_UNINLINABLE (newdecl);
1498 #define GNU_INLINE_P(fn) (DECL_DECLARED_INLINE_P (fn) \
1499 && lookup_attribute ("gnu_inline", \
1500 DECL_ATTRIBUTES (fn)))
1502 /* A subroutine of duplicate_decls. Emits a diagnostic when newdecl
1503 ambiguates olddecl. Returns true if an error occurs. */
1505 static bool
1506 duplicate_function_template_decls (tree newdecl, tree olddecl)
1509 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1510 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1511 /* Function template declarations can be differentiated by parameter
1512 and return type. */
1513 if (compparms (TYPE_ARG_TYPES (TREE_TYPE (oldres)),
1514 TYPE_ARG_TYPES (TREE_TYPE (newres)))
1515 && same_type_p (TREE_TYPE (TREE_TYPE (newdecl)),
1516 TREE_TYPE (TREE_TYPE (olddecl))))
1518 /* ... and also by their template-heads and requires-clauses. */
1519 if (template_heads_equivalent_p (newdecl, olddecl)
1520 && function_requirements_equivalent_p (newres, oldres))
1522 error ("ambiguating new declaration %q+#D", newdecl);
1523 inform (DECL_SOURCE_LOCATION (olddecl),
1524 "old declaration %q#D", olddecl);
1525 return true;
1528 /* FIXME: The types are the same but the are differences
1529 in either the template heads or function requirements.
1530 We should be able to diagnose a set of common errors
1531 stemming from these declarations. For example:
1533 template<typename T> requires C void f(...);
1534 template<typename T> void f(...) requires C;
1536 These are functionally equivalent but not equivalent. */
1539 return false;
1542 /* OLD_PARMS is the innermost set of template parameters for some template
1543 declaration, and NEW_PARMS is the corresponding set of template parameters
1544 for a redeclaration of that template. Merge the default arguments within
1545 these two sets of parameters. CLASS_P is true iff the template in
1546 question is a class template. */
1548 bool
1549 merge_default_template_args (tree new_parms, tree old_parms, bool class_p)
1551 gcc_checking_assert (TREE_VEC_LENGTH (new_parms)
1552 == TREE_VEC_LENGTH (old_parms));
1553 for (int i = 0; i < TREE_VEC_LENGTH (new_parms); i++)
1555 tree new_parm = TREE_VALUE (TREE_VEC_ELT (new_parms, i));
1556 tree old_parm = TREE_VALUE (TREE_VEC_ELT (old_parms, i));
1557 tree& new_default = TREE_PURPOSE (TREE_VEC_ELT (new_parms, i));
1558 tree& old_default = TREE_PURPOSE (TREE_VEC_ELT (old_parms, i));
1559 if (error_operand_p (new_parm) || error_operand_p (old_parm))
1560 return false;
1561 if (new_default != NULL_TREE && old_default != NULL_TREE)
1563 auto_diagnostic_group d;
1564 error ("redefinition of default argument for %q+#D", new_parm);
1565 inform (DECL_SOURCE_LOCATION (old_parm),
1566 "original definition appeared here");
1567 return false;
1569 else if (new_default != NULL_TREE)
1570 /* Update the previous template parameters (which are the ones
1571 that will really count) with the new default value. */
1572 old_default = new_default;
1573 else if (class_p && old_default != NULL_TREE)
1574 /* Update the new parameters, too; they'll be used as the
1575 parameters for any members. */
1576 new_default = old_default;
1578 return true;
1581 /* If NEWDECL is a redeclaration of OLDDECL, merge the declarations.
1582 If the redeclaration is invalid, a diagnostic is issued, and the
1583 error_mark_node is returned. Otherwise, OLDDECL is returned.
1585 If NEWDECL is not a redeclaration of OLDDECL, NULL_TREE is
1586 returned.
1588 HIDING is true if the new decl is being hidden. WAS_HIDDEN is true
1589 if the old decl was hidden.
1591 Hidden decls can be anticipated builtins, injected friends, or
1592 (coming soon) injected from a local-extern decl. */
1594 tree
1595 duplicate_decls (tree newdecl, tree olddecl, bool hiding, bool was_hidden)
1597 unsigned olddecl_uid = DECL_UID (olddecl);
1598 int types_match = 0;
1599 int new_defines_function = 0;
1600 tree new_template_info;
1601 location_t olddecl_loc = DECL_SOURCE_LOCATION (olddecl);
1602 location_t newdecl_loc = DECL_SOURCE_LOCATION (newdecl);
1604 if (newdecl == olddecl)
1605 return olddecl;
1607 types_match = decls_match (newdecl, olddecl);
1609 /* If either the type of the new decl or the type of the old decl is an
1610 error_mark_node, then that implies that we have already issued an
1611 error (earlier) for some bogus type specification, and in that case,
1612 it is rather pointless to harass the user with yet more error message
1613 about the same declaration, so just pretend the types match here. */
1614 if (TREE_TYPE (newdecl) == error_mark_node
1615 || TREE_TYPE (olddecl) == error_mark_node)
1616 return error_mark_node;
1618 /* Check for redeclaration and other discrepancies. */
1619 if (TREE_CODE (olddecl) == FUNCTION_DECL
1620 && DECL_IS_UNDECLARED_BUILTIN (olddecl))
1622 if (TREE_CODE (newdecl) != FUNCTION_DECL)
1624 /* Avoid warnings redeclaring built-ins which have not been
1625 explicitly declared. */
1626 if (was_hidden)
1628 if (TREE_PUBLIC (newdecl)
1629 && CP_DECL_CONTEXT (newdecl) == global_namespace)
1630 warning_at (newdecl_loc,
1631 OPT_Wbuiltin_declaration_mismatch,
1632 "built-in function %qD declared as non-function",
1633 newdecl);
1634 return NULL_TREE;
1637 /* If you declare a built-in or predefined function name as static,
1638 the old definition is overridden, but optionally warn this was a
1639 bad choice of name. */
1640 if (! TREE_PUBLIC (newdecl))
1642 warning_at (newdecl_loc,
1643 OPT_Wshadow,
1644 fndecl_built_in_p (olddecl)
1645 ? G_("shadowing built-in function %q#D")
1646 : G_("shadowing library function %q#D"), olddecl);
1647 /* Discard the old built-in function. */
1648 return NULL_TREE;
1650 /* If the built-in is not ansi, then programs can override
1651 it even globally without an error. */
1652 else if (! fndecl_built_in_p (olddecl))
1653 warning_at (newdecl_loc, 0,
1654 "library function %q#D redeclared as non-function %q#D",
1655 olddecl, newdecl);
1656 else
1657 error_at (newdecl_loc,
1658 "declaration of %q#D conflicts with built-in "
1659 "declaration %q#D", newdecl, olddecl);
1660 return NULL_TREE;
1662 else if (!types_match)
1664 /* Avoid warnings redeclaring built-ins which have not been
1665 explicitly declared. */
1666 if (was_hidden)
1668 tree t1, t2;
1670 /* A new declaration doesn't match a built-in one unless it
1671 is also extern "C". */
1672 gcc_assert (DECL_IS_UNDECLARED_BUILTIN (olddecl));
1673 gcc_assert (DECL_EXTERN_C_P (olddecl));
1674 if (!DECL_EXTERN_C_P (newdecl))
1675 return NULL_TREE;
1677 for (t1 = TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1678 t2 = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1679 t1 || t2;
1680 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1682 if (!t1 || !t2)
1683 break;
1684 /* FILE, tm types are not known at the time
1685 we create the builtins. */
1686 for (unsigned i = 0;
1687 i < sizeof (builtin_structptr_types)
1688 / sizeof (builtin_structptr_type);
1689 ++i)
1690 if (TREE_VALUE (t2) == builtin_structptr_types[i].node)
1692 tree t = TREE_VALUE (t1);
1694 if (TYPE_PTR_P (t)
1695 && TYPE_IDENTIFIER (TREE_TYPE (t))
1696 == get_identifier (builtin_structptr_types[i].str)
1697 && compparms (TREE_CHAIN (t1), TREE_CHAIN (t2)))
1699 tree oldargs = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1701 TYPE_ARG_TYPES (TREE_TYPE (olddecl))
1702 = TYPE_ARG_TYPES (TREE_TYPE (newdecl));
1703 types_match = decls_match (newdecl, olddecl);
1704 if (types_match)
1705 return duplicate_decls (newdecl, olddecl,
1706 hiding, was_hidden);
1707 TYPE_ARG_TYPES (TREE_TYPE (olddecl)) = oldargs;
1709 goto next_arg;
1712 if (! same_type_p (TREE_VALUE (t1), TREE_VALUE (t2)))
1713 break;
1714 next_arg:;
1717 warning_at (newdecl_loc,
1718 OPT_Wbuiltin_declaration_mismatch,
1719 "declaration of %q#D conflicts with built-in "
1720 "declaration %q#D", newdecl, olddecl);
1722 else if ((DECL_EXTERN_C_P (newdecl)
1723 && DECL_EXTERN_C_P (olddecl))
1724 || compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1725 TYPE_ARG_TYPES (TREE_TYPE (olddecl))))
1727 /* Don't really override olddecl for __* prefixed builtins
1728 except for __[^b]*_chk, the compiler might be using those
1729 explicitly. */
1730 if (fndecl_built_in_p (olddecl))
1732 tree id = DECL_NAME (olddecl);
1733 const char *name = IDENTIFIER_POINTER (id);
1734 size_t len;
1736 if (name[0] == '_'
1737 && name[1] == '_'
1738 && (startswith (name + 2, "builtin_")
1739 || (len = strlen (name)) <= strlen ("___chk")
1740 || memcmp (name + len - strlen ("_chk"),
1741 "_chk", strlen ("_chk") + 1) != 0))
1743 if (DECL_INITIAL (newdecl))
1745 error_at (newdecl_loc,
1746 "definition of %q#D ambiguates built-in "
1747 "declaration %q#D", newdecl, olddecl);
1748 return error_mark_node;
1750 auto_diagnostic_group d;
1751 if (permerror (newdecl_loc,
1752 "new declaration %q#D ambiguates built-in"
1753 " declaration %q#D", newdecl, olddecl)
1754 && flag_permissive)
1755 inform (newdecl_loc,
1756 "ignoring the %q#D declaration", newdecl);
1757 return flag_permissive ? olddecl : error_mark_node;
1761 /* A near match; override the builtin. */
1763 if (TREE_PUBLIC (newdecl))
1764 warning_at (newdecl_loc,
1765 OPT_Wbuiltin_declaration_mismatch,
1766 "new declaration %q#D ambiguates built-in "
1767 "declaration %q#D", newdecl, olddecl);
1768 else
1769 warning (OPT_Wshadow,
1770 fndecl_built_in_p (olddecl)
1771 ? G_("shadowing built-in function %q#D")
1772 : G_("shadowing library function %q#D"), olddecl);
1774 else
1775 /* Discard the old built-in function. */
1776 return NULL_TREE;
1778 /* Replace the old RTL to avoid problems with inlining. */
1779 COPY_DECL_RTL (newdecl, olddecl);
1781 else
1783 /* Even if the types match, prefer the new declarations type
1784 for built-ins which have not been explicitly declared,
1785 for exception lists, etc... */
1786 tree type = TREE_TYPE (newdecl);
1787 tree attribs = (*targetm.merge_type_attributes)
1788 (TREE_TYPE (olddecl), type);
1790 type = cp_build_type_attribute_variant (type, attribs);
1791 TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = type;
1794 /* If a function is explicitly declared "throw ()", propagate that to
1795 the corresponding builtin. */
1796 if (DECL_BUILT_IN_CLASS (olddecl) == BUILT_IN_NORMAL
1797 && was_hidden
1798 && TREE_NOTHROW (newdecl)
1799 && !TREE_NOTHROW (olddecl))
1801 enum built_in_function fncode = DECL_FUNCTION_CODE (olddecl);
1802 tree tmpdecl = builtin_decl_explicit (fncode);
1803 if (tmpdecl && tmpdecl != olddecl && types_match)
1804 TREE_NOTHROW (tmpdecl) = 1;
1807 /* Whether or not the builtin can throw exceptions has no
1808 bearing on this declarator. */
1809 TREE_NOTHROW (olddecl) = 0;
1811 if (DECL_THIS_STATIC (newdecl) && !DECL_THIS_STATIC (olddecl))
1813 /* If a builtin function is redeclared as `static', merge
1814 the declarations, but make the original one static. */
1815 DECL_THIS_STATIC (olddecl) = 1;
1816 TREE_PUBLIC (olddecl) = 0;
1818 /* Make the old declaration consistent with the new one so
1819 that all remnants of the builtin-ness of this function
1820 will be banished. */
1821 SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
1822 COPY_DECL_RTL (newdecl, olddecl);
1825 else if (TREE_CODE (olddecl) != TREE_CODE (newdecl))
1827 /* C++ Standard, 3.3, clause 4:
1828 "[Note: a namespace name or a class template name must be unique
1829 in its declarative region (7.3.2, clause 14). ]" */
1830 if (TREE_CODE (olddecl) == NAMESPACE_DECL
1831 || TREE_CODE (newdecl) == NAMESPACE_DECL)
1832 /* Namespace conflicts with not namespace. */;
1833 else if (DECL_TYPE_TEMPLATE_P (olddecl)
1834 || DECL_TYPE_TEMPLATE_P (newdecl))
1835 /* Class template conflicts. */;
1836 else if ((TREE_CODE (olddecl) == TEMPLATE_DECL
1837 && DECL_TEMPLATE_RESULT (olddecl)
1838 && TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)) == VAR_DECL)
1839 || (TREE_CODE (newdecl) == TEMPLATE_DECL
1840 && DECL_TEMPLATE_RESULT (newdecl)
1841 && TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == VAR_DECL))
1842 /* Variable template conflicts. */;
1843 else if (concept_definition_p (olddecl)
1844 || concept_definition_p (newdecl))
1845 /* Concept conflicts. */;
1846 else if ((TREE_CODE (newdecl) == FUNCTION_DECL
1847 && DECL_FUNCTION_TEMPLATE_P (olddecl))
1848 || (TREE_CODE (olddecl) == FUNCTION_DECL
1849 && DECL_FUNCTION_TEMPLATE_P (newdecl)))
1851 /* One is a function and the other is a template
1852 function. */
1853 if (!UDLIT_OPER_P (DECL_NAME (newdecl)))
1854 return NULL_TREE;
1856 /* There can only be one! */
1857 if (TREE_CODE (newdecl) == TEMPLATE_DECL
1858 && check_raw_literal_operator (olddecl))
1859 error_at (newdecl_loc,
1860 "literal operator %q#D conflicts with"
1861 " raw literal operator", newdecl);
1862 else if (check_raw_literal_operator (newdecl))
1863 error_at (newdecl_loc,
1864 "raw literal operator %q#D conflicts with"
1865 " literal operator template", newdecl);
1866 else
1867 return NULL_TREE;
1869 inform (olddecl_loc, "previous declaration %q#D", olddecl);
1870 return error_mark_node;
1872 else if ((VAR_P (olddecl) && DECL_DECOMPOSITION_P (olddecl))
1873 || (VAR_P (newdecl) && DECL_DECOMPOSITION_P (newdecl)))
1874 /* A structured binding must be unique in its declarative region. */;
1875 else if (DECL_IMPLICIT_TYPEDEF_P (olddecl)
1876 || DECL_IMPLICIT_TYPEDEF_P (newdecl))
1877 /* One is an implicit typedef, that's ok. */
1878 return NULL_TREE;
1880 error ("%q#D redeclared as different kind of entity", newdecl);
1881 inform (olddecl_loc, "previous declaration %q#D", olddecl);
1883 return error_mark_node;
1885 else if (!types_match)
1887 if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl))
1888 /* These are certainly not duplicate declarations; they're
1889 from different scopes. */
1890 return NULL_TREE;
1892 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1894 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1895 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1897 /* The name of a class template may not be declared to refer to
1898 any other template, class, function, object, namespace, value,
1899 or type in the same scope. */
1900 if (TREE_CODE (oldres) == TYPE_DECL
1901 || TREE_CODE (newres) == TYPE_DECL)
1903 error_at (newdecl_loc,
1904 "conflicting declaration of template %q#D", newdecl);
1905 inform (olddecl_loc,
1906 "previous declaration %q#D", olddecl);
1907 return error_mark_node;
1910 else if (TREE_CODE (oldres) == FUNCTION_DECL
1911 && TREE_CODE (newres) == FUNCTION_DECL)
1913 if (duplicate_function_template_decls (newdecl, olddecl))
1914 return error_mark_node;
1915 return NULL_TREE;
1917 else if (check_concept_refinement (olddecl, newdecl))
1918 return error_mark_node;
1919 return NULL_TREE;
1921 if (TREE_CODE (newdecl) == FUNCTION_DECL)
1923 if (DECL_EXTERN_C_P (newdecl) && DECL_EXTERN_C_P (olddecl))
1925 error_at (newdecl_loc,
1926 "conflicting declaration of C function %q#D",
1927 newdecl);
1928 inform (olddecl_loc,
1929 "previous declaration %q#D", olddecl);
1930 return error_mark_node;
1932 /* For function versions, params and types match, but they
1933 are not ambiguous. */
1934 else if ((!DECL_FUNCTION_VERSIONED (newdecl)
1935 && !DECL_FUNCTION_VERSIONED (olddecl))
1936 // The functions have the same parameter types.
1937 && compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1938 TYPE_ARG_TYPES (TREE_TYPE (olddecl)))
1939 // And the same constraints.
1940 && equivalently_constrained (newdecl, olddecl))
1942 error_at (newdecl_loc,
1943 "ambiguating new declaration of %q#D", newdecl);
1944 inform (olddecl_loc,
1945 "old declaration %q#D", olddecl);
1946 return error_mark_node;
1948 else
1949 return NULL_TREE;
1951 else
1953 error_at (newdecl_loc, "conflicting declaration %q#D", newdecl);
1954 inform (olddecl_loc,
1955 "previous declaration as %q#D", olddecl);
1956 return error_mark_node;
1959 else if (TREE_CODE (newdecl) == FUNCTION_DECL
1960 && DECL_OMP_DECLARE_REDUCTION_P (newdecl))
1962 /* OMP UDRs are never duplicates. */
1963 gcc_assert (DECL_OMP_DECLARE_REDUCTION_P (olddecl));
1964 error_at (newdecl_loc,
1965 "redeclaration of %<pragma omp declare reduction%>");
1966 inform (olddecl_loc,
1967 "previous %<pragma omp declare reduction%> declaration");
1968 return error_mark_node;
1970 else if (TREE_CODE (newdecl) == FUNCTION_DECL
1971 && ((DECL_TEMPLATE_SPECIALIZATION (olddecl)
1972 && (!DECL_TEMPLATE_INFO (newdecl)
1973 || (DECL_TI_TEMPLATE (newdecl)
1974 != DECL_TI_TEMPLATE (olddecl))))
1975 || (DECL_TEMPLATE_SPECIALIZATION (newdecl)
1976 && (!DECL_TEMPLATE_INFO (olddecl)
1977 || (DECL_TI_TEMPLATE (olddecl)
1978 != DECL_TI_TEMPLATE (newdecl))))))
1979 /* It's OK to have a template specialization and a non-template
1980 with the same type, or to have specializations of two
1981 different templates with the same type. Note that if one is a
1982 specialization, and the other is an instantiation of the same
1983 template, that we do not exit at this point. That situation
1984 can occur if we instantiate a template class, and then
1985 specialize one of its methods. This situation is valid, but
1986 the declarations must be merged in the usual way. */
1987 return NULL_TREE;
1988 else if (TREE_CODE (newdecl) == FUNCTION_DECL
1989 && ((DECL_TEMPLATE_INSTANTIATION (olddecl)
1990 && !DECL_USE_TEMPLATE (newdecl))
1991 || (DECL_TEMPLATE_INSTANTIATION (newdecl)
1992 && !DECL_USE_TEMPLATE (olddecl))))
1993 /* One of the declarations is a template instantiation, and the
1994 other is not a template at all. That's OK. */
1995 return NULL_TREE;
1996 else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
1998 /* In [namespace.alias] we have:
2000 In a declarative region, a namespace-alias-definition can be
2001 used to redefine a namespace-alias declared in that declarative
2002 region to refer only to the namespace to which it already
2003 refers.
2005 Therefore, if we encounter a second alias directive for the same
2006 alias, we can just ignore the second directive. */
2007 if (DECL_NAMESPACE_ALIAS (newdecl)
2008 && (DECL_NAMESPACE_ALIAS (newdecl)
2009 == DECL_NAMESPACE_ALIAS (olddecl)))
2010 return olddecl;
2012 /* Leave it to update_binding to merge or report error. */
2013 return NULL_TREE;
2015 else
2017 const char *errmsg = redeclaration_error_message (newdecl, olddecl);
2018 if (errmsg)
2020 auto_diagnostic_group d;
2021 error_at (newdecl_loc, errmsg, newdecl);
2022 if (DECL_NAME (olddecl) != NULL_TREE)
2023 inform (olddecl_loc,
2024 (DECL_INITIAL (olddecl) && namespace_bindings_p ())
2025 ? G_("%q#D previously defined here")
2026 : G_("%q#D previously declared here"), olddecl);
2027 return error_mark_node;
2029 else if (TREE_CODE (olddecl) == FUNCTION_DECL
2030 && DECL_INITIAL (olddecl) != NULL_TREE
2031 && !prototype_p (TREE_TYPE (olddecl))
2032 && prototype_p (TREE_TYPE (newdecl)))
2034 /* Prototype decl follows defn w/o prototype. */
2035 auto_diagnostic_group d;
2036 if (warning_at (newdecl_loc, 0,
2037 "prototype specified for %q#D", newdecl))
2038 inform (olddecl_loc,
2039 "previous non-prototype definition here");
2041 else if (VAR_OR_FUNCTION_DECL_P (olddecl)
2042 && DECL_LANGUAGE (newdecl) != DECL_LANGUAGE (olddecl))
2044 /* [dcl.link]
2045 If two declarations of the same function or object
2046 specify different linkage-specifications ..., the program
2047 is ill-formed.... Except for functions with C++ linkage,
2048 a function declaration without a linkage specification
2049 shall not precede the first linkage specification for
2050 that function. A function can be declared without a
2051 linkage specification after an explicit linkage
2052 specification has been seen; the linkage explicitly
2053 specified in the earlier declaration is not affected by
2054 such a function declaration.
2056 DR 563 raises the question why the restrictions on
2057 functions should not also apply to objects. Older
2058 versions of G++ silently ignore the linkage-specification
2059 for this example:
2061 namespace N {
2062 extern int i;
2063 extern "C" int i;
2066 which is clearly wrong. Therefore, we now treat objects
2067 like functions. */
2068 if (current_lang_depth () == 0)
2070 /* There is no explicit linkage-specification, so we use
2071 the linkage from the previous declaration. */
2072 retrofit_lang_decl (newdecl);
2073 SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
2075 else
2077 auto_diagnostic_group d;
2078 error_at (newdecl_loc,
2079 "conflicting declaration of %q#D with %qL linkage",
2080 newdecl, DECL_LANGUAGE (newdecl));
2081 inform (olddecl_loc,
2082 "previous declaration with %qL linkage",
2083 DECL_LANGUAGE (olddecl));
2087 if (DECL_LANG_SPECIFIC (olddecl) && DECL_USE_TEMPLATE (olddecl))
2089 else if (TREE_CODE (olddecl) == FUNCTION_DECL)
2091 /* Note: free functions, as TEMPLATE_DECLs, are handled below. */
2092 if (DECL_FUNCTION_MEMBER_P (olddecl)
2093 && (/* grokfndecl passes member function templates too
2094 as FUNCTION_DECLs. */
2095 DECL_TEMPLATE_INFO (olddecl)
2096 /* C++11 8.3.6/6.
2097 Default arguments for a member function of a class
2098 template shall be specified on the initial declaration
2099 of the member function within the class template. */
2100 || CLASSTYPE_TEMPLATE_INFO (CP_DECL_CONTEXT (olddecl))))
2102 check_redeclaration_no_default_args (newdecl);
2104 if (DECL_TEMPLATE_INFO (olddecl)
2105 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (olddecl)))
2107 tree new_parms = DECL_TEMPLATE_INFO (newdecl)
2108 ? DECL_INNERMOST_TEMPLATE_PARMS (DECL_TI_TEMPLATE (newdecl))
2109 : INNERMOST_TEMPLATE_PARMS (current_template_parms);
2110 tree old_parms
2111 = DECL_INNERMOST_TEMPLATE_PARMS (DECL_TI_TEMPLATE (olddecl));
2112 merge_default_template_args (new_parms, old_parms,
2113 /*class_p=*/false);
2116 else
2118 tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl);
2119 tree t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
2120 int i = 1;
2122 for (; t1 && t1 != void_list_node;
2123 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2), i++)
2124 if (TREE_PURPOSE (t1) && TREE_PURPOSE (t2))
2126 if (simple_cst_equal (TREE_PURPOSE (t1),
2127 TREE_PURPOSE (t2)) == 1)
2129 auto_diagnostic_group d;
2130 if (permerror (newdecl_loc,
2131 "default argument given for parameter "
2132 "%d of %q#D", i, newdecl))
2133 inform (olddecl_loc,
2134 "previous specification in %q#D here",
2135 olddecl);
2137 else
2139 auto_diagnostic_group d;
2140 error_at (newdecl_loc,
2141 "default argument given for parameter %d "
2142 "of %q#D", i, newdecl);
2143 inform (olddecl_loc,
2144 "previous specification in %q#D here",
2145 olddecl);
2149 /* C++17 11.3.6/4: "If a friend declaration specifies a default
2150 argument expression, that declaration... shall be the only
2151 declaration of the function or function template in the
2152 translation unit." */
2153 check_no_redeclaration_friend_default_args (olddecl, newdecl);
2158 /* Do not merge an implicit typedef with an explicit one. In:
2160 class A;
2162 typedef class A A __attribute__ ((foo));
2164 the attribute should apply only to the typedef. */
2165 if (TREE_CODE (olddecl) == TYPE_DECL
2166 && (DECL_IMPLICIT_TYPEDEF_P (olddecl)
2167 || DECL_IMPLICIT_TYPEDEF_P (newdecl)))
2168 return NULL_TREE;
2170 if (DECL_TEMPLATE_PARM_P (olddecl) != DECL_TEMPLATE_PARM_P (newdecl))
2171 return NULL_TREE;
2173 if (!validate_constexpr_redeclaration (olddecl, newdecl))
2174 return error_mark_node;
2176 if (modules_p ()
2177 && TREE_CODE (CP_DECL_CONTEXT (olddecl)) == NAMESPACE_DECL
2178 && TREE_CODE (olddecl) != NAMESPACE_DECL
2179 && !hiding)
2181 if (!module_may_redeclare (olddecl))
2183 if (DECL_ARTIFICIAL (olddecl))
2184 error ("declaration %qD conflicts with builtin", newdecl);
2185 else
2187 error ("declaration %qD conflicts with import", newdecl);
2188 inform (olddecl_loc, "import declared %q#D here", olddecl);
2191 return error_mark_node;
2194 tree not_tmpl = STRIP_TEMPLATE (olddecl);
2195 if (DECL_LANG_SPECIFIC (not_tmpl) && DECL_MODULE_ATTACH_P (not_tmpl))
2197 if (DECL_MODULE_EXPORT_P (STRIP_TEMPLATE (newdecl))
2198 && !DECL_MODULE_EXPORT_P (not_tmpl))
2200 error ("conflicting exporting declaration %qD", newdecl);
2201 inform (olddecl_loc, "previous declaration %q#D here", olddecl);
2204 else if (DECL_MODULE_EXPORT_P (newdecl))
2205 DECL_MODULE_EXPORT_P (not_tmpl) = true;
2208 /* We have committed to returning OLDDECL at this point. */
2210 /* If new decl is `static' and an `extern' was seen previously,
2211 warn about it. */
2212 warn_extern_redeclared_static (newdecl, olddecl);
2214 /* True to merge attributes between the declarations, false to
2215 set OLDDECL's attributes to those of NEWDECL (for template
2216 explicit specializations that specify their own attributes
2217 independent of those specified for the primary template). */
2218 const bool merge_attr = (TREE_CODE (newdecl) != FUNCTION_DECL
2219 || !DECL_TEMPLATE_SPECIALIZATION (newdecl)
2220 || DECL_TEMPLATE_SPECIALIZATION (olddecl));
2222 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2224 if (merge_attr)
2226 if (diagnose_mismatched_attributes (olddecl, newdecl))
2227 inform (olddecl_loc, DECL_INITIAL (olddecl)
2228 ? G_("previous definition of %qD here")
2229 : G_("previous declaration of %qD here"), olddecl);
2231 /* [dcl.attr.noreturn]: The first declaration of a function shall
2232 specify the noreturn attribute if any declaration of that function
2233 specifies the noreturn attribute. */
2234 tree a;
2235 if (TREE_THIS_VOLATILE (newdecl)
2236 && !TREE_THIS_VOLATILE (olddecl)
2237 /* This applies to [[noreturn]] only, not its GNU variants. */
2238 && (a = lookup_attribute ("noreturn", DECL_ATTRIBUTES (newdecl)))
2239 && cxx11_attribute_p (a)
2240 && get_attribute_namespace (a) == NULL_TREE)
2242 error_at (newdecl_loc, "function %qD declared %<[[noreturn]]%> "
2243 "but its first declaration was not", newdecl);
2244 inform (olddecl_loc, "previous declaration of %qD", olddecl);
2248 /* Now that functions must hold information normally held
2249 by field decls, there is extra work to do so that
2250 declaration information does not get destroyed during
2251 definition. */
2252 if (DECL_VINDEX (olddecl))
2253 DECL_VINDEX (newdecl) = DECL_VINDEX (olddecl);
2254 if (DECL_CONTEXT (olddecl))
2255 DECL_CONTEXT (newdecl) = DECL_CONTEXT (olddecl);
2256 DECL_STATIC_CONSTRUCTOR (newdecl) |= DECL_STATIC_CONSTRUCTOR (olddecl);
2257 DECL_STATIC_DESTRUCTOR (newdecl) |= DECL_STATIC_DESTRUCTOR (olddecl);
2258 DECL_PURE_VIRTUAL_P (newdecl) |= DECL_PURE_VIRTUAL_P (olddecl);
2259 DECL_VIRTUAL_P (newdecl) |= DECL_VIRTUAL_P (olddecl);
2260 DECL_INVALID_OVERRIDER_P (newdecl) |= DECL_INVALID_OVERRIDER_P (olddecl);
2261 DECL_FINAL_P (newdecl) |= DECL_FINAL_P (olddecl);
2262 DECL_OVERRIDE_P (newdecl) |= DECL_OVERRIDE_P (olddecl);
2263 DECL_THIS_STATIC (newdecl) |= DECL_THIS_STATIC (olddecl);
2264 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (newdecl)
2265 |= DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (olddecl);
2266 if (DECL_OVERLOADED_OPERATOR_P (olddecl))
2267 DECL_OVERLOADED_OPERATOR_CODE_RAW (newdecl)
2268 = DECL_OVERLOADED_OPERATOR_CODE_RAW (olddecl);
2269 new_defines_function = DECL_INITIAL (newdecl) != NULL_TREE;
2271 duplicate_contracts (newdecl, olddecl);
2273 /* Optionally warn about more than one declaration for the same
2274 name, but don't warn about a function declaration followed by a
2275 definition. */
2276 if (warn_redundant_decls && ! DECL_ARTIFICIAL (olddecl)
2277 && !(new_defines_function && DECL_INITIAL (olddecl) == NULL_TREE)
2278 /* Don't warn about extern decl followed by definition. */
2279 && !(DECL_EXTERNAL (olddecl) && ! DECL_EXTERNAL (newdecl))
2280 /* Don't warn if at least one is/was hidden. */
2281 && !(hiding || was_hidden)
2282 /* Don't warn about declaration followed by specialization. */
2283 && (! DECL_TEMPLATE_SPECIALIZATION (newdecl)
2284 || DECL_TEMPLATE_SPECIALIZATION (olddecl)))
2286 auto_diagnostic_group d;
2287 if (warning_at (newdecl_loc,
2288 OPT_Wredundant_decls,
2289 "redundant redeclaration of %qD in same scope",
2290 newdecl))
2291 inform (olddecl_loc,
2292 "previous declaration of %qD", olddecl);
2295 /* [dcl.fct.def.delete] A deleted definition of a function shall be the
2296 first declaration of the function or, for an explicit specialization
2297 of a function template, the first declaration of that
2298 specialization. */
2299 if (!(DECL_TEMPLATE_INSTANTIATION (olddecl)
2300 && DECL_TEMPLATE_SPECIALIZATION (newdecl)))
2302 if (DECL_DELETED_FN (newdecl))
2304 auto_diagnostic_group d;
2305 if (pedwarn (newdecl_loc, 0, "deleted definition of %qD "
2306 "is not first declaration", newdecl))
2307 inform (olddecl_loc,
2308 "previous declaration of %qD", olddecl);
2310 DECL_DELETED_FN (newdecl) |= DECL_DELETED_FN (olddecl);
2314 /* Deal with C++: must preserve virtual function table size. */
2315 if (TREE_CODE (olddecl) == TYPE_DECL)
2317 tree newtype = TREE_TYPE (newdecl);
2318 tree oldtype = TREE_TYPE (olddecl);
2320 if (newtype != error_mark_node && oldtype != error_mark_node
2321 && TYPE_LANG_SPECIFIC (newtype) && TYPE_LANG_SPECIFIC (oldtype))
2322 CLASSTYPE_FRIEND_CLASSES (newtype)
2323 = CLASSTYPE_FRIEND_CLASSES (oldtype);
2325 DECL_ORIGINAL_TYPE (newdecl) = DECL_ORIGINAL_TYPE (olddecl);
2328 /* Copy all the DECL_... slots specified in the new decl except for
2329 any that we copy here from the old type. */
2330 if (merge_attr)
2331 DECL_ATTRIBUTES (newdecl)
2332 = (*targetm.merge_decl_attributes) (olddecl, newdecl);
2333 else
2334 DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
2336 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
2338 tree old_result = DECL_TEMPLATE_RESULT (olddecl);
2339 tree new_result = DECL_TEMPLATE_RESULT (newdecl);
2340 TREE_TYPE (olddecl) = TREE_TYPE (old_result);
2342 /* The new decl should not already have gathered any
2343 specializations. */
2344 gcc_assert (!DECL_TEMPLATE_SPECIALIZATIONS (newdecl));
2346 /* Make sure the contracts are equivalent. */
2347 duplicate_contracts (newdecl, olddecl);
2349 /* Remove contracts from old_result so they aren't appended to
2350 old_result by the merge function. */
2351 remove_contract_attributes (old_result);
2353 DECL_ATTRIBUTES (old_result)
2354 = (*targetm.merge_decl_attributes) (old_result, new_result);
2356 if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2358 if (DECL_SOURCE_LOCATION (newdecl)
2359 != DECL_SOURCE_LOCATION (olddecl))
2361 /* Per C++11 8.3.6/4, default arguments cannot be added in
2362 later declarations of a function template. */
2363 check_redeclaration_no_default_args (newdecl);
2364 /* C++17 11.3.6/4: "If a friend declaration specifies a default
2365 argument expression, that declaration... shall be the only
2366 declaration of the function or function template in the
2367 translation unit." */
2368 check_no_redeclaration_friend_default_args
2369 (old_result, new_result);
2371 tree new_parms = DECL_INNERMOST_TEMPLATE_PARMS (newdecl);
2372 tree old_parms = DECL_INNERMOST_TEMPLATE_PARMS (olddecl);
2373 merge_default_template_args (new_parms, old_parms,
2374 /*class_p=*/false);
2376 if (!DECL_UNIQUE_FRIEND_P (new_result))
2377 DECL_UNIQUE_FRIEND_P (old_result) = false;
2379 check_default_args (newdecl);
2381 if (GNU_INLINE_P (old_result) != GNU_INLINE_P (new_result)
2382 && DECL_INITIAL (new_result))
2384 if (DECL_INITIAL (old_result))
2385 DECL_UNINLINABLE (old_result) = 1;
2386 else
2387 DECL_UNINLINABLE (old_result) = DECL_UNINLINABLE (new_result);
2388 DECL_EXTERNAL (old_result) = DECL_EXTERNAL (new_result);
2389 DECL_NOT_REALLY_EXTERN (old_result)
2390 = DECL_NOT_REALLY_EXTERN (new_result);
2391 DECL_INTERFACE_KNOWN (old_result)
2392 = DECL_INTERFACE_KNOWN (new_result);
2393 DECL_DECLARED_INLINE_P (old_result)
2394 = DECL_DECLARED_INLINE_P (new_result);
2395 DECL_DISREGARD_INLINE_LIMITS (old_result)
2396 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2398 else
2400 DECL_DECLARED_INLINE_P (old_result)
2401 |= DECL_DECLARED_INLINE_P (new_result);
2402 DECL_DISREGARD_INLINE_LIMITS (old_result)
2403 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2404 check_redeclaration_exception_specification (newdecl, olddecl);
2406 merge_attribute_bits (new_result, old_result);
2410 /* If the new declaration is a definition, update the file and
2411 line information on the declaration, and also make
2412 the old declaration the same definition. */
2413 if (DECL_INITIAL (new_result) != NULL_TREE)
2415 DECL_SOURCE_LOCATION (olddecl)
2416 = DECL_SOURCE_LOCATION (old_result)
2417 = DECL_SOURCE_LOCATION (newdecl);
2418 DECL_INITIAL (old_result) = DECL_INITIAL (new_result);
2419 if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2421 DECL_ARGUMENTS (old_result) = DECL_ARGUMENTS (new_result);
2422 for (tree p = DECL_ARGUMENTS (old_result); p; p = DECL_CHAIN (p))
2423 DECL_CONTEXT (p) = old_result;
2425 if (tree fc = DECL_FRIEND_CONTEXT (new_result))
2426 SET_DECL_FRIEND_CONTEXT (old_result, fc);
2430 return olddecl;
2433 if (types_match)
2435 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2436 check_redeclaration_exception_specification (newdecl, olddecl);
2438 /* Automatically handles default parameters. */
2439 tree oldtype = TREE_TYPE (olddecl);
2440 tree newtype;
2442 /* For typedefs use the old type, as the new type's DECL_NAME points
2443 at newdecl, which will be ggc_freed. */
2444 if (TREE_CODE (newdecl) == TYPE_DECL)
2446 /* But NEWTYPE might have an attribute, honor that. */
2447 tree tem = TREE_TYPE (newdecl);
2448 newtype = oldtype;
2450 if (TYPE_USER_ALIGN (tem))
2452 if (TYPE_ALIGN (tem) > TYPE_ALIGN (newtype))
2453 SET_TYPE_ALIGN (newtype, TYPE_ALIGN (tem));
2454 TYPE_USER_ALIGN (newtype) = true;
2457 /* And remove the new type from the variants list. */
2458 if (TYPE_NAME (TREE_TYPE (newdecl)) == newdecl)
2460 tree remove = TREE_TYPE (newdecl);
2461 if (TYPE_MAIN_VARIANT (remove) == remove)
2463 gcc_assert (TYPE_NEXT_VARIANT (remove) == NULL_TREE);
2464 /* If remove is the main variant, no need to remove that
2465 from the list. One of the DECL_ORIGINAL_TYPE
2466 variants, e.g. created for aligned attribute, might still
2467 refer to the newdecl TYPE_DECL though, so remove that one
2468 in that case. */
2469 if (tree orig = DECL_ORIGINAL_TYPE (newdecl))
2470 if (orig != remove)
2471 for (tree t = TYPE_MAIN_VARIANT (orig); t;
2472 t = TYPE_MAIN_VARIANT (t))
2473 if (TYPE_NAME (TYPE_NEXT_VARIANT (t)) == newdecl)
2475 TYPE_NEXT_VARIANT (t)
2476 = TYPE_NEXT_VARIANT (TYPE_NEXT_VARIANT (t));
2477 break;
2480 else
2481 for (tree t = TYPE_MAIN_VARIANT (remove); ;
2482 t = TYPE_NEXT_VARIANT (t))
2483 if (TYPE_NEXT_VARIANT (t) == remove)
2485 TYPE_NEXT_VARIANT (t) = TYPE_NEXT_VARIANT (remove);
2486 break;
2490 else if (merge_attr)
2491 newtype = merge_types (TREE_TYPE (newdecl), TREE_TYPE (olddecl));
2492 else
2493 newtype = TREE_TYPE (newdecl);
2495 if (VAR_P (newdecl))
2497 DECL_THIS_EXTERN (newdecl) |= DECL_THIS_EXTERN (olddecl);
2498 /* For already initialized vars, TREE_READONLY could have been
2499 cleared in cp_finish_decl, because the var needs runtime
2500 initialization or destruction. Make sure not to set
2501 TREE_READONLY on it again. */
2502 if (DECL_INITIALIZED_P (olddecl)
2503 && !DECL_EXTERNAL (olddecl)
2504 && !TREE_READONLY (olddecl))
2505 TREE_READONLY (newdecl) = 0;
2506 DECL_INITIALIZED_P (newdecl) |= DECL_INITIALIZED_P (olddecl);
2507 DECL_NONTRIVIALLY_INITIALIZED_P (newdecl)
2508 |= DECL_NONTRIVIALLY_INITIALIZED_P (olddecl);
2509 if (DECL_DEPENDENT_INIT_P (olddecl))
2510 SET_DECL_DEPENDENT_INIT_P (newdecl, true);
2511 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (newdecl)
2512 |= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (olddecl);
2513 DECL_DECLARED_CONSTEXPR_P (newdecl)
2514 |= DECL_DECLARED_CONSTEXPR_P (olddecl);
2515 DECL_DECLARED_CONSTINIT_P (newdecl)
2516 |= DECL_DECLARED_CONSTINIT_P (olddecl);
2518 /* Merge the threadprivate attribute from OLDDECL into NEWDECL. */
2519 if (DECL_LANG_SPECIFIC (olddecl)
2520 && CP_DECL_THREADPRIVATE_P (olddecl))
2522 /* Allocate a LANG_SPECIFIC structure for NEWDECL, if needed. */
2523 retrofit_lang_decl (newdecl);
2524 CP_DECL_THREADPRIVATE_P (newdecl) = 1;
2528 /* An explicit specialization of a function template or of a member
2529 function of a class template can be declared transaction_safe
2530 independently of whether the corresponding template entity is declared
2531 transaction_safe. */
2532 if (flag_tm && TREE_CODE (newdecl) == FUNCTION_DECL
2533 && DECL_TEMPLATE_INSTANTIATION (olddecl)
2534 && DECL_TEMPLATE_SPECIALIZATION (newdecl)
2535 && tx_safe_fn_type_p (newtype)
2536 && !tx_safe_fn_type_p (TREE_TYPE (newdecl)))
2537 newtype = tx_unsafe_fn_variant (newtype);
2539 TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = newtype;
2541 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2542 check_default_args (newdecl);
2544 /* Lay the type out, unless already done. */
2545 if (! same_type_p (newtype, oldtype)
2546 && TREE_TYPE (newdecl) != error_mark_node
2547 && !(processing_template_decl && uses_template_parms (newdecl)))
2548 layout_type (TREE_TYPE (newdecl));
2550 if ((VAR_P (newdecl)
2551 || TREE_CODE (newdecl) == PARM_DECL
2552 || TREE_CODE (newdecl) == RESULT_DECL
2553 || TREE_CODE (newdecl) == FIELD_DECL
2554 || TREE_CODE (newdecl) == TYPE_DECL)
2555 && !(processing_template_decl && uses_template_parms (newdecl)))
2556 layout_decl (newdecl, 0);
2558 /* Merge deprecatedness. */
2559 if (TREE_DEPRECATED (newdecl))
2560 TREE_DEPRECATED (olddecl) = 1;
2562 /* Merge unavailability. */
2563 if (TREE_UNAVAILABLE (newdecl))
2564 TREE_UNAVAILABLE (olddecl) = 1;
2566 /* Preserve function specific target and optimization options */
2567 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2569 if (DECL_FUNCTION_SPECIFIC_TARGET (olddecl)
2570 && !DECL_FUNCTION_SPECIFIC_TARGET (newdecl))
2571 DECL_FUNCTION_SPECIFIC_TARGET (newdecl)
2572 = DECL_FUNCTION_SPECIFIC_TARGET (olddecl);
2574 if (DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl)
2575 && !DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl))
2576 DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl)
2577 = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl);
2579 if (!DECL_UNIQUE_FRIEND_P (olddecl))
2580 DECL_UNIQUE_FRIEND_P (newdecl) = false;
2582 else
2584 /* Merge the const type qualifier. */
2585 if (TREE_READONLY (newdecl))
2586 TREE_READONLY (olddecl) = 1;
2587 /* Merge the volatile type qualifier. */
2588 if (TREE_THIS_VOLATILE (newdecl))
2589 TREE_THIS_VOLATILE (olddecl) = 1;
2592 /* Merge the initialization information. */
2593 if (DECL_INITIAL (newdecl) == NULL_TREE
2594 && DECL_INITIAL (olddecl) != NULL_TREE)
2596 DECL_INITIAL (newdecl) = DECL_INITIAL (olddecl);
2597 DECL_SOURCE_LOCATION (newdecl) = DECL_SOURCE_LOCATION (olddecl);
2598 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2600 DECL_SAVED_TREE (newdecl) = DECL_SAVED_TREE (olddecl);
2601 DECL_STRUCT_FUNCTION (newdecl) = DECL_STRUCT_FUNCTION (olddecl);
2605 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2607 DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (newdecl)
2608 |= DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (olddecl);
2609 DECL_NO_LIMIT_STACK (newdecl) |= DECL_NO_LIMIT_STACK (olddecl);
2610 if (DECL_IS_OPERATOR_NEW_P (olddecl))
2611 DECL_SET_IS_OPERATOR_NEW (newdecl, true);
2612 DECL_LOOPING_CONST_OR_PURE_P (newdecl)
2613 |= DECL_LOOPING_CONST_OR_PURE_P (olddecl);
2614 DECL_IS_REPLACEABLE_OPERATOR (newdecl)
2615 |= DECL_IS_REPLACEABLE_OPERATOR (olddecl);
2617 if (merge_attr)
2618 merge_attribute_bits (newdecl, olddecl);
2619 else
2621 /* Merge the noreturn bit. */
2622 TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2623 TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2624 TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2625 DECL_IS_MALLOC (olddecl) = DECL_IS_MALLOC (newdecl);
2626 DECL_PURE_P (olddecl) = DECL_PURE_P (newdecl);
2628 /* Keep the old RTL. */
2629 COPY_DECL_RTL (olddecl, newdecl);
2631 else if (VAR_P (newdecl)
2632 && (DECL_SIZE (olddecl) || !DECL_SIZE (newdecl)))
2634 /* Keep the old RTL. We cannot keep the old RTL if the old
2635 declaration was for an incomplete object and the new
2636 declaration is not since many attributes of the RTL will
2637 change. */
2638 COPY_DECL_RTL (olddecl, newdecl);
2641 /* If cannot merge, then use the new type and qualifiers,
2642 and don't preserve the old rtl. */
2643 else
2645 /* Clean out any memory we had of the old declaration. */
2646 tree oldstatic = value_member (olddecl, static_aggregates);
2647 if (oldstatic)
2648 TREE_VALUE (oldstatic) = error_mark_node;
2650 TREE_TYPE (olddecl) = TREE_TYPE (newdecl);
2651 TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2652 TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2653 TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2654 TREE_SIDE_EFFECTS (olddecl) = TREE_SIDE_EFFECTS (newdecl);
2657 /* Merge the storage class information. */
2658 merge_weak (newdecl, olddecl);
2660 DECL_DEFER_OUTPUT (newdecl) |= DECL_DEFER_OUTPUT (olddecl);
2661 TREE_PUBLIC (newdecl) = TREE_PUBLIC (olddecl);
2662 TREE_STATIC (olddecl) = TREE_STATIC (newdecl) |= TREE_STATIC (olddecl);
2663 if (! DECL_EXTERNAL (olddecl))
2664 DECL_EXTERNAL (newdecl) = 0;
2665 if (! DECL_COMDAT (olddecl))
2666 DECL_COMDAT (newdecl) = 0;
2668 if (VAR_OR_FUNCTION_DECL_P (newdecl) && DECL_LOCAL_DECL_P (newdecl))
2670 if (!DECL_LOCAL_DECL_P (olddecl))
2671 /* This can happen if olddecl was brought in from the
2672 enclosing namespace via a using-decl. The new decl is
2673 then not a block-scope extern at all. */
2674 DECL_LOCAL_DECL_P (newdecl) = false;
2675 else
2677 retrofit_lang_decl (newdecl);
2678 tree alias = DECL_LOCAL_DECL_ALIAS (newdecl)
2679 = DECL_LOCAL_DECL_ALIAS (olddecl);
2680 DECL_ATTRIBUTES (alias)
2681 = (*targetm.merge_decl_attributes) (alias, newdecl);
2682 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2683 merge_attribute_bits (newdecl, alias);
2687 new_template_info = NULL_TREE;
2688 if (DECL_LANG_SPECIFIC (newdecl) && DECL_LANG_SPECIFIC (olddecl))
2690 bool new_redefines_gnu_inline = false;
2692 if (new_defines_function
2693 && ((DECL_INTERFACE_KNOWN (olddecl)
2694 && TREE_CODE (olddecl) == FUNCTION_DECL)
2695 || (TREE_CODE (olddecl) == TEMPLATE_DECL
2696 && (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl))
2697 == FUNCTION_DECL))))
2698 new_redefines_gnu_inline = GNU_INLINE_P (STRIP_TEMPLATE (olddecl));
2700 if (!new_redefines_gnu_inline)
2702 DECL_INTERFACE_KNOWN (newdecl) |= DECL_INTERFACE_KNOWN (olddecl);
2703 DECL_NOT_REALLY_EXTERN (newdecl) |= DECL_NOT_REALLY_EXTERN (olddecl);
2704 DECL_COMDAT (newdecl) |= DECL_COMDAT (olddecl);
2707 if (TREE_CODE (newdecl) != TYPE_DECL)
2709 DECL_TEMPLATE_INSTANTIATED (newdecl)
2710 |= DECL_TEMPLATE_INSTANTIATED (olddecl);
2711 DECL_ODR_USED (newdecl) |= DECL_ODR_USED (olddecl);
2713 /* If the OLDDECL is an instantiation and/or specialization,
2714 then the NEWDECL must be too. But, it may not yet be marked
2715 as such if the caller has created NEWDECL, but has not yet
2716 figured out that it is a redeclaration. */
2717 if (!DECL_USE_TEMPLATE (newdecl))
2718 DECL_USE_TEMPLATE (newdecl) = DECL_USE_TEMPLATE (olddecl);
2720 if (!DECL_TEMPLATE_SPECIALIZATION (newdecl))
2721 DECL_INITIALIZED_IN_CLASS_P (newdecl)
2722 |= DECL_INITIALIZED_IN_CLASS_P (olddecl);
2725 /* Don't really know how much of the language-specific
2726 values we should copy from old to new. */
2727 DECL_IN_AGGR_P (newdecl) = DECL_IN_AGGR_P (olddecl);
2729 if (LANG_DECL_HAS_MIN (newdecl))
2731 DECL_ACCESS (newdecl) = DECL_ACCESS (olddecl);
2732 if (DECL_TEMPLATE_INFO (newdecl))
2734 new_template_info = DECL_TEMPLATE_INFO (newdecl);
2735 if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2736 && DECL_TEMPLATE_SPECIALIZATION (newdecl))
2737 /* Remember the presence of explicit specialization args. */
2738 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (olddecl))
2739 = TINFO_USED_TEMPLATE_ID (new_template_info);
2742 /* We don't want to copy template info from a non-templated friend
2743 (PR105761), but these shouldn't have DECL_TEMPLATE_INFO now. */
2744 gcc_checking_assert (!DECL_TEMPLATE_INFO (olddecl)
2745 || !non_templated_friend_p (olddecl));
2746 DECL_TEMPLATE_INFO (newdecl) = DECL_TEMPLATE_INFO (olddecl);
2749 if (DECL_DECLARES_FUNCTION_P (newdecl))
2751 /* Only functions have these fields. */
2752 DECL_NONCONVERTING_P (newdecl) = DECL_NONCONVERTING_P (olddecl);
2753 DECL_BEFRIENDING_CLASSES (newdecl)
2754 = chainon (DECL_BEFRIENDING_CLASSES (newdecl),
2755 DECL_BEFRIENDING_CLASSES (olddecl));
2756 /* DECL_THUNKS is only valid for virtual functions,
2757 otherwise it is a DECL_FRIEND_CONTEXT. */
2758 if (DECL_VIRTUAL_P (newdecl))
2759 SET_DECL_THUNKS (newdecl, DECL_THUNKS (olddecl));
2760 else if (tree fc = DECL_FRIEND_CONTEXT (newdecl))
2761 SET_DECL_FRIEND_CONTEXT (olddecl, fc);
2763 else if (VAR_P (newdecl))
2765 /* Only variables have this field. */
2766 if (VAR_HAD_UNKNOWN_BOUND (olddecl))
2767 SET_VAR_HAD_UNKNOWN_BOUND (newdecl);
2771 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2773 tree parm;
2775 /* Merge parameter attributes. */
2776 tree oldarg, newarg;
2777 for (oldarg = DECL_ARGUMENTS(olddecl), newarg = DECL_ARGUMENTS(newdecl);
2778 oldarg && newarg;
2779 oldarg = DECL_CHAIN(oldarg), newarg = DECL_CHAIN(newarg))
2781 DECL_ATTRIBUTES (newarg)
2782 = (*targetm.merge_decl_attributes) (oldarg, newarg);
2783 DECL_ATTRIBUTES (oldarg) = DECL_ATTRIBUTES (newarg);
2786 if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2787 && !DECL_TEMPLATE_INSTANTIATION (newdecl))
2789 /* If newdecl is not a specialization, then it is not a
2790 template-related function at all. And that means that we
2791 should have exited above, returning 0. */
2792 gcc_assert (DECL_TEMPLATE_SPECIALIZATION (newdecl));
2794 if (DECL_ODR_USED (olddecl))
2795 /* From [temp.expl.spec]:
2797 If a template, a member template or the member of a class
2798 template is explicitly specialized then that
2799 specialization shall be declared before the first use of
2800 that specialization that would cause an implicit
2801 instantiation to take place, in every translation unit in
2802 which such a use occurs. */
2803 error ("explicit specialization of %qD after first use",
2804 olddecl);
2806 SET_DECL_TEMPLATE_SPECIALIZATION (olddecl);
2807 DECL_COMDAT (newdecl) = (TREE_PUBLIC (newdecl)
2808 && DECL_DECLARED_INLINE_P (newdecl));
2810 /* Don't propagate visibility from the template to the
2811 specialization here. We'll do that in determine_visibility if
2812 appropriate. */
2813 DECL_VISIBILITY_SPECIFIED (olddecl) = 0;
2815 /* [temp.expl.spec/14] We don't inline explicit specialization
2816 just because the primary template says so. */
2817 gcc_assert (!merge_attr);
2819 DECL_DECLARED_INLINE_P (olddecl)
2820 = DECL_DECLARED_INLINE_P (newdecl);
2822 DECL_DISREGARD_INLINE_LIMITS (olddecl)
2823 = DECL_DISREGARD_INLINE_LIMITS (newdecl);
2825 DECL_UNINLINABLE (olddecl) = DECL_UNINLINABLE (newdecl);
2827 else if (new_defines_function && DECL_INITIAL (olddecl))
2829 /* Never inline re-defined extern inline functions.
2830 FIXME: this could be better handled by keeping both
2831 function as separate declarations. */
2832 DECL_UNINLINABLE (newdecl) = 1;
2834 else
2836 if (DECL_PENDING_INLINE_P (olddecl))
2838 DECL_PENDING_INLINE_P (newdecl) = 1;
2839 DECL_PENDING_INLINE_INFO (newdecl)
2840 = DECL_PENDING_INLINE_INFO (olddecl);
2842 else if (DECL_PENDING_INLINE_P (newdecl))
2844 else if (DECL_SAVED_AUTO_RETURN_TYPE (newdecl) == NULL)
2845 DECL_SAVED_AUTO_RETURN_TYPE (newdecl)
2846 = DECL_SAVED_AUTO_RETURN_TYPE (olddecl);
2848 DECL_DECLARED_INLINE_P (newdecl) |= DECL_DECLARED_INLINE_P (olddecl);
2850 DECL_UNINLINABLE (newdecl) = DECL_UNINLINABLE (olddecl)
2851 = (DECL_UNINLINABLE (newdecl) || DECL_UNINLINABLE (olddecl));
2853 DECL_DISREGARD_INLINE_LIMITS (newdecl)
2854 = DECL_DISREGARD_INLINE_LIMITS (olddecl)
2855 = (DECL_DISREGARD_INLINE_LIMITS (newdecl)
2856 || DECL_DISREGARD_INLINE_LIMITS (olddecl));
2859 /* Preserve abstractness on cloned [cd]tors. */
2860 DECL_ABSTRACT_P (newdecl) = DECL_ABSTRACT_P (olddecl);
2862 /* Update newdecl's parms to point at olddecl. */
2863 for (parm = DECL_ARGUMENTS (newdecl); parm;
2864 parm = DECL_CHAIN (parm))
2865 DECL_CONTEXT (parm) = olddecl;
2867 if (! types_match)
2869 SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
2870 COPY_DECL_ASSEMBLER_NAME (newdecl, olddecl);
2871 COPY_DECL_RTL (newdecl, olddecl);
2873 if (! types_match || new_defines_function)
2875 /* These are the final DECL_ARGUMENTS that will be used within the
2876 body; update any references to old DECL_ARGUMENTS in the
2877 contracts, if present. */
2878 if (tree contracts = DECL_CONTRACTS (newdecl))
2879 remap_contracts (olddecl, newdecl, contracts, true);
2881 /* These need to be copied so that the names are available.
2882 Note that if the types do match, we'll preserve inline
2883 info and other bits, but if not, we won't. */
2884 DECL_ARGUMENTS (olddecl) = DECL_ARGUMENTS (newdecl);
2885 DECL_RESULT (olddecl) = DECL_RESULT (newdecl);
2887 /* In some cases, duplicate_contracts will remove contracts from
2888 OLDDECL, to avoid duplications. Sometimes, the contracts end up
2889 shared. If we removed them, re-add them. */
2890 if (!DECL_CONTRACTS (olddecl))
2891 copy_contract_attributes (olddecl, newdecl);
2893 /* If redeclaring a builtin function, it stays built in
2894 if newdecl is a gnu_inline definition, or if newdecl is just
2895 a declaration. */
2896 if (fndecl_built_in_p (olddecl)
2897 && (new_defines_function ? GNU_INLINE_P (newdecl) : types_match))
2899 copy_decl_built_in_function (newdecl, olddecl);
2900 /* If we're keeping the built-in definition, keep the rtl,
2901 regardless of declaration matches. */
2902 COPY_DECL_RTL (olddecl, newdecl);
2903 if (DECL_BUILT_IN_CLASS (newdecl) == BUILT_IN_NORMAL)
2905 enum built_in_function fncode = DECL_FUNCTION_CODE (newdecl);
2906 if (builtin_decl_explicit_p (fncode))
2908 /* A compatible prototype of these builtin functions
2909 is seen, assume the runtime implements it with
2910 the expected semantics. */
2911 switch (fncode)
2913 case BUILT_IN_STPCPY:
2914 set_builtin_decl_implicit_p (fncode, true);
2915 break;
2916 default:
2917 set_builtin_decl_declared_p (fncode, true);
2918 break;
2922 copy_attributes_to_builtin (newdecl);
2925 if (new_defines_function)
2926 /* If defining a function declared with other language
2927 linkage, use the previously declared language linkage. */
2928 SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
2929 else if (types_match)
2931 DECL_RESULT (newdecl) = DECL_RESULT (olddecl);
2932 /* Don't clear out the arguments if we're just redeclaring a
2933 function. */
2934 if (DECL_ARGUMENTS (olddecl))
2936 /* If we removed contracts from previous definition, re-attach
2937 them. Otherwise, rewrite the contracts so they match the
2938 parameters of the new declaration. */
2939 if (DECL_INITIAL (olddecl)
2940 && DECL_CONTRACTS (newdecl)
2941 && !DECL_CONTRACTS (olddecl))
2942 copy_contract_attributes (olddecl, newdecl);
2943 else
2945 /* Temporarily undo the re-contexting of parameters so we can
2946 actually remap parameters. The inliner won't replace
2947 parameters if we don't do this. */
2948 tree args = DECL_ARGUMENTS (newdecl);
2949 for (tree p = args; p; p = DECL_CHAIN (p))
2950 DECL_CONTEXT (p) = newdecl;
2952 /* Save new argument names for use in contracts parsing,
2953 unless we've already started parsing the body of olddecl
2954 (particular issues arise when newdecl is from a prior
2955 friend decl with no argument names, see
2956 modules/contracts-tpl-friend-1). */
2957 if (tree contracts = DECL_CONTRACTS (olddecl))
2958 remap_contracts (newdecl, olddecl, contracts, true);
2960 /* And reverse this operation again. */
2961 for (tree p = args; p; p = DECL_CHAIN (p))
2962 DECL_CONTEXT (p) = olddecl;
2965 DECL_ARGUMENTS (newdecl) = DECL_ARGUMENTS (olddecl);
2969 else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
2970 NAMESPACE_LEVEL (newdecl) = NAMESPACE_LEVEL (olddecl);
2972 /* Now preserve various other info from the definition. */
2973 TREE_ADDRESSABLE (newdecl) = TREE_ADDRESSABLE (olddecl);
2974 TREE_ASM_WRITTEN (newdecl) = TREE_ASM_WRITTEN (olddecl);
2975 DECL_COMMON (newdecl) = DECL_COMMON (olddecl);
2976 COPY_DECL_ASSEMBLER_NAME (olddecl, newdecl);
2978 /* Warn about conflicting visibility specifications. */
2979 if (DECL_VISIBILITY_SPECIFIED (olddecl)
2980 && DECL_VISIBILITY_SPECIFIED (newdecl)
2981 && DECL_VISIBILITY (newdecl) != DECL_VISIBILITY (olddecl))
2983 auto_diagnostic_group d;
2984 if (warning_at (newdecl_loc, OPT_Wattributes,
2985 "%qD: visibility attribute ignored because it "
2986 "conflicts with previous declaration", newdecl))
2987 inform (olddecl_loc,
2988 "previous declaration of %qD", olddecl);
2990 /* Choose the declaration which specified visibility. */
2991 if (DECL_VISIBILITY_SPECIFIED (olddecl))
2993 DECL_VISIBILITY (newdecl) = DECL_VISIBILITY (olddecl);
2994 DECL_VISIBILITY_SPECIFIED (newdecl) = 1;
2996 /* Init priority used to be merged from newdecl to olddecl by the memcpy,
2997 so keep this behavior. */
2998 if (VAR_P (newdecl) && DECL_HAS_INIT_PRIORITY_P (newdecl))
3000 SET_DECL_INIT_PRIORITY (olddecl, DECL_INIT_PRIORITY (newdecl));
3001 DECL_HAS_INIT_PRIORITY_P (olddecl) = 1;
3003 /* Likewise for DECL_ALIGN, DECL_USER_ALIGN and DECL_PACKED. */
3004 if (DECL_ALIGN (olddecl) > DECL_ALIGN (newdecl))
3006 SET_DECL_ALIGN (newdecl, DECL_ALIGN (olddecl));
3007 DECL_USER_ALIGN (newdecl) |= DECL_USER_ALIGN (olddecl);
3009 else if (DECL_ALIGN (olddecl) == DECL_ALIGN (newdecl)
3010 && DECL_USER_ALIGN (olddecl) != DECL_USER_ALIGN (newdecl))
3011 DECL_USER_ALIGN (newdecl) = 1;
3013 DECL_USER_ALIGN (olddecl) = DECL_USER_ALIGN (newdecl);
3014 if (DECL_WARN_IF_NOT_ALIGN (olddecl)
3015 > DECL_WARN_IF_NOT_ALIGN (newdecl))
3016 SET_DECL_WARN_IF_NOT_ALIGN (newdecl,
3017 DECL_WARN_IF_NOT_ALIGN (olddecl));
3018 if (TREE_CODE (newdecl) == FIELD_DECL)
3019 DECL_PACKED (olddecl) = DECL_PACKED (newdecl);
3021 /* The DECL_LANG_SPECIFIC information in OLDDECL will be replaced
3022 with that from NEWDECL below. */
3023 if (DECL_LANG_SPECIFIC (olddecl))
3025 gcc_checking_assert (DECL_LANG_SPECIFIC (olddecl)
3026 != DECL_LANG_SPECIFIC (newdecl));
3027 ggc_free (DECL_LANG_SPECIFIC (olddecl));
3030 /* Merge the USED information. */
3031 if (TREE_USED (olddecl))
3032 TREE_USED (newdecl) = 1;
3033 else if (TREE_USED (newdecl))
3034 TREE_USED (olddecl) = 1;
3036 if (VAR_P (newdecl))
3038 if (DECL_READ_P (olddecl))
3039 DECL_READ_P (newdecl) = 1;
3040 else if (DECL_READ_P (newdecl))
3041 DECL_READ_P (olddecl) = 1;
3044 if (DECL_PRESERVE_P (olddecl))
3045 DECL_PRESERVE_P (newdecl) = 1;
3046 else if (DECL_PRESERVE_P (newdecl))
3047 DECL_PRESERVE_P (olddecl) = 1;
3049 /* Merge the DECL_FUNCTION_VERSIONED information. newdecl will be copied
3050 to olddecl and deleted. */
3051 if (TREE_CODE (newdecl) == FUNCTION_DECL
3052 && DECL_FUNCTION_VERSIONED (olddecl))
3054 /* Set the flag for newdecl so that it gets copied to olddecl. */
3055 DECL_FUNCTION_VERSIONED (newdecl) = 1;
3056 /* newdecl will be purged after copying to olddecl and is no longer
3057 a version. */
3058 cgraph_node::delete_function_version_by_decl (newdecl);
3061 if (TREE_CODE (newdecl) == FUNCTION_DECL)
3063 int function_size;
3064 struct symtab_node *snode = symtab_node::get (olddecl);
3066 function_size = sizeof (struct tree_decl_common);
3068 memcpy ((char *) olddecl + sizeof (struct tree_common),
3069 (char *) newdecl + sizeof (struct tree_common),
3070 function_size - sizeof (struct tree_common));
3072 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3073 (char *) newdecl + sizeof (struct tree_decl_common),
3074 sizeof (struct tree_function_decl) - sizeof (struct tree_decl_common));
3076 /* Preserve symtab node mapping. */
3077 olddecl->decl_with_vis.symtab_node = snode;
3079 if (new_template_info)
3080 /* If newdecl is a template instantiation, it is possible that
3081 the following sequence of events has occurred:
3083 o A friend function was declared in a class template. The
3084 class template was instantiated.
3086 o The instantiation of the friend declaration was
3087 recorded on the instantiation list, and is newdecl.
3089 o Later, however, instantiate_class_template called pushdecl
3090 on the newdecl to perform name injection. But, pushdecl in
3091 turn called duplicate_decls when it discovered that another
3092 declaration of a global function with the same name already
3093 existed.
3095 o Here, in duplicate_decls, we decided to clobber newdecl.
3097 If we're going to do that, we'd better make sure that
3098 olddecl, and not newdecl, is on the list of
3099 instantiations so that if we try to do the instantiation
3100 again we won't get the clobbered declaration. */
3101 reregister_specialization (newdecl,
3102 new_template_info,
3103 olddecl);
3105 else
3107 size_t size = tree_code_size (TREE_CODE (newdecl));
3109 memcpy ((char *) olddecl + sizeof (struct tree_common),
3110 (char *) newdecl + sizeof (struct tree_common),
3111 sizeof (struct tree_decl_common) - sizeof (struct tree_common));
3113 switch (TREE_CODE (newdecl))
3115 case LABEL_DECL:
3116 case VAR_DECL:
3117 case RESULT_DECL:
3118 case PARM_DECL:
3119 case FIELD_DECL:
3120 case TYPE_DECL:
3121 case CONST_DECL:
3123 struct symtab_node *snode = NULL;
3125 if (VAR_P (newdecl)
3126 && (TREE_STATIC (olddecl) || TREE_PUBLIC (olddecl)
3127 || DECL_EXTERNAL (olddecl)))
3128 snode = symtab_node::get (olddecl);
3129 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3130 (char *) newdecl + sizeof (struct tree_decl_common),
3131 size - sizeof (struct tree_decl_common)
3132 + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
3133 if (VAR_P (newdecl))
3134 olddecl->decl_with_vis.symtab_node = snode;
3136 break;
3137 default:
3138 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3139 (char *) newdecl + sizeof (struct tree_decl_common),
3140 sizeof (struct tree_decl_non_common) - sizeof (struct tree_decl_common)
3141 + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
3142 break;
3146 if (VAR_OR_FUNCTION_DECL_P (newdecl))
3148 if (DECL_EXTERNAL (olddecl)
3149 || TREE_PUBLIC (olddecl)
3150 || TREE_STATIC (olddecl))
3152 /* Merge the section attribute.
3153 We want to issue an error if the sections conflict but that must be
3154 done later in decl_attributes since we are called before attributes
3155 are assigned. */
3156 if (DECL_SECTION_NAME (newdecl) != NULL)
3157 set_decl_section_name (olddecl, newdecl);
3159 if (DECL_ONE_ONLY (newdecl))
3161 struct symtab_node *oldsym, *newsym;
3162 if (TREE_CODE (olddecl) == FUNCTION_DECL)
3163 oldsym = cgraph_node::get_create (olddecl);
3164 else
3165 oldsym = varpool_node::get_create (olddecl);
3166 newsym = symtab_node::get (newdecl);
3167 oldsym->set_comdat_group (newsym->get_comdat_group ());
3171 if (VAR_P (newdecl)
3172 && CP_DECL_THREAD_LOCAL_P (newdecl))
3174 CP_DECL_THREAD_LOCAL_P (olddecl) = true;
3175 if (!processing_template_decl)
3176 set_decl_tls_model (olddecl, DECL_TLS_MODEL (newdecl));
3180 DECL_UID (olddecl) = olddecl_uid;
3182 /* NEWDECL contains the merged attribute lists.
3183 Update OLDDECL to be the same. */
3184 DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
3186 /* If OLDDECL had its DECL_RTL instantiated, re-invoke make_decl_rtl
3187 so that encode_section_info has a chance to look at the new decl
3188 flags and attributes. */
3189 if (DECL_RTL_SET_P (olddecl)
3190 && (TREE_CODE (olddecl) == FUNCTION_DECL
3191 || (VAR_P (olddecl)
3192 && TREE_STATIC (olddecl))))
3193 make_decl_rtl (olddecl);
3195 /* The NEWDECL will no longer be needed. Because every out-of-class
3196 declaration of a member results in a call to duplicate_decls,
3197 freeing these nodes represents in a significant savings.
3199 Before releasing the node, be sore to remove function from symbol
3200 table that might have been inserted there to record comdat group.
3201 Be sure to however do not free DECL_STRUCT_FUNCTION because this
3202 structure is shared in between newdecl and oldecl. */
3203 if (TREE_CODE (newdecl) == FUNCTION_DECL)
3204 DECL_STRUCT_FUNCTION (newdecl) = NULL;
3205 if (VAR_OR_FUNCTION_DECL_P (newdecl))
3207 struct symtab_node *snode = symtab_node::get (newdecl);
3208 if (snode)
3209 snode->remove ();
3212 if (TREE_CODE (olddecl) == FUNCTION_DECL)
3214 tree clone;
3215 FOR_EACH_CLONE (clone, olddecl)
3217 DECL_ATTRIBUTES (clone) = DECL_ATTRIBUTES (olddecl);
3218 DECL_PRESERVE_P (clone) |= DECL_PRESERVE_P (olddecl);
3222 /* Remove the associated constraints for newdecl, if any, before
3223 reclaiming memory. */
3224 if (flag_concepts)
3225 remove_constraints (newdecl);
3227 ggc_free (newdecl);
3229 return olddecl;
3232 /* Return zero if the declaration NEWDECL is valid
3233 when the declaration OLDDECL (assumed to be for the same name)
3234 has already been seen.
3235 Otherwise return an error message format string with a %s
3236 where the identifier should go. */
3238 static const char *
3239 redeclaration_error_message (tree newdecl, tree olddecl)
3241 if (TREE_CODE (newdecl) == TYPE_DECL)
3243 /* Because C++ can put things into name space for free,
3244 constructs like "typedef struct foo { ... } foo"
3245 would look like an erroneous redeclaration. */
3246 if (same_type_p (TREE_TYPE (newdecl), TREE_TYPE (olddecl)))
3247 return NULL;
3248 else
3249 return G_("redefinition of %q#D");
3251 else if (TREE_CODE (newdecl) == FUNCTION_DECL)
3253 /* If this is a pure function, its olddecl will actually be
3254 the original initialization to `0' (which we force to call
3255 abort()). Don't complain about redefinition in this case. */
3256 if (DECL_LANG_SPECIFIC (olddecl) && DECL_PURE_VIRTUAL_P (olddecl)
3257 && DECL_INITIAL (olddecl) == NULL_TREE)
3258 return NULL;
3260 /* If both functions come from different namespaces, this is not
3261 a redeclaration - this is a conflict with a used function. */
3262 if (DECL_NAMESPACE_SCOPE_P (olddecl)
3263 && DECL_CONTEXT (olddecl) != DECL_CONTEXT (newdecl)
3264 && ! decls_match (olddecl, newdecl))
3265 return G_("%qD conflicts with used function");
3267 /* We'll complain about linkage mismatches in
3268 warn_extern_redeclared_static. */
3270 /* Defining the same name twice is no good. */
3271 if (decl_defined_p (olddecl)
3272 && decl_defined_p (newdecl))
3274 if (DECL_NAME (olddecl) == NULL_TREE)
3275 return G_("%q#D not declared in class");
3276 else if (!GNU_INLINE_P (olddecl)
3277 || GNU_INLINE_P (newdecl))
3278 return G_("redefinition of %q#D");
3281 if (DECL_DECLARED_INLINE_P (olddecl) && DECL_DECLARED_INLINE_P (newdecl))
3283 bool olda = GNU_INLINE_P (olddecl);
3284 bool newa = GNU_INLINE_P (newdecl);
3286 if (olda != newa)
3288 if (newa)
3289 return G_("%q+D redeclared inline with "
3290 "%<gnu_inline%> attribute");
3291 else
3292 return G_("%q+D redeclared inline without "
3293 "%<gnu_inline%> attribute");
3297 if (deduction_guide_p (olddecl)
3298 && deduction_guide_p (newdecl))
3299 return G_("deduction guide %q+D redeclared");
3301 /* [class.compare.default]: A definition of a comparison operator as
3302 defaulted that appears in a class shall be the first declaration of
3303 that function. */
3304 special_function_kind sfk = special_function_p (olddecl);
3305 if (sfk == sfk_comparison && DECL_DEFAULTED_FN (newdecl))
3306 return G_("comparison operator %q+D defaulted after "
3307 "its first declaration");
3309 check_abi_tag_redeclaration
3310 (olddecl, lookup_attribute ("abi_tag", DECL_ATTRIBUTES (olddecl)),
3311 lookup_attribute ("abi_tag", DECL_ATTRIBUTES (newdecl)));
3313 return NULL;
3315 else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
3317 tree nt, ot;
3319 if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == CONCEPT_DECL)
3320 return G_("redefinition of %q#D");
3322 if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) != FUNCTION_DECL)
3323 return redeclaration_error_message (DECL_TEMPLATE_RESULT (newdecl),
3324 DECL_TEMPLATE_RESULT (olddecl));
3326 if (DECL_TEMPLATE_RESULT (newdecl) == DECL_TEMPLATE_RESULT (olddecl))
3327 return NULL;
3329 nt = DECL_TEMPLATE_RESULT (newdecl);
3330 if (DECL_TEMPLATE_INFO (nt))
3331 nt = DECL_TEMPLATE_RESULT (template_for_substitution (nt));
3332 ot = DECL_TEMPLATE_RESULT (olddecl);
3333 if (DECL_TEMPLATE_INFO (ot))
3334 ot = DECL_TEMPLATE_RESULT (template_for_substitution (ot));
3335 if (DECL_INITIAL (nt) && DECL_INITIAL (ot)
3336 && (!GNU_INLINE_P (ot) || GNU_INLINE_P (nt)))
3337 return G_("redefinition of %q#D");
3339 if (DECL_DECLARED_INLINE_P (ot) && DECL_DECLARED_INLINE_P (nt))
3341 bool olda = GNU_INLINE_P (ot);
3342 bool newa = GNU_INLINE_P (nt);
3344 if (olda != newa)
3346 if (newa)
3347 return G_("%q+D redeclared inline with "
3348 "%<gnu_inline%> attribute");
3349 else
3350 return G_("%q+D redeclared inline without "
3351 "%<gnu_inline%> attribute");
3355 if (deduction_guide_p (olddecl)
3356 && deduction_guide_p (newdecl))
3357 return G_("deduction guide %q+D redeclared");
3359 /* Core issue #226 (C++11):
3361 If a friend function template declaration specifies a
3362 default template-argument, that declaration shall be a
3363 definition and shall be the only declaration of the
3364 function template in the translation unit. */
3365 if ((cxx_dialect != cxx98)
3366 && TREE_CODE (ot) == FUNCTION_DECL && DECL_UNIQUE_FRIEND_P (ot)
3367 && !check_default_tmpl_args (nt, DECL_TEMPLATE_PARMS (newdecl),
3368 /*is_primary=*/true,
3369 /*is_partial=*/false,
3370 /*is_friend_decl=*/2))
3371 return G_("redeclaration of friend %q#D "
3372 "may not have default template arguments");
3374 return NULL;
3376 else if (VAR_P (newdecl)
3377 && (CP_DECL_THREAD_LOCAL_P (newdecl)
3378 != CP_DECL_THREAD_LOCAL_P (olddecl))
3379 && (! DECL_LANG_SPECIFIC (olddecl)
3380 || ! CP_DECL_THREADPRIVATE_P (olddecl)
3381 || CP_DECL_THREAD_LOCAL_P (newdecl)))
3383 /* Only variables can be thread-local, and all declarations must
3384 agree on this property. */
3385 if (CP_DECL_THREAD_LOCAL_P (newdecl))
3386 return G_("thread-local declaration of %q#D follows "
3387 "non-thread-local declaration");
3388 else
3389 return G_("non-thread-local declaration of %q#D follows "
3390 "thread-local declaration");
3392 else if (toplevel_bindings_p () || DECL_NAMESPACE_SCOPE_P (newdecl))
3394 /* The objects have been declared at namespace scope. If either
3395 is a member of an anonymous union, then this is an invalid
3396 redeclaration. For example:
3398 int i;
3399 union { int i; };
3401 is invalid. */
3402 if ((VAR_P (newdecl) && DECL_ANON_UNION_VAR_P (newdecl))
3403 || (VAR_P (olddecl) && DECL_ANON_UNION_VAR_P (olddecl)))
3404 return G_("redeclaration of %q#D");
3405 /* If at least one declaration is a reference, there is no
3406 conflict. For example:
3408 int i = 3;
3409 extern int i;
3411 is valid. */
3412 if (DECL_EXTERNAL (newdecl) || DECL_EXTERNAL (olddecl))
3413 return NULL;
3415 /* Static data member declared outside a class definition
3416 if the variable is defined within the class with constexpr
3417 specifier is declaration rather than definition (and
3418 deprecated). */
3419 if (cxx_dialect >= cxx17
3420 && VAR_P (olddecl)
3421 && DECL_CLASS_SCOPE_P (olddecl)
3422 && DECL_DECLARED_CONSTEXPR_P (olddecl)
3423 && !DECL_INITIAL (newdecl))
3425 DECL_EXTERNAL (newdecl) = 1;
3426 /* For now, only warn with explicit -Wdeprecated. */
3427 if (OPTION_SET_P (warn_deprecated))
3429 auto_diagnostic_group d;
3430 if (warning_at (DECL_SOURCE_LOCATION (newdecl), OPT_Wdeprecated,
3431 "redundant redeclaration of %<constexpr%> "
3432 "static data member %qD", newdecl))
3433 inform (DECL_SOURCE_LOCATION (olddecl),
3434 "previous declaration of %qD", olddecl);
3436 return NULL;
3439 /* Reject two definitions. */
3440 return G_("redefinition of %q#D");
3442 else
3444 /* Objects declared with block scope: */
3445 /* Reject two definitions, and reject a definition
3446 together with an external reference. */
3447 if (!(DECL_EXTERNAL (newdecl) && DECL_EXTERNAL (olddecl)))
3448 return G_("redeclaration of %q#D");
3449 return NULL;
3454 /* Hash and equality functions for the named_label table. */
3456 hashval_t
3457 named_label_hash::hash (const value_type entry)
3459 return IDENTIFIER_HASH_VALUE (entry->name);
3462 bool
3463 named_label_hash::equal (const value_type entry, compare_type name)
3465 return name == entry->name;
3468 /* Look for a label named ID in the current function. If one cannot
3469 be found, create one. Return the named_label_entry, or NULL on
3470 failure. */
3472 static named_label_entry *
3473 lookup_label_1 (tree id, bool making_local_p)
3475 auto_cond_timevar tv (TV_NAME_LOOKUP);
3477 /* You can't use labels at global scope. */
3478 if (current_function_decl == NULL_TREE)
3480 error ("label %qE referenced outside of any function", id);
3481 return NULL;
3484 if (!named_labels)
3485 named_labels = hash_table<named_label_hash>::create_ggc (13);
3487 hashval_t hash = IDENTIFIER_HASH_VALUE (id);
3488 named_label_entry **slot
3489 = named_labels->find_slot_with_hash (id, hash, INSERT);
3490 named_label_entry *old = *slot;
3492 if (old && old->label_decl)
3494 if (!making_local_p)
3495 return old;
3497 if (old->binding_level == current_binding_level)
3499 error ("local label %qE conflicts with existing label", id);
3500 inform (DECL_SOURCE_LOCATION (old->label_decl), "previous label");
3501 return NULL;
3505 /* We are making a new decl, create or reuse the named_label_entry */
3506 named_label_entry *ent = NULL;
3507 if (old && !old->label_decl)
3508 ent = old;
3509 else
3511 ent = ggc_cleared_alloc<named_label_entry> ();
3512 ent->name = id;
3513 ent->outer = old;
3514 *slot = ent;
3517 /* Now create the LABEL_DECL. */
3518 tree decl = build_decl (input_location, LABEL_DECL, id, void_type_node);
3520 DECL_CONTEXT (decl) = current_function_decl;
3521 SET_DECL_MODE (decl, VOIDmode);
3522 if (making_local_p)
3524 C_DECLARED_LABEL_FLAG (decl) = true;
3525 DECL_CHAIN (decl) = current_binding_level->names;
3526 current_binding_level->names = decl;
3529 ent->label_decl = decl;
3531 return ent;
3534 /* Wrapper for lookup_label_1. */
3536 tree
3537 lookup_label (tree id)
3539 named_label_entry *ent = lookup_label_1 (id, false);
3540 return ent ? ent->label_decl : NULL_TREE;
3543 tree
3544 declare_local_label (tree id)
3546 named_label_entry *ent = lookup_label_1 (id, true);
3547 return ent ? ent->label_decl : NULL_TREE;
3550 /* Returns nonzero if it is ill-formed to jump past the declaration of
3551 DECL. Returns 2 if it's also a real problem. */
3553 static int
3554 decl_jump_unsafe (tree decl)
3556 /* [stmt.dcl]/3: A program that jumps from a point where a local variable
3557 with automatic storage duration is not in scope to a point where it is
3558 in scope is ill-formed unless the variable has scalar type, class type
3559 with a trivial default constructor and a trivial destructor, a
3560 cv-qualified version of one of these types, or an array of one of the
3561 preceding types and is declared without an initializer (8.5). */
3562 tree type = TREE_TYPE (decl);
3564 if (!VAR_P (decl) || TREE_STATIC (decl)
3565 || type == error_mark_node)
3566 return 0;
3568 if (DECL_NONTRIVIALLY_INITIALIZED_P (decl)
3569 || variably_modified_type_p (type, NULL_TREE))
3570 return 2;
3572 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
3573 return 1;
3575 return 0;
3578 /* A subroutine of check_previous_goto_1 and check_goto to identify a branch
3579 to the user. */
3581 static bool
3582 identify_goto (tree decl, location_t loc, const location_t *locus,
3583 diagnostic_t diag_kind)
3585 bool complained
3586 = emit_diagnostic (diag_kind, loc, 0,
3587 decl ? N_("jump to label %qD")
3588 : N_("jump to case label"), decl);
3589 if (complained && locus)
3590 inform (*locus, " from here");
3591 return complained;
3594 /* Check that a single previously seen jump to a newly defined label
3595 is OK. DECL is the LABEL_DECL or 0; LEVEL is the binding_level for
3596 the jump context; NAMES are the names in scope in LEVEL at the jump
3597 context; LOCUS is the source position of the jump or 0. Returns
3598 true if all is well. */
3600 static bool
3601 check_previous_goto_1 (tree decl, cp_binding_level* level, tree names,
3602 bool exited_omp, const location_t *locus)
3604 cp_binding_level *b;
3605 bool complained = false;
3606 int identified = 0;
3607 bool saw_eh = false, saw_omp = false, saw_tm = false, saw_cxif = false;
3608 bool saw_ceif = false, saw_se = false;
3610 if (exited_omp)
3612 complained = identify_goto (decl, input_location, locus, DK_ERROR);
3613 if (complained)
3614 inform (input_location, " exits OpenMP structured block");
3615 saw_omp = true;
3616 identified = 2;
3619 for (b = current_binding_level; b ; b = b->level_chain)
3621 tree new_decls, old_decls = (b == level ? names : NULL_TREE);
3623 for (new_decls = b->names; new_decls != old_decls;
3624 new_decls = (DECL_P (new_decls) ? DECL_CHAIN (new_decls)
3625 : TREE_CHAIN (new_decls)))
3627 int problem = decl_jump_unsafe (new_decls);
3628 if (! problem)
3629 continue;
3631 if (!identified)
3633 complained = identify_goto (decl, input_location, locus,
3634 problem > 1
3635 ? DK_ERROR : DK_PERMERROR);
3636 identified = 1;
3638 if (complained)
3640 if (problem > 1)
3641 inform (DECL_SOURCE_LOCATION (new_decls),
3642 " crosses initialization of %q#D", new_decls);
3643 else
3644 inform (DECL_SOURCE_LOCATION (new_decls),
3645 " enters scope of %q#D, which has "
3646 "non-trivial destructor", new_decls);
3650 if (b == level)
3651 break;
3653 const char *inf = NULL;
3654 location_t loc = input_location;
3655 switch (b->kind)
3657 case sk_try:
3658 if (!saw_eh)
3659 inf = G_(" enters %<try%> block");
3660 saw_eh = true;
3661 break;
3663 case sk_catch:
3664 if (!saw_eh)
3665 inf = G_(" enters %<catch%> block");
3666 saw_eh = true;
3667 break;
3669 case sk_omp:
3670 if (!saw_omp)
3671 inf = G_(" enters OpenMP structured block");
3672 saw_omp = true;
3673 break;
3675 case sk_transaction:
3676 if (!saw_tm)
3677 inf = G_(" enters synchronized or atomic statement");
3678 saw_tm = true;
3679 break;
3681 case sk_stmt_expr:
3682 if (!saw_se)
3683 inf = G_(" enters statement expression");
3684 saw_se = true;
3685 break;
3687 case sk_block:
3688 if (!saw_cxif && level_for_constexpr_if (b->level_chain))
3690 inf = G_(" enters %<constexpr if%> statement");
3691 loc = EXPR_LOCATION (b->level_chain->this_entity);
3692 saw_cxif = true;
3694 else if (!saw_ceif && level_for_consteval_if (b->level_chain))
3696 inf = G_(" enters %<consteval if%> statement");
3697 loc = EXPR_LOCATION (b->level_chain->this_entity);
3698 saw_ceif = true;
3700 break;
3702 default:
3703 break;
3706 if (inf)
3708 if (identified < 2)
3709 complained = identify_goto (decl, input_location, locus, DK_ERROR);
3710 identified = 2;
3711 if (complained)
3712 inform (loc, inf);
3716 return !identified;
3719 static void
3720 check_previous_goto (tree decl, struct named_label_use_entry *use)
3722 check_previous_goto_1 (decl, use->binding_level,
3723 use->names_in_scope, use->in_omp_scope,
3724 &use->o_goto_locus);
3727 static bool
3728 check_switch_goto (cp_binding_level* level)
3730 return check_previous_goto_1 (NULL_TREE, level, level->names, false, NULL);
3733 /* Check that a new jump to a label DECL is OK. Called by
3734 finish_goto_stmt. */
3736 void
3737 check_goto (tree decl)
3739 /* We can't know where a computed goto is jumping.
3740 So we assume that it's OK. */
3741 if (TREE_CODE (decl) != LABEL_DECL)
3742 return;
3744 hashval_t hash = IDENTIFIER_HASH_VALUE (DECL_NAME (decl));
3745 named_label_entry **slot
3746 = named_labels->find_slot_with_hash (DECL_NAME (decl), hash, NO_INSERT);
3747 named_label_entry *ent = *slot;
3749 /* If the label hasn't been defined yet, defer checking. */
3750 if (! DECL_INITIAL (decl))
3752 /* Don't bother creating another use if the last goto had the
3753 same data, and will therefore create the same set of errors. */
3754 if (ent->uses
3755 && ent->uses->names_in_scope == current_binding_level->names)
3756 return;
3758 named_label_use_entry *new_use
3759 = ggc_alloc<named_label_use_entry> ();
3760 new_use->binding_level = current_binding_level;
3761 new_use->names_in_scope = current_binding_level->names;
3762 new_use->o_goto_locus = input_location;
3763 new_use->in_omp_scope = false;
3765 new_use->next = ent->uses;
3766 ent->uses = new_use;
3767 return;
3770 bool saw_catch = false, complained = false;
3771 int identified = 0;
3772 tree bad;
3773 unsigned ix;
3775 if (ent->in_try_scope || ent->in_catch_scope || ent->in_transaction_scope
3776 || ent->in_constexpr_if || ent->in_consteval_if
3777 || ent->in_omp_scope || ent->in_stmt_expr
3778 || !vec_safe_is_empty (ent->bad_decls))
3780 diagnostic_t diag_kind = DK_PERMERROR;
3781 if (ent->in_try_scope || ent->in_catch_scope || ent->in_constexpr_if
3782 || ent->in_consteval_if || ent->in_transaction_scope
3783 || ent->in_omp_scope || ent->in_stmt_expr)
3784 diag_kind = DK_ERROR;
3785 complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3786 &input_location, diag_kind);
3787 identified = 1 + (diag_kind == DK_ERROR);
3790 FOR_EACH_VEC_SAFE_ELT (ent->bad_decls, ix, bad)
3792 int u = decl_jump_unsafe (bad);
3794 if (u > 1 && DECL_ARTIFICIAL (bad))
3796 /* Can't skip init of __exception_info. */
3797 if (identified == 1)
3799 complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3800 &input_location, DK_ERROR);
3801 identified = 2;
3803 if (complained)
3804 inform (DECL_SOURCE_LOCATION (bad), " enters %<catch%> block");
3805 saw_catch = true;
3807 else if (complained)
3809 if (u > 1)
3810 inform (DECL_SOURCE_LOCATION (bad),
3811 " skips initialization of %q#D", bad);
3812 else
3813 inform (DECL_SOURCE_LOCATION (bad),
3814 " enters scope of %q#D which has "
3815 "non-trivial destructor", bad);
3819 if (complained)
3821 if (ent->in_try_scope)
3822 inform (input_location, " enters %<try%> block");
3823 else if (ent->in_catch_scope && !saw_catch)
3824 inform (input_location, " enters %<catch%> block");
3825 else if (ent->in_transaction_scope)
3826 inform (input_location, " enters synchronized or atomic statement");
3827 else if (ent->in_constexpr_if)
3828 inform (input_location, " enters %<constexpr if%> statement");
3829 else if (ent->in_consteval_if)
3830 inform (input_location, " enters %<consteval if%> statement");
3831 else if (ent->in_stmt_expr)
3832 inform (input_location, " enters statement expression");
3835 if (ent->in_omp_scope)
3837 if (complained)
3838 inform (input_location, " enters OpenMP structured block");
3840 else if (flag_openmp)
3841 for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3843 if (b == ent->binding_level)
3844 break;
3845 if (b->kind == sk_omp)
3847 if (identified < 2)
3849 complained = identify_goto (decl,
3850 DECL_SOURCE_LOCATION (decl),
3851 &input_location, DK_ERROR);
3852 identified = 2;
3854 if (complained)
3855 inform (input_location, " exits OpenMP structured block");
3856 break;
3861 /* Check that a return is ok wrt OpenMP structured blocks.
3862 Called by finish_return_stmt. Returns true if all is well. */
3864 bool
3865 check_omp_return (void)
3867 for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3868 if (b->kind == sk_omp)
3870 error ("invalid exit from OpenMP structured block");
3871 return false;
3873 else if (b->kind == sk_function_parms)
3874 break;
3875 return true;
3878 /* Define a label, specifying the location in the source file.
3879 Return the LABEL_DECL node for the label. */
3881 tree
3882 define_label (location_t location, tree name)
3884 auto_cond_timevar tv (TV_NAME_LOOKUP);
3886 /* After labels, make any new cleanups in the function go into their
3887 own new (temporary) binding contour. */
3888 for (cp_binding_level *p = current_binding_level;
3889 p->kind != sk_function_parms;
3890 p = p->level_chain)
3891 p->more_cleanups_ok = 0;
3893 named_label_entry *ent = lookup_label_1 (name, false);
3894 tree decl = ent->label_decl;
3896 if (DECL_INITIAL (decl) != NULL_TREE)
3898 error ("duplicate label %qD", decl);
3899 return error_mark_node;
3901 else
3903 /* Mark label as having been defined. */
3904 DECL_INITIAL (decl) = error_mark_node;
3905 /* Say where in the source. */
3906 DECL_SOURCE_LOCATION (decl) = location;
3908 ent->binding_level = current_binding_level;
3909 ent->names_in_scope = current_binding_level->names;
3911 for (named_label_use_entry *use = ent->uses; use; use = use->next)
3912 check_previous_goto (decl, use);
3913 ent->uses = NULL;
3916 return decl;
3919 struct cp_switch
3921 cp_binding_level *level;
3922 struct cp_switch *next;
3923 /* The SWITCH_STMT being built. */
3924 tree switch_stmt;
3925 /* A splay-tree mapping the low element of a case range to the high
3926 element, or NULL_TREE if there is no high element. Used to
3927 determine whether or not a new case label duplicates an old case
3928 label. We need a tree, rather than simply a hash table, because
3929 of the GNU case range extension. */
3930 splay_tree cases;
3931 /* Remember whether a default: case label has been seen. */
3932 bool has_default_p;
3933 /* Remember whether a BREAK_STMT has been seen in this SWITCH_STMT. */
3934 bool break_stmt_seen_p;
3935 /* Set if inside of {FOR,DO,WHILE}_BODY nested inside of a switch,
3936 where BREAK_STMT doesn't belong to the SWITCH_STMT. */
3937 bool in_loop_body_p;
3940 /* A stack of the currently active switch statements. The innermost
3941 switch statement is on the top of the stack. There is no need to
3942 mark the stack for garbage collection because it is only active
3943 during the processing of the body of a function, and we never
3944 collect at that point. */
3946 static struct cp_switch *switch_stack;
3948 /* Called right after a switch-statement condition is parsed.
3949 SWITCH_STMT is the switch statement being parsed. */
3951 void
3952 push_switch (tree switch_stmt)
3954 struct cp_switch *p = XNEW (struct cp_switch);
3955 p->level = current_binding_level;
3956 p->next = switch_stack;
3957 p->switch_stmt = switch_stmt;
3958 p->cases = splay_tree_new (case_compare, NULL, NULL);
3959 p->has_default_p = false;
3960 p->break_stmt_seen_p = false;
3961 p->in_loop_body_p = false;
3962 switch_stack = p;
3965 void
3966 pop_switch (void)
3968 struct cp_switch *cs = switch_stack;
3970 /* Emit warnings as needed. */
3971 location_t switch_location = cp_expr_loc_or_input_loc (cs->switch_stmt);
3972 tree cond = SWITCH_STMT_COND (cs->switch_stmt);
3973 const bool bool_cond_p
3974 = (SWITCH_STMT_TYPE (cs->switch_stmt)
3975 && TREE_CODE (SWITCH_STMT_TYPE (cs->switch_stmt)) == BOOLEAN_TYPE);
3976 if (!processing_template_decl)
3977 c_do_switch_warnings (cs->cases, switch_location,
3978 SWITCH_STMT_TYPE (cs->switch_stmt), cond,
3979 bool_cond_p);
3981 /* For the benefit of block_may_fallthru remember if the switch body
3982 case labels cover all possible values and if there are break; stmts. */
3983 if (cs->has_default_p
3984 || (!processing_template_decl
3985 && c_switch_covers_all_cases_p (cs->cases,
3986 SWITCH_STMT_TYPE (cs->switch_stmt))))
3987 SWITCH_STMT_ALL_CASES_P (cs->switch_stmt) = 1;
3988 if (!cs->break_stmt_seen_p)
3989 SWITCH_STMT_NO_BREAK_P (cs->switch_stmt) = 1;
3990 /* Now that we're done with the switch warnings, set the switch type
3991 to the type of the condition if the index type was of scoped enum type.
3992 (Such types don't participate in the integer promotions.) We do this
3993 because of bit-fields whose declared type is a scoped enum type:
3994 gimplification will use the lowered index type, but convert the
3995 case values to SWITCH_STMT_TYPE, which would have been the declared type
3996 and verify_gimple_switch doesn't accept that. */
3997 if (is_bitfield_expr_with_lowered_type (cond))
3998 SWITCH_STMT_TYPE (cs->switch_stmt) = TREE_TYPE (cond);
3999 gcc_assert (!cs->in_loop_body_p);
4000 splay_tree_delete (cs->cases);
4001 switch_stack = switch_stack->next;
4002 free (cs);
4005 /* Note that a BREAK_STMT is about to be added. If it is inside of
4006 a SWITCH_STMT and not inside of a loop body inside of it, note
4007 in switch_stack we've seen a BREAK_STMT. */
4009 void
4010 note_break_stmt (void)
4012 if (switch_stack && !switch_stack->in_loop_body_p)
4013 switch_stack->break_stmt_seen_p = true;
4016 /* Note the start of processing of an iteration statement's body.
4017 The note_break_stmt function will do nothing while processing it.
4018 Return a flag that should be passed to note_iteration_stmt_body_end. */
4020 bool
4021 note_iteration_stmt_body_start (void)
4023 if (!switch_stack)
4024 return false;
4025 bool ret = switch_stack->in_loop_body_p;
4026 switch_stack->in_loop_body_p = true;
4027 return ret;
4030 /* Note the end of processing of an iteration statement's body. */
4032 void
4033 note_iteration_stmt_body_end (bool prev)
4035 if (switch_stack)
4036 switch_stack->in_loop_body_p = prev;
4039 /* Convert a case constant VALUE in a switch to the type TYPE of the switch
4040 condition. Note that if TYPE and VALUE are already integral we don't
4041 really do the conversion because the language-independent
4042 warning/optimization code will work better that way. */
4044 static tree
4045 case_conversion (tree type, tree value)
4047 if (value == NULL_TREE)
4048 return value;
4050 value = mark_rvalue_use (value);
4052 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
4053 type = type_promotes_to (type);
4055 tree ovalue = value;
4056 /* The constant-expression VALUE shall be a converted constant expression
4057 of the adjusted type of the switch condition, which doesn't allow
4058 narrowing conversions. */
4059 value = build_converted_constant_expr (type, value, tf_warning_or_error);
4061 if (cxx_dialect >= cxx11
4062 && (SCOPED_ENUM_P (type)
4063 || !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ovalue))))
4064 /* Use the converted value. */;
4065 else
4066 /* The already integral case. */
4067 value = ovalue;
4069 return cxx_constant_value (value);
4072 /* Note that we've seen a definition of a case label, and complain if this
4073 is a bad place for one. */
4075 tree
4076 finish_case_label (location_t loc, tree low_value, tree high_value)
4078 tree cond, r;
4079 cp_binding_level *p;
4080 tree type;
4082 if (low_value == NULL_TREE && high_value == NULL_TREE)
4083 switch_stack->has_default_p = true;
4085 if (processing_template_decl)
4087 tree label;
4089 /* For templates, just add the case label; we'll do semantic
4090 analysis at instantiation-time. */
4091 label = build_decl (loc, LABEL_DECL, NULL_TREE, void_type_node);
4092 return add_stmt (build_case_label (low_value, high_value, label));
4095 /* Find the condition on which this switch statement depends. */
4096 cond = SWITCH_STMT_COND (switch_stack->switch_stmt);
4097 if (cond && TREE_CODE (cond) == TREE_LIST)
4098 cond = TREE_VALUE (cond);
4100 if (!check_switch_goto (switch_stack->level))
4101 return error_mark_node;
4103 type = SWITCH_STMT_TYPE (switch_stack->switch_stmt);
4104 if (type == error_mark_node)
4105 return error_mark_node;
4107 low_value = case_conversion (type, low_value);
4108 high_value = case_conversion (type, high_value);
4110 r = c_add_case_label (loc, switch_stack->cases, cond, low_value, high_value);
4112 /* After labels, make any new cleanups in the function go into their
4113 own new (temporary) binding contour. */
4114 for (p = current_binding_level;
4115 p->kind != sk_function_parms;
4116 p = p->level_chain)
4117 p->more_cleanups_ok = 0;
4119 return r;
4122 struct typename_info {
4123 tree scope;
4124 tree name;
4125 tree template_id;
4126 bool enum_p;
4127 bool class_p;
4130 struct typename_hasher : ggc_ptr_hash<tree_node>
4132 typedef typename_info *compare_type;
4134 /* Hash a TYPENAME_TYPE. */
4136 static hashval_t
4137 hash (tree context, tree fullname)
4139 hashval_t hash = 0;
4140 hash = iterative_hash_object (context, hash);
4141 hash = iterative_hash_object (fullname, hash);
4142 return hash;
4145 static hashval_t
4146 hash (const typename_info *ti)
4148 return typename_hasher::hash (ti->scope, ti->template_id);
4151 static hashval_t
4152 hash (tree t)
4154 return typename_hasher::hash (TYPE_CONTEXT (t), TYPENAME_TYPE_FULLNAME (t));
4157 /* Compare two TYPENAME_TYPEs. */
4159 static bool
4160 equal (tree t1, const typename_info *t2)
4162 return (TYPE_IDENTIFIER (t1) == t2->name
4163 && TYPE_CONTEXT (t1) == t2->scope
4164 && TYPENAME_TYPE_FULLNAME (t1) == t2->template_id
4165 && TYPENAME_IS_ENUM_P (t1) == t2->enum_p
4166 && TYPENAME_IS_CLASS_P (t1) == t2->class_p);
4170 /* Build a TYPENAME_TYPE. If the type is `typename T::t', CONTEXT is
4171 the type of `T', NAME is the IDENTIFIER_NODE for `t'.
4173 Returns the new TYPENAME_TYPE. */
4175 static GTY (()) hash_table<typename_hasher> *typename_htab;
4177 tree
4178 build_typename_type (tree context, tree name, tree fullname,
4179 enum tag_types tag_type)
4181 typename_info ti;
4183 if (typename_htab == NULL)
4184 typename_htab = hash_table<typename_hasher>::create_ggc (61);
4186 ti.scope = FROB_CONTEXT (context);
4187 ti.name = name;
4188 ti.template_id = fullname;
4189 ti.enum_p = tag_type == enum_type;
4190 ti.class_p = (tag_type == class_type
4191 || tag_type == record_type
4192 || tag_type == union_type);
4193 hashval_t hash = typename_hasher::hash (&ti);
4195 /* See if we already have this type. */
4196 tree *e = typename_htab->find_slot_with_hash (&ti, hash, INSERT);
4197 tree t = *e;
4198 if (*e)
4199 t = *e;
4200 else
4202 /* Build the TYPENAME_TYPE. */
4203 t = cxx_make_type (TYPENAME_TYPE);
4204 TYPE_CONTEXT (t) = ti.scope;
4205 TYPENAME_TYPE_FULLNAME (t) = ti.template_id;
4206 TYPENAME_IS_ENUM_P (t) = ti.enum_p;
4207 TYPENAME_IS_CLASS_P (t) = ti.class_p;
4209 /* Build the corresponding TYPE_DECL. */
4210 tree d = build_decl (input_location, TYPE_DECL, name, t);
4211 TYPE_NAME (t) = d;
4212 TYPE_STUB_DECL (t) = d;
4213 DECL_CONTEXT (d) = ti.scope;
4214 DECL_ARTIFICIAL (d) = 1;
4216 /* Store it in the hash table. */
4217 *e = t;
4219 /* TYPENAME_TYPEs must always be compared structurally, because
4220 they may or may not resolve down to another type depending on
4221 the currently open classes. */
4222 SET_TYPE_STRUCTURAL_EQUALITY (t);
4225 return t;
4228 /* Resolve `typename CONTEXT::NAME'. TAG_TYPE indicates the tag
4229 provided to name the type. Returns an appropriate type, unless an
4230 error occurs, in which case error_mark_node is returned. If we
4231 locate a non-artificial TYPE_DECL and TF_KEEP_TYPE_DECL is set, we
4232 return that, rather than the _TYPE it corresponds to, in other
4233 cases we look through the type decl. If TF_ERROR is set, complain
4234 about errors, otherwise be quiet. */
4236 tree
4237 make_typename_type (tree context, tree name, enum tag_types tag_type,
4238 tsubst_flags_t complain)
4240 tree fullname;
4241 tree t;
4242 bool want_template;
4244 if (name == error_mark_node
4245 || context == NULL_TREE
4246 || context == error_mark_node)
4247 return error_mark_node;
4249 if (TYPE_P (name))
4251 if (!(TYPE_LANG_SPECIFIC (name)
4252 && (CLASSTYPE_IS_TEMPLATE (name)
4253 || CLASSTYPE_USE_TEMPLATE (name))))
4254 name = TYPE_IDENTIFIER (name);
4255 else
4256 /* Create a TEMPLATE_ID_EXPR for the type. */
4257 name = build_nt (TEMPLATE_ID_EXPR,
4258 CLASSTYPE_TI_TEMPLATE (name),
4259 CLASSTYPE_TI_ARGS (name));
4261 else if (TREE_CODE (name) == TYPE_DECL)
4262 name = DECL_NAME (name);
4264 fullname = name;
4266 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
4268 name = TREE_OPERAND (name, 0);
4269 if (DECL_TYPE_TEMPLATE_P (name))
4270 name = TREE_OPERAND (fullname, 0) = DECL_NAME (name);
4271 if (TREE_CODE (name) != IDENTIFIER_NODE)
4273 if (complain & tf_error)
4274 error ("%qD is not a type", name);
4275 return error_mark_node;
4278 if (TREE_CODE (name) == TEMPLATE_DECL)
4280 if (complain & tf_error)
4281 error ("%qD used without template arguments", name);
4282 return error_mark_node;
4284 else if (is_overloaded_fn (name))
4286 if (complain & tf_error)
4287 error ("%qD is a function, not a type", name);
4288 return error_mark_node;
4290 gcc_assert (identifier_p (name));
4291 gcc_assert (TYPE_P (context));
4293 if (TREE_CODE (context) == TYPE_PACK_EXPANSION)
4294 /* This can happen for C++17 variadic using (c++/88986). */;
4295 else if (!MAYBE_CLASS_TYPE_P (context))
4297 if (complain & tf_error)
4298 error ("%q#T is not a class", context);
4299 return error_mark_node;
4302 /* When the CONTEXT is a dependent type, NAME could refer to a
4303 dependent base class of CONTEXT. But look inside it anyway
4304 if CONTEXT is a currently open scope, in case it refers to a
4305 member of the current instantiation or a non-dependent base;
4306 lookup will stop when we hit a dependent base. */
4307 if (!dependent_scope_p (context))
4308 /* We should only set WANT_TYPE when we're a nested typename type.
4309 Then we can give better diagnostics if we find a non-type. */
4310 t = lookup_field (context, name, 2, /*want_type=*/true);
4311 else
4312 t = NULL_TREE;
4314 if ((!t || TREE_CODE (t) == TREE_LIST) && dependent_type_p (context))
4315 return build_typename_type (context, name, fullname, tag_type);
4317 want_template = TREE_CODE (fullname) == TEMPLATE_ID_EXPR;
4319 if (!t)
4321 if (complain & tf_error)
4323 if (!COMPLETE_TYPE_P (context))
4324 cxx_incomplete_type_error (NULL_TREE, context);
4325 else
4326 error (want_template ? G_("no class template named %q#T in %q#T")
4327 : G_("no type named %q#T in %q#T"), name, context);
4329 return error_mark_node;
4332 /* Pull out the template from an injected-class-name (or multiple). */
4333 if (want_template)
4334 t = maybe_get_template_decl_from_type_decl (t);
4336 if (TREE_CODE (t) == TREE_LIST)
4338 if (complain & tf_error)
4340 error ("lookup of %qT in %qT is ambiguous", name, context);
4341 print_candidates (t);
4343 return error_mark_node;
4346 if (want_template && !DECL_TYPE_TEMPLATE_P (t))
4348 if (complain & tf_error)
4349 error ("%<typename %T::%D%> names %q#T, which is not a class template",
4350 context, name, t);
4351 return error_mark_node;
4353 if (!want_template && TREE_CODE (t) != TYPE_DECL)
4355 if ((complain & tf_tst_ok) && cxx_dialect >= cxx17
4356 && DECL_TYPE_TEMPLATE_P (t))
4357 /* The caller permits this typename-specifier to name a template
4358 (because it appears in a CTAD-enabled context). */;
4359 else
4361 if (complain & tf_error)
4362 error ("%<typename %T::%D%> names %q#T, which is not a type",
4363 context, name, t);
4364 return error_mark_node;
4368 if (!check_accessibility_of_qualified_id (t, /*object_type=*/NULL_TREE,
4369 context, complain))
4370 return error_mark_node;
4372 if (!want_template && DECL_TYPE_TEMPLATE_P (t))
4373 return make_template_placeholder (t);
4375 if (want_template)
4377 t = lookup_template_class (t, TREE_OPERAND (fullname, 1),
4378 NULL_TREE, context,
4379 /*entering_scope=*/0,
4380 complain | tf_user);
4381 if (t == error_mark_node)
4382 return error_mark_node;
4383 t = TYPE_NAME (t);
4386 if (DECL_ARTIFICIAL (t) || !(complain & tf_keep_type_decl))
4387 t = TREE_TYPE (t);
4389 maybe_record_typedef_use (t);
4391 return t;
4394 /* Resolve `CONTEXT::template NAME'. Returns a TEMPLATE_DECL if the name
4395 can be resolved or an UNBOUND_CLASS_TEMPLATE, unless an error occurs,
4396 in which case error_mark_node is returned.
4398 If PARM_LIST is non-NULL, also make sure that the template parameter
4399 list of TEMPLATE_DECL matches.
4401 If COMPLAIN zero, don't complain about any errors that occur. */
4403 tree
4404 make_unbound_class_template (tree context, tree name, tree parm_list,
4405 tsubst_flags_t complain)
4407 if (TYPE_P (name))
4408 name = TYPE_IDENTIFIER (name);
4409 else if (DECL_P (name))
4410 name = DECL_NAME (name);
4411 gcc_assert (identifier_p (name));
4413 if (!dependent_type_p (context)
4414 || currently_open_class (context))
4416 tree tmpl = NULL_TREE;
4418 if (MAYBE_CLASS_TYPE_P (context))
4419 tmpl = lookup_field (context, name, 0, false);
4421 if (tmpl && TREE_CODE (tmpl) == TYPE_DECL)
4422 tmpl = maybe_get_template_decl_from_type_decl (tmpl);
4424 if (!tmpl || !DECL_TYPE_TEMPLATE_P (tmpl))
4426 if (complain & tf_error)
4427 error ("no class template named %q#T in %q#T", name, context);
4428 return error_mark_node;
4431 if (parm_list
4432 && !comp_template_parms (DECL_TEMPLATE_PARMS (tmpl), parm_list))
4434 if (complain & tf_error)
4436 error ("template parameters do not match template %qD", tmpl);
4437 inform (DECL_SOURCE_LOCATION (tmpl),
4438 "%qD declared here", tmpl);
4440 return error_mark_node;
4443 if (!perform_or_defer_access_check (TYPE_BINFO (context), tmpl, tmpl,
4444 complain))
4445 return error_mark_node;
4447 return tmpl;
4450 return make_unbound_class_template_raw (context, name, parm_list);
4453 /* Build an UNBOUND_CLASS_TEMPLATE. */
4455 tree
4456 make_unbound_class_template_raw (tree context, tree name, tree parm_list)
4458 /* Build the UNBOUND_CLASS_TEMPLATE. */
4459 tree t = cxx_make_type (UNBOUND_CLASS_TEMPLATE);
4460 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
4461 TREE_TYPE (t) = NULL_TREE;
4462 SET_TYPE_STRUCTURAL_EQUALITY (t);
4464 /* Build the corresponding TEMPLATE_DECL. */
4465 tree d = build_decl (input_location, TEMPLATE_DECL, name, t);
4466 TYPE_NAME (t) = d;
4467 TYPE_STUB_DECL (t) = d;
4468 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
4469 DECL_ARTIFICIAL (d) = 1;
4470 DECL_TEMPLATE_PARMS (d) = parm_list;
4472 return t;
4477 /* Push the declarations of builtin types into the global namespace.
4478 RID_INDEX is the index of the builtin type in the array
4479 RID_POINTERS. NAME is the name used when looking up the builtin
4480 type. TYPE is the _TYPE node for the builtin type.
4482 The calls to set_global_binding below should be
4483 eliminated. Built-in types should not be looked up name; their
4484 names are keywords that the parser can recognize. However, there
4485 is code in c-common.cc that uses identifier_global_value to look up
4486 built-in types by name. */
4488 void
4489 record_builtin_type (enum rid rid_index,
4490 const char* name,
4491 tree type)
4493 tree decl = NULL_TREE;
4495 if (name)
4497 tree tname = get_identifier (name);
4498 tree tdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, tname, type);
4499 DECL_ARTIFICIAL (tdecl) = 1;
4500 set_global_binding (tdecl);
4501 decl = tdecl;
4504 if ((int) rid_index < (int) RID_MAX)
4505 if (tree rname = ridpointers[(int) rid_index])
4506 if (!decl || DECL_NAME (decl) != rname)
4508 tree rdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, rname, type);
4509 DECL_ARTIFICIAL (rdecl) = 1;
4510 set_global_binding (rdecl);
4511 if (!decl)
4512 decl = rdecl;
4515 if (decl)
4517 if (!TYPE_NAME (type))
4518 TYPE_NAME (type) = decl;
4519 debug_hooks->type_decl (decl, 0);
4523 /* Push a type into the namespace so that the back ends ignore it. */
4525 static void
4526 record_unknown_type (tree type, const char* name)
4528 tree decl = pushdecl (build_decl (UNKNOWN_LOCATION,
4529 TYPE_DECL, get_identifier (name), type));
4530 /* Make sure the "unknown type" typedecl gets ignored for debug info. */
4531 DECL_IGNORED_P (decl) = 1;
4532 TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
4533 TYPE_SIZE (type) = TYPE_SIZE (void_type_node);
4534 SET_TYPE_ALIGN (type, 1);
4535 TYPE_USER_ALIGN (type) = 0;
4536 SET_TYPE_MODE (type, TYPE_MODE (void_type_node));
4539 /* Create all the predefined identifiers. */
4541 static void
4542 initialize_predefined_identifiers (void)
4544 struct predefined_identifier
4546 const char *name; /* Name. */
4547 tree *node; /* Node to store it in. */
4548 cp_identifier_kind kind; /* Kind of identifier. */
4551 /* A table of identifiers to create at startup. */
4552 static const predefined_identifier predefined_identifiers[] = {
4553 {"C++", &lang_name_cplusplus, cik_normal},
4554 {"C", &lang_name_c, cik_normal},
4555 /* Some of these names have a trailing space so that it is
4556 impossible for them to conflict with names written by users. */
4557 {"__ct ", &ctor_identifier, cik_ctor},
4558 {"__ct_base ", &base_ctor_identifier, cik_ctor},
4559 {"__ct_comp ", &complete_ctor_identifier, cik_ctor},
4560 {"__dt ", &dtor_identifier, cik_dtor},
4561 {"__dt_base ", &base_dtor_identifier, cik_dtor},
4562 {"__dt_comp ", &complete_dtor_identifier, cik_dtor},
4563 {"__dt_del ", &deleting_dtor_identifier, cik_dtor},
4564 {"__conv_op ", &conv_op_identifier, cik_conv_op},
4565 {"__in_chrg", &in_charge_identifier, cik_normal},
4566 {"__as_base ", &as_base_identifier, cik_normal},
4567 {"this", &this_identifier, cik_normal},
4568 {"__delta", &delta_identifier, cik_normal},
4569 {"__pfn", &pfn_identifier, cik_normal},
4570 {"_vptr", &vptr_identifier, cik_normal},
4571 {"__vtt_parm", &vtt_parm_identifier, cik_normal},
4572 {"::", &global_identifier, cik_normal},
4573 /* The demangler expects anonymous namespaces to be called
4574 something starting with '_GLOBAL__N_'. It no longer needs
4575 to be unique to the TU. */
4576 {"_GLOBAL__N_1", &anon_identifier, cik_normal},
4577 {"auto", &auto_identifier, cik_normal},
4578 {"decltype(auto)", &decltype_auto_identifier, cik_normal},
4579 {"initializer_list", &init_list_identifier, cik_normal},
4580 {"__for_range ", &for_range__identifier, cik_normal},
4581 {"__for_begin ", &for_begin__identifier, cik_normal},
4582 {"__for_end ", &for_end__identifier, cik_normal},
4583 {"__for_range", &for_range_identifier, cik_normal},
4584 {"__for_begin", &for_begin_identifier, cik_normal},
4585 {"__for_end", &for_end_identifier, cik_normal},
4586 {"abi_tag", &abi_tag_identifier, cik_normal},
4587 {"aligned", &aligned_identifier, cik_normal},
4588 {"begin", &begin_identifier, cik_normal},
4589 {"end", &end_identifier, cik_normal},
4590 {"get", &get__identifier, cik_normal},
4591 {"gnu", &gnu_identifier, cik_normal},
4592 {"tuple_element", &tuple_element_identifier, cik_normal},
4593 {"tuple_size", &tuple_size_identifier, cik_normal},
4594 {"type", &type_identifier, cik_normal},
4595 {"value", &value_identifier, cik_normal},
4596 {"_FUN", &fun_identifier, cik_normal},
4597 {"__closure", &closure_identifier, cik_normal},
4598 {"heap uninit", &heap_uninit_identifier, cik_normal},
4599 {"heap ", &heap_identifier, cik_normal},
4600 {"heap deleted", &heap_deleted_identifier, cik_normal},
4601 {"heap [] uninit", &heap_vec_uninit_identifier, cik_normal},
4602 {"heap []", &heap_vec_identifier, cik_normal},
4603 {"omp", &omp_identifier, cik_normal},
4604 {NULL, NULL, cik_normal}
4607 for (const predefined_identifier *pid = predefined_identifiers;
4608 pid->name; ++pid)
4610 *pid->node = get_identifier (pid->name);
4611 /* Some of these identifiers already have a special kind. */
4612 if (pid->kind != cik_normal)
4613 set_identifier_kind (*pid->node, pid->kind);
4617 /* Create the predefined scalar types of C,
4618 and some nodes representing standard constants (0, 1, (void *)0).
4619 Initialize the global binding level.
4620 Make definitions for built-in primitive functions. */
4622 void
4623 cxx_init_decl_processing (void)
4625 tree void_ftype;
4626 tree void_ftype_ptr;
4628 /* Create all the identifiers we need. */
4629 initialize_predefined_identifiers ();
4631 /* Create the global variables. */
4632 push_to_top_level ();
4634 current_function_decl = NULL_TREE;
4635 current_binding_level = NULL;
4636 /* Enter the global namespace. */
4637 gcc_assert (global_namespace == NULL_TREE);
4638 global_namespace = build_lang_decl (NAMESPACE_DECL, global_identifier,
4639 void_type_node);
4640 TREE_PUBLIC (global_namespace) = true;
4641 DECL_MODULE_EXPORT_P (global_namespace) = true;
4642 DECL_CONTEXT (global_namespace)
4643 = build_translation_unit_decl (get_identifier (main_input_filename));
4644 /* Remember whether we want the empty class passing ABI change warning
4645 in this TU. */
4646 TRANSLATION_UNIT_WARN_EMPTY_P (DECL_CONTEXT (global_namespace))
4647 = warn_abi && abi_version_crosses (12);
4648 debug_hooks->register_main_translation_unit
4649 (DECL_CONTEXT (global_namespace));
4650 begin_scope (sk_namespace, global_namespace);
4651 current_namespace = global_namespace;
4653 if (flag_visibility_ms_compat)
4654 default_visibility = VISIBILITY_HIDDEN;
4656 /* Initially, C. */
4657 current_lang_name = lang_name_c;
4659 /* Create the `std' namespace. */
4660 push_namespace (get_identifier ("std"));
4661 std_node = current_namespace;
4662 pop_namespace ();
4664 flag_noexcept_type = (cxx_dialect >= cxx17);
4666 c_common_nodes_and_builtins ();
4668 tree bool_ftype = build_function_type_list (boolean_type_node, NULL_TREE);
4669 tree decl
4670 = add_builtin_function ("__builtin_is_constant_evaluated",
4671 bool_ftype, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
4672 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4673 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4675 /* The concrete return type of __builtin_source_location is
4676 const std::source_location::__impl*, but we can't form the type
4677 at this point. So we initially declare it with an auto return
4678 type which we then "deduce" from require_deduced_type upon first use. */
4679 tree auto_ftype = build_function_type_list (make_auto (), NULL_TREE);
4680 decl = add_builtin_function ("__builtin_source_location",
4681 auto_ftype, CP_BUILT_IN_SOURCE_LOCATION,
4682 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4683 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4685 tree bool_vaftype = build_varargs_function_type_list (boolean_type_node,
4686 NULL_TREE);
4687 decl
4688 = add_builtin_function ("__builtin_is_corresponding_member",
4689 bool_vaftype,
4690 CP_BUILT_IN_IS_CORRESPONDING_MEMBER,
4691 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4692 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4694 decl
4695 = add_builtin_function ("__builtin_is_pointer_interconvertible_with_class",
4696 bool_vaftype,
4697 CP_BUILT_IN_IS_POINTER_INTERCONVERTIBLE_WITH_CLASS,
4698 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4699 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4701 integer_two_node = build_int_cst (NULL_TREE, 2);
4703 /* Guess at the initial static decls size. */
4704 vec_alloc (static_decls, 500);
4706 /* ... and keyed classes. */
4707 vec_alloc (keyed_classes, 100);
4709 record_builtin_type (RID_BOOL, "bool", boolean_type_node);
4710 truthvalue_type_node = boolean_type_node;
4711 truthvalue_false_node = boolean_false_node;
4712 truthvalue_true_node = boolean_true_node;
4714 empty_except_spec = build_tree_list (NULL_TREE, NULL_TREE);
4715 noexcept_true_spec = build_tree_list (boolean_true_node, NULL_TREE);
4716 noexcept_false_spec = build_tree_list (boolean_false_node, NULL_TREE);
4717 noexcept_deferred_spec = build_tree_list (make_node (DEFERRED_NOEXCEPT),
4718 NULL_TREE);
4720 #if 0
4721 record_builtin_type (RID_MAX, NULL, string_type_node);
4722 #endif
4724 delta_type_node = ptrdiff_type_node;
4725 vtable_index_type = ptrdiff_type_node;
4727 vtt_parm_type = build_pointer_type (const_ptr_type_node);
4728 void_ftype = build_function_type_list (void_type_node, NULL_TREE);
4729 void_ftype_ptr = build_function_type_list (void_type_node,
4730 ptr_type_node, NULL_TREE);
4731 void_ftype_ptr
4732 = build_exception_variant (void_ftype_ptr, empty_except_spec);
4734 /* Create the conversion operator marker. This operator's DECL_NAME
4735 is in the identifier table, so we can use identifier equality to
4736 find it. */
4737 conv_op_marker = build_lang_decl (FUNCTION_DECL, conv_op_identifier,
4738 void_ftype);
4740 /* C++ extensions */
4742 unknown_type_node = make_node (LANG_TYPE);
4743 record_unknown_type (unknown_type_node, "unknown type");
4745 /* Indirecting an UNKNOWN_TYPE node yields an UNKNOWN_TYPE node. */
4746 TREE_TYPE (unknown_type_node) = unknown_type_node;
4748 /* Looking up TYPE_POINTER_TO and TYPE_REFERENCE_TO yield the same
4749 result. */
4750 TYPE_POINTER_TO (unknown_type_node) = unknown_type_node;
4751 TYPE_REFERENCE_TO (unknown_type_node) = unknown_type_node;
4753 init_list_type_node = make_node (LANG_TYPE);
4754 record_unknown_type (init_list_type_node, "init list");
4756 /* Used when parsing to distinguish parameter-lists () and (void). */
4757 explicit_void_list_node = build_tree_list (NULL_TREE, void_type_node);
4760 /* Make sure we get a unique function type, so we can give
4761 its pointer type a name. (This wins for gdb.) */
4762 tree vfunc_type = make_node (FUNCTION_TYPE);
4763 TREE_TYPE (vfunc_type) = integer_type_node;
4764 TYPE_ARG_TYPES (vfunc_type) = NULL_TREE;
4765 layout_type (vfunc_type);
4767 vtable_entry_type = build_pointer_type (vfunc_type);
4769 record_builtin_type (RID_MAX, "__vtbl_ptr_type", vtable_entry_type);
4771 vtbl_type_node
4772 = build_cplus_array_type (vtable_entry_type, NULL_TREE);
4773 layout_type (vtbl_type_node);
4774 vtbl_type_node = cp_build_qualified_type (vtbl_type_node, TYPE_QUAL_CONST);
4775 record_builtin_type (RID_MAX, NULL, vtbl_type_node);
4776 vtbl_ptr_type_node = build_pointer_type (vtable_entry_type);
4777 layout_type (vtbl_ptr_type_node);
4778 record_builtin_type (RID_MAX, NULL, vtbl_ptr_type_node);
4780 push_namespace (get_identifier ("__cxxabiv1"));
4781 abi_node = current_namespace;
4782 pop_namespace ();
4784 any_targ_node = make_node (LANG_TYPE);
4785 record_unknown_type (any_targ_node, "any type");
4787 /* Now, C++. */
4788 current_lang_name = lang_name_cplusplus;
4790 if (aligned_new_threshold > 1
4791 && !pow2p_hwi (aligned_new_threshold))
4793 error ("%<-faligned-new=%d%> is not a power of two",
4794 aligned_new_threshold);
4795 aligned_new_threshold = 1;
4797 if (aligned_new_threshold == -1)
4798 aligned_new_threshold = (cxx_dialect >= cxx17) ? 1 : 0;
4799 if (aligned_new_threshold == 1)
4800 aligned_new_threshold = malloc_alignment () / BITS_PER_UNIT;
4803 tree newattrs, extvisattr;
4804 tree newtype, deltype;
4805 tree ptr_ftype_sizetype;
4806 tree new_eh_spec;
4808 ptr_ftype_sizetype
4809 = build_function_type_list (ptr_type_node, size_type_node, NULL_TREE);
4810 if (cxx_dialect == cxx98)
4812 tree bad_alloc_id;
4813 tree bad_alloc_type_node;
4814 tree bad_alloc_decl;
4816 push_nested_namespace (std_node);
4817 bad_alloc_id = get_identifier ("bad_alloc");
4818 bad_alloc_type_node = make_class_type (RECORD_TYPE);
4819 TYPE_CONTEXT (bad_alloc_type_node) = current_namespace;
4820 bad_alloc_decl
4821 = create_implicit_typedef (bad_alloc_id, bad_alloc_type_node);
4822 DECL_CONTEXT (bad_alloc_decl) = current_namespace;
4823 pop_nested_namespace (std_node);
4825 new_eh_spec
4826 = add_exception_specifier (NULL_TREE, bad_alloc_type_node, -1);
4828 else
4829 new_eh_spec = noexcept_false_spec;
4831 /* Ensure attribs.cc is initialized. */
4832 init_attributes ();
4834 extvisattr = build_tree_list (get_identifier ("externally_visible"),
4835 NULL_TREE);
4836 newattrs = tree_cons (get_identifier ("alloc_size"),
4837 build_tree_list (NULL_TREE, integer_one_node),
4838 extvisattr);
4839 newtype = cp_build_type_attribute_variant (ptr_ftype_sizetype, newattrs);
4840 newtype = build_exception_variant (newtype, new_eh_spec);
4841 deltype = cp_build_type_attribute_variant (void_ftype_ptr, extvisattr);
4842 deltype = build_exception_variant (deltype, empty_except_spec);
4843 tree opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
4844 DECL_IS_MALLOC (opnew) = 1;
4845 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4846 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4847 opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
4848 DECL_IS_MALLOC (opnew) = 1;
4849 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4850 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4851 tree opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4852 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4853 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4854 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4855 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4856 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4857 if (flag_sized_deallocation)
4859 /* Also push the sized deallocation variants:
4860 void operator delete(void*, std::size_t) throw();
4861 void operator delete[](void*, std::size_t) throw(); */
4862 tree void_ftype_ptr_size
4863 = build_function_type_list (void_type_node, ptr_type_node,
4864 size_type_node, NULL_TREE);
4865 deltype = cp_build_type_attribute_variant (void_ftype_ptr_size,
4866 extvisattr);
4867 deltype = build_exception_variant (deltype, empty_except_spec);
4868 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4869 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4870 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4871 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4872 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4873 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4876 if (aligned_new_threshold)
4878 push_nested_namespace (std_node);
4879 tree align_id = get_identifier ("align_val_t");
4880 align_type_node = start_enum (align_id, NULL_TREE, size_type_node,
4881 NULL_TREE, /*scoped*/true, NULL);
4882 pop_nested_namespace (std_node);
4884 /* operator new (size_t, align_val_t); */
4885 newtype = build_function_type_list (ptr_type_node, size_type_node,
4886 align_type_node, NULL_TREE);
4887 newtype = cp_build_type_attribute_variant (newtype, newattrs);
4888 newtype = build_exception_variant (newtype, new_eh_spec);
4889 opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
4890 DECL_IS_MALLOC (opnew) = 1;
4891 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4892 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4893 opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
4894 DECL_IS_MALLOC (opnew) = 1;
4895 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4896 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4898 /* operator delete (void *, align_val_t); */
4899 deltype = build_function_type_list (void_type_node, ptr_type_node,
4900 align_type_node, NULL_TREE);
4901 deltype = cp_build_type_attribute_variant (deltype, extvisattr);
4902 deltype = build_exception_variant (deltype, empty_except_spec);
4903 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4904 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4905 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4906 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4907 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4908 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4910 if (flag_sized_deallocation)
4912 /* operator delete (void *, size_t, align_val_t); */
4913 deltype = build_function_type_list (void_type_node, ptr_type_node,
4914 size_type_node, align_type_node,
4915 NULL_TREE);
4916 deltype = cp_build_type_attribute_variant (deltype, extvisattr);
4917 deltype = build_exception_variant (deltype, empty_except_spec);
4918 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4919 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4920 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4921 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4922 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4923 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4927 /* C++-specific nullptr initialization. */
4928 if (abi_version_at_least (9))
4929 SET_TYPE_ALIGN (nullptr_type_node, GET_MODE_ALIGNMENT (ptr_mode));
4930 record_builtin_type (RID_MAX, "decltype(nullptr)", nullptr_type_node);
4933 if (! supports_one_only ())
4934 flag_weak = 0;
4936 abort_fndecl
4937 = build_library_fn_ptr ("__cxa_pure_virtual", void_ftype,
4938 ECF_NORETURN | ECF_NOTHROW | ECF_COLD);
4939 if (flag_weak)
4940 /* If no definition is available, resolve references to NULL. */
4941 declare_weak (abort_fndecl);
4943 /* Perform other language dependent initializations. */
4944 init_class_processing ();
4945 init_rtti_processing ();
4946 init_template_processing ();
4948 if (flag_exceptions)
4949 init_exception_processing ();
4951 if (modules_p ())
4952 init_modules (parse_in);
4954 make_fname_decl = cp_make_fname_decl;
4955 start_fname_decls ();
4957 /* Show we use EH for cleanups. */
4958 if (flag_exceptions)
4959 using_eh_for_cleanups ();
4961 /* Check that the hardware interference sizes are at least
4962 alignof(max_align_t), as required by the standard. */
4963 const int max_align = max_align_t_align () / BITS_PER_UNIT;
4964 if (OPTION_SET_P (param_destruct_interfere_size))
4966 if (param_destruct_interfere_size < max_align)
4967 error ("%<--param destructive-interference-size=%d%> is less than "
4968 "%d", param_destruct_interfere_size, max_align);
4969 else if (param_destruct_interfere_size < param_l1_cache_line_size)
4970 warning (OPT_Winterference_size,
4971 "%<--param destructive-interference-size=%d%> "
4972 "is less than %<--param l1-cache-line-size=%d%>",
4973 param_destruct_interfere_size, param_l1_cache_line_size);
4975 else if (param_destruct_interfere_size)
4976 /* Assume the internal value is OK. */;
4977 else if (param_l1_cache_line_size >= max_align)
4978 param_destruct_interfere_size = param_l1_cache_line_size;
4979 /* else leave it unset. */
4981 if (OPTION_SET_P (param_construct_interfere_size))
4983 if (param_construct_interfere_size < max_align)
4984 error ("%<--param constructive-interference-size=%d%> is less than "
4985 "%d", param_construct_interfere_size, max_align);
4986 else if (param_construct_interfere_size > param_l1_cache_line_size
4987 && param_l1_cache_line_size >= max_align)
4988 warning (OPT_Winterference_size,
4989 "%<--param constructive-interference-size=%d%> "
4990 "is greater than %<--param l1-cache-line-size=%d%>",
4991 param_construct_interfere_size, param_l1_cache_line_size);
4993 else if (param_construct_interfere_size)
4994 /* Assume the internal value is OK. */;
4995 else if (param_l1_cache_line_size >= max_align)
4996 param_construct_interfere_size = param_l1_cache_line_size;
4999 /* Enter an abi node in global-module context. returns a cookie to
5000 give to pop_abi_namespace. */
5002 unsigned
5003 push_abi_namespace (tree node)
5005 push_nested_namespace (node);
5006 push_visibility ("default", 2);
5007 unsigned flags = module_kind;
5008 module_kind = 0;
5009 return flags;
5012 /* Pop an abi namespace, FLAGS is the cookie push_abi_namespace gave
5013 you. */
5015 void
5016 pop_abi_namespace (unsigned flags, tree node)
5018 module_kind = flags;
5019 pop_visibility (2);
5020 pop_nested_namespace (node);
5023 /* Create the VAR_DECL for __FUNCTION__ etc. ID is the name to give
5024 the decl, LOC is the location to give the decl, NAME is the
5025 initialization string and TYPE_DEP indicates whether NAME depended
5026 on the type of the function. We make use of that to detect
5027 __PRETTY_FUNCTION__ inside a template fn. This is being done lazily
5028 at the point of first use, so we mustn't push the decl now. */
5030 static tree
5031 cp_make_fname_decl (location_t loc, tree id, int type_dep)
5033 tree domain = NULL_TREE;
5034 tree init = NULL_TREE;
5036 if (!(type_dep && in_template_function ()))
5038 const char *name = NULL;
5039 bool release_name = false;
5041 if (current_function_decl == NULL_TREE)
5042 name = "top level";
5043 else if (type_dep == 0)
5045 /* __FUNCTION__ */
5046 name = fname_as_string (type_dep);
5047 release_name = true;
5049 else
5051 /* __PRETTY_FUNCTION__ */
5052 gcc_checking_assert (type_dep == 1);
5053 name = cxx_printable_name (current_function_decl, 2);
5056 size_t length = strlen (name);
5057 domain = build_index_type (size_int (length));
5058 init = build_string (length + 1, name);
5059 if (release_name)
5060 free (const_cast<char *> (name));
5063 tree type = cp_build_qualified_type (char_type_node, TYPE_QUAL_CONST);
5064 type = build_cplus_array_type (type, domain);
5066 if (init)
5067 TREE_TYPE (init) = type;
5068 else
5069 init = error_mark_node;
5071 tree decl = build_decl (loc, VAR_DECL, id, type);
5073 TREE_READONLY (decl) = 1;
5074 DECL_ARTIFICIAL (decl) = 1;
5075 DECL_DECLARED_CONSTEXPR_P (decl) = 1;
5076 TREE_STATIC (decl) = 1;
5078 TREE_USED (decl) = 1;
5080 SET_DECL_VALUE_EXPR (decl, init);
5081 DECL_HAS_VALUE_EXPR_P (decl) = 1;
5082 /* For decl_constant_var_p. */
5083 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
5085 if (current_function_decl)
5087 DECL_CONTEXT (decl) = current_function_decl;
5088 decl = pushdecl_outermost_localscope (decl);
5089 if (decl != error_mark_node)
5090 add_decl_expr (decl);
5092 else
5094 DECL_THIS_STATIC (decl) = true;
5095 decl = pushdecl_top_level_and_finish (decl, NULL_TREE);
5098 return decl;
5101 /* Install DECL as a builtin function at current global scope. Return
5102 the new decl (if we found an existing version). Also installs it
5103 into ::std, if it's not '_*'. */
5105 tree
5106 cxx_builtin_function (tree decl)
5108 retrofit_lang_decl (decl);
5110 DECL_ARTIFICIAL (decl) = 1;
5111 SET_DECL_LANGUAGE (decl, lang_c);
5112 /* Runtime library routines are, by definition, available in an
5113 external shared object. */
5114 DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
5115 DECL_VISIBILITY_SPECIFIED (decl) = 1;
5117 tree id = DECL_NAME (decl);
5118 const char *name = IDENTIFIER_POINTER (id);
5119 bool hiding = false;
5120 if (name[0] != '_' || name[1] != '_')
5121 /* In the user's namespace, it must be declared before use. */
5122 hiding = true;
5123 else if (IDENTIFIER_LENGTH (id) > strlen ("___chk")
5124 && !startswith (name + 2, "builtin_")
5125 && 0 == memcmp (name + IDENTIFIER_LENGTH (id) - strlen ("_chk"),
5126 "_chk", strlen ("_chk") + 1))
5127 /* Treat __*_chk fortification functions as anticipated as well,
5128 unless they are __builtin_*_chk. */
5129 hiding = true;
5131 /* All builtins that don't begin with an '_' should additionally
5132 go in the 'std' namespace. */
5133 if (name[0] != '_')
5135 tree std_decl = copy_decl (decl);
5137 push_nested_namespace (std_node);
5138 DECL_CONTEXT (std_decl) = FROB_CONTEXT (std_node);
5139 pushdecl (std_decl, hiding);
5140 pop_nested_namespace (std_node);
5143 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5144 decl = pushdecl (decl, hiding);
5146 return decl;
5149 /* Like cxx_builtin_function, but guarantee the function is added to the global
5150 scope. This is to allow function specific options to add new machine
5151 dependent builtins when the target ISA changes via attribute((target(...)))
5152 which saves space on program startup if the program does not use non-generic
5153 ISAs. */
5155 tree
5156 cxx_builtin_function_ext_scope (tree decl)
5158 push_nested_namespace (global_namespace);
5159 decl = cxx_builtin_function (decl);
5160 pop_nested_namespace (global_namespace);
5162 return decl;
5165 /* Implement LANG_HOOKS_SIMULATE_BUILTIN_FUNCTION_DECL. */
5167 tree
5168 cxx_simulate_builtin_function_decl (tree decl)
5170 retrofit_lang_decl (decl);
5172 DECL_ARTIFICIAL (decl) = 1;
5173 SET_DECL_LANGUAGE (decl, lang_cplusplus);
5174 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5175 return pushdecl (decl);
5178 /* Generate a FUNCTION_DECL with the typical flags for a runtime library
5179 function. Not called directly. */
5181 static tree
5182 build_library_fn (tree name, enum tree_code operator_code, tree type,
5183 int ecf_flags)
5185 tree fn = build_lang_decl (FUNCTION_DECL, name, type);
5186 DECL_EXTERNAL (fn) = 1;
5187 TREE_PUBLIC (fn) = 1;
5188 DECL_ARTIFICIAL (fn) = 1;
5189 DECL_OVERLOADED_OPERATOR_CODE_RAW (fn)
5190 = OVL_OP_INFO (false, operator_code)->ovl_op_code;
5191 SET_DECL_LANGUAGE (fn, lang_c);
5192 /* Runtime library routines are, by definition, available in an
5193 external shared object. */
5194 DECL_VISIBILITY (fn) = VISIBILITY_DEFAULT;
5195 DECL_VISIBILITY_SPECIFIED (fn) = 1;
5196 set_call_expr_flags (fn, ecf_flags);
5197 return fn;
5200 /* Returns the _DECL for a library function with C++ linkage. */
5202 static tree
5203 build_cp_library_fn (tree name, enum tree_code operator_code, tree type,
5204 int ecf_flags)
5206 tree fn = build_library_fn (name, operator_code, type, ecf_flags);
5207 DECL_CONTEXT (fn) = FROB_CONTEXT (current_namespace);
5208 SET_DECL_LANGUAGE (fn, lang_cplusplus);
5209 return fn;
5212 /* Like build_library_fn, but takes a C string instead of an
5213 IDENTIFIER_NODE. */
5215 tree
5216 build_library_fn_ptr (const char* name, tree type, int ecf_flags)
5218 return build_library_fn (get_identifier (name), ERROR_MARK, type, ecf_flags);
5221 /* Like build_cp_library_fn, but takes a C string instead of an
5222 IDENTIFIER_NODE. */
5224 tree
5225 build_cp_library_fn_ptr (const char* name, tree type, int ecf_flags)
5227 return build_cp_library_fn (get_identifier (name), ERROR_MARK, type,
5228 ecf_flags);
5231 /* Like build_library_fn, but also pushes the function so that we will
5232 be able to find it via get_global_binding. Also, the function
5233 may throw exceptions listed in RAISES. */
5235 tree
5236 push_library_fn (tree name, tree type, tree raises, int ecf_flags)
5238 if (raises)
5239 type = build_exception_variant (type, raises);
5241 tree fn = build_library_fn (name, ERROR_MARK, type, ecf_flags);
5242 return pushdecl_top_level (fn);
5245 /* Like build_cp_library_fn, but also pushes the function so that it
5246 will be found by normal lookup. */
5248 static tree
5249 push_cp_library_fn (enum tree_code operator_code, tree type,
5250 int ecf_flags)
5252 tree fn = build_cp_library_fn (ovl_op_identifier (false, operator_code),
5253 operator_code, type, ecf_flags);
5254 pushdecl (fn);
5255 if (flag_tm)
5256 apply_tm_attr (fn, get_identifier ("transaction_safe"));
5257 return fn;
5260 /* Like push_library_fn, but also note that this function throws
5261 and does not return. Used for __throw_foo and the like. */
5263 tree
5264 push_throw_library_fn (tree name, tree type)
5266 tree fn = push_library_fn (name, type, NULL_TREE, ECF_NORETURN | ECF_COLD);
5267 return fn;
5270 /* When we call finish_struct for an anonymous union, we create
5271 default copy constructors and such. But, an anonymous union
5272 shouldn't have such things; this function undoes the damage to the
5273 anonymous union type T.
5275 (The reason that we create the synthesized methods is that we don't
5276 distinguish `union { int i; }' from `typedef union { int i; } U'.
5277 The first is an anonymous union; the second is just an ordinary
5278 union type.) */
5280 void
5281 fixup_anonymous_aggr (tree t)
5283 /* Wipe out memory of synthesized methods. */
5284 TYPE_HAS_USER_CONSTRUCTOR (t) = 0;
5285 TYPE_HAS_DEFAULT_CONSTRUCTOR (t) = 0;
5286 TYPE_HAS_COPY_CTOR (t) = 0;
5287 TYPE_HAS_CONST_COPY_CTOR (t) = 0;
5288 TYPE_HAS_COPY_ASSIGN (t) = 0;
5289 TYPE_HAS_CONST_COPY_ASSIGN (t) = 0;
5291 /* Splice the implicitly generated functions out of TYPE_FIELDS and diagnose
5292 invalid members. */
5293 for (tree probe, *prev_p = &TYPE_FIELDS (t); (probe = *prev_p);)
5295 if (TREE_CODE (probe) == FUNCTION_DECL && DECL_ARTIFICIAL (probe))
5296 *prev_p = DECL_CHAIN (probe);
5297 else
5298 prev_p = &DECL_CHAIN (probe);
5300 if (DECL_ARTIFICIAL (probe)
5301 && (!DECL_IMPLICIT_TYPEDEF_P (probe)
5302 || TYPE_ANON_P (TREE_TYPE (probe))))
5303 continue;
5305 if (TREE_CODE (probe) != FIELD_DECL
5306 || (TREE_PRIVATE (probe) || TREE_PROTECTED (probe)))
5308 /* We already complained about static data members in
5309 finish_static_data_member_decl. */
5310 if (!VAR_P (probe))
5312 auto_diagnostic_group d;
5313 if (permerror (DECL_SOURCE_LOCATION (probe),
5314 TREE_CODE (t) == UNION_TYPE
5315 ? "%q#D invalid; an anonymous union may "
5316 "only have public non-static data members"
5317 : "%q#D invalid; an anonymous struct may "
5318 "only have public non-static data members", probe))
5320 static bool hint;
5321 if (flag_permissive && !hint)
5323 hint = true;
5324 inform (DECL_SOURCE_LOCATION (probe),
5325 "this flexibility is deprecated and will be "
5326 "removed");
5333 /* Splice all functions out of CLASSTYPE_MEMBER_VEC. */
5334 vec<tree,va_gc>* vec = CLASSTYPE_MEMBER_VEC (t);
5335 unsigned store = 0;
5336 for (tree elt : vec)
5337 if (!is_overloaded_fn (elt))
5338 (*vec)[store++] = elt;
5339 vec_safe_truncate (vec, store);
5341 /* Wipe RTTI info. */
5342 CLASSTYPE_TYPEINFO_VAR (t) = NULL_TREE;
5344 /* Anonymous aggregates cannot have fields with ctors, dtors or complex
5345 assignment operators (because they cannot have these methods themselves).
5346 For anonymous unions this is already checked because they are not allowed
5347 in any union, otherwise we have to check it. */
5348 if (TREE_CODE (t) != UNION_TYPE)
5350 tree field, type;
5352 if (BINFO_N_BASE_BINFOS (TYPE_BINFO (t)))
5354 error_at (location_of (t), "anonymous struct with base classes");
5355 /* Avoid ICE after error on anon-struct9.C. */
5356 TYPE_NEEDS_CONSTRUCTING (t) = false;
5359 for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
5360 if (TREE_CODE (field) == FIELD_DECL)
5362 type = TREE_TYPE (field);
5363 if (CLASS_TYPE_P (type))
5365 if (TYPE_NEEDS_CONSTRUCTING (type))
5366 error ("member %q+#D with constructor not allowed "
5367 "in anonymous aggregate", field);
5368 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
5369 error ("member %q+#D with destructor not allowed "
5370 "in anonymous aggregate", field);
5371 if (TYPE_HAS_COMPLEX_COPY_ASSIGN (type))
5372 error ("member %q+#D with copy assignment operator "
5373 "not allowed in anonymous aggregate", field);
5379 /* Warn for an attribute located at LOCATION that appertains to the
5380 class type CLASS_TYPE that has not been properly placed after its
5381 class-key, in it class-specifier. */
5383 void
5384 warn_misplaced_attr_for_class_type (location_t location,
5385 tree class_type)
5387 gcc_assert (OVERLOAD_TYPE_P (class_type));
5389 auto_diagnostic_group d;
5390 if (warning_at (location, OPT_Wattributes,
5391 "attribute ignored in declaration "
5392 "of %q#T", class_type))
5393 inform (location,
5394 "attribute for %q#T must follow the %qs keyword",
5395 class_type, class_key_or_enum_as_string (class_type));
5398 /* Returns the cv-qualifiers that apply to the type specified
5399 by the DECLSPECS. */
5401 static int
5402 get_type_quals (const cp_decl_specifier_seq *declspecs)
5404 int type_quals = TYPE_UNQUALIFIED;
5406 if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5407 type_quals |= TYPE_QUAL_CONST;
5408 if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5409 type_quals |= TYPE_QUAL_VOLATILE;
5410 if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5411 type_quals |= TYPE_QUAL_RESTRICT;
5413 return type_quals;
5416 /* Make sure that a declaration with no declarator is well-formed, i.e.
5417 just declares a tagged type or anonymous union.
5419 Returns the type declared; or NULL_TREE if none. */
5421 tree
5422 check_tag_decl (cp_decl_specifier_seq *declspecs,
5423 bool explicit_type_instantiation_p)
5425 int saw_friend = decl_spec_seq_has_spec_p (declspecs, ds_friend);
5426 int saw_typedef = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
5427 /* If a class, struct, or enum type is declared by the DECLSPECS
5428 (i.e, if a class-specifier, enum-specifier, or non-typename
5429 elaborated-type-specifier appears in the DECLSPECS),
5430 DECLARED_TYPE is set to the corresponding type. */
5431 tree declared_type = NULL_TREE;
5432 bool error_p = false;
5434 if (declspecs->multiple_types_p)
5435 error_at (smallest_type_location (declspecs),
5436 "multiple types in one declaration");
5437 else if (declspecs->redefined_builtin_type)
5439 location_t loc = declspecs->locations[ds_redefined_builtin_type_spec];
5440 if (!in_system_header_at (loc))
5441 permerror (loc, "redeclaration of C++ built-in type %qT",
5442 declspecs->redefined_builtin_type);
5443 return NULL_TREE;
5446 if (declspecs->type
5447 && TYPE_P (declspecs->type)
5448 && ((TREE_CODE (declspecs->type) != TYPENAME_TYPE
5449 && MAYBE_CLASS_TYPE_P (declspecs->type))
5450 || TREE_CODE (declspecs->type) == ENUMERAL_TYPE))
5451 declared_type = declspecs->type;
5452 else if (declspecs->type == error_mark_node)
5453 error_p = true;
5455 if (type_uses_auto (declared_type))
5457 error_at (declspecs->locations[ds_type_spec],
5458 "%<auto%> can only be specified for variables "
5459 "or function declarations");
5460 return error_mark_node;
5463 if (declared_type && !OVERLOAD_TYPE_P (declared_type))
5464 declared_type = NULL_TREE;
5466 if (!declared_type && !saw_friend && !error_p)
5467 permerror (input_location, "declaration does not declare anything");
5468 /* Check for an anonymous union. */
5469 else if (declared_type && RECORD_OR_UNION_CODE_P (TREE_CODE (declared_type))
5470 && TYPE_UNNAMED_P (declared_type))
5472 /* 7/3 In a simple-declaration, the optional init-declarator-list
5473 can be omitted only when declaring a class (clause 9) or
5474 enumeration (7.2), that is, when the decl-specifier-seq contains
5475 either a class-specifier, an elaborated-type-specifier with
5476 a class-key (9.1), or an enum-specifier. In these cases and
5477 whenever a class-specifier or enum-specifier is present in the
5478 decl-specifier-seq, the identifiers in these specifiers are among
5479 the names being declared by the declaration (as class-name,
5480 enum-names, or enumerators, depending on the syntax). In such
5481 cases, and except for the declaration of an unnamed bit-field (9.6),
5482 the decl-specifier-seq shall introduce one or more names into the
5483 program, or shall redeclare a name introduced by a previous
5484 declaration. [Example:
5485 enum { }; // ill-formed
5486 typedef class { }; // ill-formed
5487 --end example] */
5488 if (saw_typedef)
5490 error_at (declspecs->locations[ds_typedef],
5491 "missing type-name in typedef-declaration");
5492 return NULL_TREE;
5494 /* Anonymous unions are objects, so they can have specifiers. */;
5495 SET_ANON_AGGR_TYPE_P (declared_type);
5497 if (TREE_CODE (declared_type) != UNION_TYPE)
5498 pedwarn (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (declared_type)),
5499 OPT_Wpedantic, "ISO C++ prohibits anonymous structs");
5502 else
5504 if (decl_spec_seq_has_spec_p (declspecs, ds_inline))
5505 error_at (declspecs->locations[ds_inline],
5506 "%<inline%> can only be specified for functions");
5507 else if (decl_spec_seq_has_spec_p (declspecs, ds_virtual))
5508 error_at (declspecs->locations[ds_virtual],
5509 "%<virtual%> can only be specified for functions");
5510 else if (saw_friend
5511 && (!current_class_type
5512 || current_scope () != current_class_type))
5513 error_at (declspecs->locations[ds_friend],
5514 "%<friend%> can only be specified inside a class");
5515 else if (decl_spec_seq_has_spec_p (declspecs, ds_explicit))
5516 error_at (declspecs->locations[ds_explicit],
5517 "%<explicit%> can only be specified for constructors");
5518 else if (declspecs->storage_class)
5519 error_at (declspecs->locations[ds_storage_class],
5520 "a storage class can only be specified for objects "
5521 "and functions");
5522 else if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5523 error_at (declspecs->locations[ds_const],
5524 "%<const%> can only be specified for objects and "
5525 "functions");
5526 else if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5527 error_at (declspecs->locations[ds_volatile],
5528 "%<volatile%> can only be specified for objects and "
5529 "functions");
5530 else if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5531 error_at (declspecs->locations[ds_restrict],
5532 "%<__restrict%> can only be specified for objects and "
5533 "functions");
5534 else if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
5535 error_at (declspecs->locations[ds_thread],
5536 "%<__thread%> can only be specified for objects "
5537 "and functions");
5538 else if (saw_typedef)
5539 warning_at (declspecs->locations[ds_typedef], 0,
5540 "%<typedef%> was ignored in this declaration");
5541 else if (decl_spec_seq_has_spec_p (declspecs, ds_constexpr))
5542 error_at (declspecs->locations[ds_constexpr],
5543 "%qs cannot be used for type declarations", "constexpr");
5544 else if (decl_spec_seq_has_spec_p (declspecs, ds_constinit))
5545 error_at (declspecs->locations[ds_constinit],
5546 "%qs cannot be used for type declarations", "constinit");
5547 else if (decl_spec_seq_has_spec_p (declspecs, ds_consteval))
5548 error_at (declspecs->locations[ds_consteval],
5549 "%qs cannot be used for type declarations", "consteval");
5552 if (declspecs->attributes && warn_attributes && declared_type)
5554 location_t loc;
5555 if (!CLASS_TYPE_P (declared_type)
5556 || !CLASSTYPE_TEMPLATE_INSTANTIATION (declared_type))
5557 /* For a non-template class, use the name location. */
5558 loc = location_of (declared_type);
5559 else
5560 /* For a template class (an explicit instantiation), use the
5561 current location. */
5562 loc = input_location;
5564 if (explicit_type_instantiation_p)
5565 /* [dcl.attr.grammar]/4:
5567 No attribute-specifier-seq shall appertain to an explicit
5568 instantiation. */
5570 if (warning_at (loc, OPT_Wattributes,
5571 "attribute ignored in explicit instantiation %q#T",
5572 declared_type))
5573 inform (loc,
5574 "no attribute can be applied to "
5575 "an explicit instantiation");
5577 else
5578 warn_misplaced_attr_for_class_type (loc, declared_type);
5581 /* Diagnose invalid application of contracts, if any. */
5582 if (find_contract (declspecs->attributes))
5583 diagnose_misapplied_contracts (declspecs->attributes);
5584 else
5585 diagnose_misapplied_contracts (declspecs->std_attributes);
5587 return declared_type;
5590 /* Called when a declaration is seen that contains no names to declare.
5591 If its type is a reference to a structure, union or enum inherited
5592 from a containing scope, shadow that tag name for the current scope
5593 with a forward reference.
5594 If its type defines a new named structure or union
5595 or defines an enum, it is valid but we need not do anything here.
5596 Otherwise, it is an error.
5598 C++: may have to grok the declspecs to learn about static,
5599 complain for anonymous unions.
5601 Returns the TYPE declared -- or NULL_TREE if none. */
5603 tree
5604 shadow_tag (cp_decl_specifier_seq *declspecs)
5606 tree t = check_tag_decl (declspecs,
5607 /*explicit_type_instantiation_p=*/false);
5609 if (!t)
5610 return NULL_TREE;
5612 t = maybe_process_partial_specialization (t);
5613 if (t == error_mark_node)
5614 return NULL_TREE;
5616 /* This is where the variables in an anonymous union are
5617 declared. An anonymous union declaration looks like:
5618 union { ... } ;
5619 because there is no declarator after the union, the parser
5620 sends that declaration here. */
5621 if (ANON_AGGR_TYPE_P (t))
5623 fixup_anonymous_aggr (t);
5625 if (TYPE_FIELDS (t))
5627 tree decl = grokdeclarator (/*declarator=*/NULL,
5628 declspecs, NORMAL, 0, NULL);
5629 finish_anon_union (decl);
5633 return t;
5636 /* Decode a "typename", such as "int **", returning a ..._TYPE node. */
5638 tree
5639 groktypename (cp_decl_specifier_seq *type_specifiers,
5640 const cp_declarator *declarator,
5641 bool is_template_arg)
5643 tree attrs;
5644 tree type;
5645 enum decl_context context
5646 = is_template_arg ? TEMPLATE_TYPE_ARG : TYPENAME;
5647 attrs = type_specifiers->attributes;
5648 type_specifiers->attributes = NULL_TREE;
5649 type = grokdeclarator (declarator, type_specifiers, context, 0, &attrs);
5650 if (attrs && type != error_mark_node)
5652 if (CLASS_TYPE_P (type))
5653 warning (OPT_Wattributes, "ignoring attributes applied to class type %qT "
5654 "outside of definition", type);
5655 else if (MAYBE_CLASS_TYPE_P (type))
5656 /* A template type parameter or other dependent type. */
5657 warning (OPT_Wattributes, "ignoring attributes applied to dependent "
5658 "type %qT without an associated declaration", type);
5659 else
5660 cplus_decl_attributes (&type, attrs, 0);
5662 return type;
5665 /* Process a DECLARATOR for a function-scope or namespace-scope
5666 variable or function declaration.
5667 (Function definitions go through start_function; class member
5668 declarations appearing in the body of the class go through
5669 grokfield.) The DECL corresponding to the DECLARATOR is returned.
5670 If an error occurs, the error_mark_node is returned instead.
5672 DECLSPECS are the decl-specifiers for the declaration. INITIALIZED is
5673 SD_INITIALIZED if an explicit initializer is present, or SD_DEFAULTED
5674 for an explicitly defaulted function, or SD_DELETED for an explicitly
5675 deleted function, but 0 (SD_UNINITIALIZED) if this is a variable
5676 implicitly initialized via a default constructor. It can also be
5677 SD_DECOMPOSITION which behaves much like SD_INITIALIZED, but we also
5678 mark the new decl as DECL_DECOMPOSITION_P.
5680 ATTRIBUTES and PREFIX_ATTRIBUTES are GNU attributes associated with this
5681 declaration.
5683 The scope represented by the context of the returned DECL is pushed
5684 (if it is not the global namespace) and is assigned to
5685 *PUSHED_SCOPE_P. The caller is then responsible for calling
5686 pop_scope on *PUSHED_SCOPE_P if it is set. */
5688 tree
5689 start_decl (const cp_declarator *declarator,
5690 cp_decl_specifier_seq *declspecs,
5691 int initialized,
5692 tree attributes,
5693 tree prefix_attributes,
5694 tree *pushed_scope_p)
5696 tree decl;
5697 tree context;
5698 bool was_public;
5699 int flags;
5700 bool alias;
5701 tree initial;
5703 *pushed_scope_p = NULL_TREE;
5705 if (prefix_attributes != error_mark_node)
5706 attributes = attr_chainon (attributes, prefix_attributes);
5708 decl = grokdeclarator (declarator, declspecs, NORMAL, initialized,
5709 &attributes);
5711 if (decl == NULL_TREE || VOID_TYPE_P (decl)
5712 || decl == error_mark_node
5713 || prefix_attributes == error_mark_node)
5714 return error_mark_node;
5716 context = CP_DECL_CONTEXT (decl);
5717 if (context != global_namespace)
5718 *pushed_scope_p = push_scope (context);
5720 if (initialized && TREE_CODE (decl) == TYPE_DECL)
5722 error_at (DECL_SOURCE_LOCATION (decl),
5723 "typedef %qD is initialized (use %qs instead)",
5724 decl, "decltype");
5725 return error_mark_node;
5728 /* Save the DECL_INITIAL value in case it gets clobbered to assist
5729 with attribute validation. */
5730 initial = DECL_INITIAL (decl);
5732 if (initialized)
5734 if (! toplevel_bindings_p ()
5735 && DECL_EXTERNAL (decl))
5736 warning (0, "declaration of %q#D has %<extern%> and is initialized",
5737 decl);
5738 DECL_EXTERNAL (decl) = 0;
5739 if (toplevel_bindings_p ())
5740 TREE_STATIC (decl) = 1;
5741 /* Tell 'cplus_decl_attributes' this is an initialized decl,
5742 even though we might not yet have the initializer expression. */
5743 if (!DECL_INITIAL (decl))
5744 DECL_INITIAL (decl) = error_mark_node;
5746 alias = lookup_attribute ("alias", DECL_ATTRIBUTES (decl)) != 0;
5748 if (alias && TREE_CODE (decl) == FUNCTION_DECL)
5749 record_key_method_defined (decl);
5751 /* If this is a typedef that names the class for linkage purposes
5752 (7.1.3p8), apply any attributes directly to the type. */
5753 if (TREE_CODE (decl) == TYPE_DECL
5754 && OVERLOAD_TYPE_P (TREE_TYPE (decl))
5755 && decl == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (decl))))
5756 flags = ATTR_FLAG_TYPE_IN_PLACE;
5757 else
5758 flags = 0;
5760 /* Set attributes here so if duplicate decl, will have proper attributes. */
5761 cplus_decl_attributes (&decl, attributes, flags);
5763 /* Restore the original DECL_INITIAL that we may have clobbered earlier to
5764 assist with attribute validation. */
5765 DECL_INITIAL (decl) = initial;
5767 /* Dllimported symbols cannot be defined. Static data members (which
5768 can be initialized in-class and dllimported) go through grokfield,
5769 not here, so we don't need to exclude those decls when checking for
5770 a definition. */
5771 if (initialized && DECL_DLLIMPORT_P (decl))
5773 error_at (DECL_SOURCE_LOCATION (decl),
5774 "definition of %q#D is marked %<dllimport%>", decl);
5775 DECL_DLLIMPORT_P (decl) = 0;
5778 /* If #pragma weak was used, mark the decl weak now. */
5779 if (!processing_template_decl && !DECL_DECOMPOSITION_P (decl))
5780 maybe_apply_pragma_weak (decl);
5782 if (TREE_CODE (decl) == FUNCTION_DECL
5783 && DECL_DECLARED_INLINE_P (decl)
5784 && DECL_UNINLINABLE (decl)
5785 && lookup_attribute ("noinline", DECL_ATTRIBUTES (decl)))
5786 warning_at (DECL_SOURCE_LOCATION (decl), 0,
5787 "inline function %qD given attribute %qs", decl, "noinline");
5789 if (TYPE_P (context) && COMPLETE_TYPE_P (complete_type (context)))
5791 bool this_tmpl = (current_template_depth
5792 > template_class_depth (context));
5793 if (VAR_P (decl))
5795 tree field = lookup_field (context, DECL_NAME (decl), 0, false);
5796 if (field == NULL_TREE
5797 || !(VAR_P (field) || variable_template_p (field)))
5798 error ("%q+#D is not a static data member of %q#T", decl, context);
5799 else if (variable_template_p (field)
5800 && (DECL_LANG_SPECIFIC (decl)
5801 && DECL_TEMPLATE_SPECIALIZATION (decl)))
5802 /* OK, specialization was already checked. */;
5803 else if (variable_template_p (field) && !this_tmpl)
5805 error_at (DECL_SOURCE_LOCATION (decl),
5806 "non-member-template declaration of %qD", decl);
5807 inform (DECL_SOURCE_LOCATION (field), "does not match "
5808 "member template declaration here");
5809 return error_mark_node;
5811 else
5813 if (variable_template_p (field))
5814 field = DECL_TEMPLATE_RESULT (field);
5816 if (DECL_CONTEXT (field) != context)
5818 if (!same_type_p (DECL_CONTEXT (field), context))
5819 permerror (input_location, "ISO C++ does not permit %<%T::%D%> "
5820 "to be defined as %<%T::%D%>",
5821 DECL_CONTEXT (field), DECL_NAME (decl),
5822 context, DECL_NAME (decl));
5823 DECL_CONTEXT (decl) = DECL_CONTEXT (field);
5825 /* Static data member are tricky; an in-class initialization
5826 still doesn't provide a definition, so the in-class
5827 declaration will have DECL_EXTERNAL set, but will have an
5828 initialization. Thus, duplicate_decls won't warn
5829 about this situation, and so we check here. */
5830 if (initialized && DECL_INITIALIZED_IN_CLASS_P (field))
5831 error ("duplicate initialization of %qD", decl);
5832 field = duplicate_decls (decl, field);
5833 if (field == error_mark_node)
5834 return error_mark_node;
5835 else if (field)
5836 decl = field;
5839 else
5841 tree field = check_classfn (context, decl,
5842 this_tmpl
5843 ? current_template_parms
5844 : NULL_TREE);
5845 if (field && field != error_mark_node
5846 && duplicate_decls (decl, field))
5847 decl = field;
5850 /* cp_finish_decl sets DECL_EXTERNAL if DECL_IN_AGGR_P is set. */
5851 DECL_IN_AGGR_P (decl) = 0;
5852 /* Do not mark DECL as an explicit specialization if it was not
5853 already marked as an instantiation; a declaration should
5854 never be marked as a specialization unless we know what
5855 template is being specialized. */
5856 if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
5858 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
5859 if (TREE_CODE (decl) == FUNCTION_DECL)
5860 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
5861 && DECL_DECLARED_INLINE_P (decl));
5862 else
5863 DECL_COMDAT (decl) = false;
5865 /* [temp.expl.spec] An explicit specialization of a static data
5866 member of a template is a definition if the declaration
5867 includes an initializer; otherwise, it is a declaration.
5869 We check for processing_specialization so this only applies
5870 to the new specialization syntax. */
5871 if (!initialized && processing_specialization)
5872 DECL_EXTERNAL (decl) = 1;
5875 if (DECL_EXTERNAL (decl) && ! DECL_TEMPLATE_SPECIALIZATION (decl)
5876 /* Aliases are definitions. */
5877 && !alias)
5879 if (DECL_VIRTUAL_P (decl) || !flag_contracts)
5880 permerror (declarator->id_loc,
5881 "declaration of %q#D outside of class is not definition",
5882 decl);
5883 else if (flag_contract_strict_declarations)
5884 warning_at (declarator->id_loc, OPT_fcontract_strict_declarations_,
5885 "declaration of %q#D outside of class is not definition",
5886 decl);
5890 /* Create a DECL_LANG_SPECIFIC so that DECL_DECOMPOSITION_P works. */
5891 if (initialized == SD_DECOMPOSITION)
5892 fit_decomposition_lang_decl (decl, NULL_TREE);
5894 was_public = TREE_PUBLIC (decl);
5896 if ((DECL_EXTERNAL (decl) || TREE_CODE (decl) == FUNCTION_DECL)
5897 && current_function_decl)
5899 /* A function-scope decl of some namespace-scope decl. */
5900 DECL_LOCAL_DECL_P (decl) = true;
5901 if (named_module_purview_p ())
5902 error_at (declarator->id_loc,
5903 "block-scope extern declaration %q#D not permitted"
5904 " in module purview", decl);
5907 /* Enter this declaration into the symbol table. Don't push the plain
5908 VAR_DECL for a variable template. */
5909 if (!template_parm_scope_p ()
5910 || !VAR_P (decl))
5911 decl = maybe_push_decl (decl);
5913 if (processing_template_decl)
5914 decl = push_template_decl (decl);
5916 if (decl == error_mark_node)
5917 return error_mark_node;
5919 if (VAR_P (decl)
5920 && DECL_NAMESPACE_SCOPE_P (decl) && !TREE_PUBLIC (decl) && !was_public
5921 && !DECL_THIS_STATIC (decl) && !DECL_ARTIFICIAL (decl)
5922 /* But not templated variables. */
5923 && !(DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)))
5925 /* This is a const variable with implicit 'static'. Set
5926 DECL_THIS_STATIC so we can tell it from variables that are
5927 !TREE_PUBLIC because of the anonymous namespace. */
5928 gcc_assert (CP_TYPE_CONST_P (TREE_TYPE (decl)) || errorcount);
5929 DECL_THIS_STATIC (decl) = 1;
5932 if (current_function_decl && VAR_P (decl)
5933 && DECL_DECLARED_CONSTEXPR_P (current_function_decl)
5934 && cxx_dialect < cxx23)
5936 bool ok = false;
5937 if (CP_DECL_THREAD_LOCAL_P (decl) && !DECL_REALLY_EXTERN (decl))
5938 error_at (DECL_SOURCE_LOCATION (decl),
5939 "%qD defined %<thread_local%> in %qs function only "
5940 "available with %<-std=c++2b%> or %<-std=gnu++2b%>", decl,
5941 DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
5942 ? "consteval" : "constexpr");
5943 else if (TREE_STATIC (decl))
5944 error_at (DECL_SOURCE_LOCATION (decl),
5945 "%qD defined %<static%> in %qs function only available "
5946 "with %<-std=c++2b%> or %<-std=gnu++2b%>", decl,
5947 DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
5948 ? "consteval" : "constexpr");
5949 else
5950 ok = true;
5951 if (!ok)
5952 cp_function_chain->invalid_constexpr = true;
5955 if (!processing_template_decl && VAR_P (decl))
5956 start_decl_1 (decl, initialized);
5958 return decl;
5961 /* Process the declaration of a variable DECL. INITIALIZED is true
5962 iff DECL is explicitly initialized. (INITIALIZED is false if the
5963 variable is initialized via an implicitly-called constructor.)
5964 This function must be called for ordinary variables (including, for
5965 example, implicit instantiations of templates), but must not be
5966 called for template declarations. */
5968 void
5969 start_decl_1 (tree decl, bool initialized)
5971 gcc_checking_assert (!processing_template_decl);
5973 if (error_operand_p (decl))
5974 return;
5976 gcc_checking_assert (VAR_P (decl));
5978 tree type = TREE_TYPE (decl);
5979 bool complete_p = COMPLETE_TYPE_P (type);
5980 bool aggregate_definition_p
5981 = MAYBE_CLASS_TYPE_P (type) && !DECL_EXTERNAL (decl);
5983 /* If an explicit initializer is present, or if this is a definition
5984 of an aggregate, then we need a complete type at this point.
5985 (Scalars are always complete types, so there is nothing to
5986 check.) This code just sets COMPLETE_P; errors (if necessary)
5987 are issued below. */
5988 if ((initialized || aggregate_definition_p)
5989 && !complete_p
5990 && COMPLETE_TYPE_P (complete_type (type)))
5992 complete_p = true;
5993 /* We will not yet have set TREE_READONLY on DECL if the type
5994 was "const", but incomplete, before this point. But, now, we
5995 have a complete type, so we can try again. */
5996 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
5999 if (initialized)
6000 /* Is it valid for this decl to have an initializer at all? */
6002 /* Don't allow initializations for incomplete types except for
6003 arrays which might be completed by the initialization. */
6004 if (complete_p)
6005 ; /* A complete type is ok. */
6006 else if (type_uses_auto (type))
6007 ; /* An auto type is ok. */
6008 else if (TREE_CODE (type) != ARRAY_TYPE)
6010 error ("variable %q#D has initializer but incomplete type", decl);
6011 type = TREE_TYPE (decl) = error_mark_node;
6013 else if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (type))))
6015 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
6016 error ("elements of array %q#D have incomplete type", decl);
6017 /* else we already gave an error in start_decl. */
6020 else if (aggregate_definition_p && !complete_p)
6022 if (type_uses_auto (type))
6023 gcc_assert (CLASS_PLACEHOLDER_TEMPLATE (type));
6024 else
6026 error ("aggregate %q#D has incomplete type and cannot be defined",
6027 decl);
6028 /* Change the type so that assemble_variable will give
6029 DECL an rtl we can live with: (mem (const_int 0)). */
6030 type = TREE_TYPE (decl) = error_mark_node;
6034 /* Create a new scope to hold this declaration if necessary.
6035 Whether or not a new scope is necessary cannot be determined
6036 until after the type has been completed; if the type is a
6037 specialization of a class template it is not until after
6038 instantiation has occurred that TYPE_HAS_NONTRIVIAL_DESTRUCTOR
6039 will be set correctly. */
6040 maybe_push_cleanup_level (type);
6043 /* Given a parenthesized list of values INIT, create a CONSTRUCTOR to handle
6044 C++20 P0960. TYPE is the type of the object we're initializing. */
6046 tree
6047 do_aggregate_paren_init (tree init, tree type)
6049 tree val = TREE_VALUE (init);
6051 if (TREE_CHAIN (init) == NULL_TREE)
6053 /* If the list has a single element and it's a string literal,
6054 then it's the initializer for the array as a whole. */
6055 if (TREE_CODE (type) == ARRAY_TYPE
6056 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
6057 && TREE_CODE (tree_strip_any_location_wrapper (val))
6058 == STRING_CST)
6059 return val;
6060 /* Handle non-standard extensions like compound literals. This also
6061 prevents triggering aggregate parenthesized-initialization in
6062 compiler-generated code for =default. */
6063 else if (same_type_ignoring_top_level_qualifiers_p (type,
6064 TREE_TYPE (val)))
6065 return val;
6068 init = build_constructor_from_list (init_list_type_node, init);
6069 CONSTRUCTOR_IS_DIRECT_INIT (init) = true;
6070 CONSTRUCTOR_IS_PAREN_INIT (init) = true;
6071 return init;
6074 /* Handle initialization of references. DECL, TYPE, and INIT have the
6075 same meaning as in cp_finish_decl. *CLEANUP must be NULL on entry,
6076 but will be set to a new CLEANUP_STMT if a temporary is created
6077 that must be destroyed subsequently.
6079 Returns an initializer expression to use to initialize DECL, or
6080 NULL if the initialization can be performed statically.
6082 Quotes on semantics can be found in ARM 8.4.3. */
6084 static tree
6085 grok_reference_init (tree decl, tree type, tree init, int flags)
6087 if (init == NULL_TREE)
6089 if ((DECL_LANG_SPECIFIC (decl) == 0
6090 || DECL_IN_AGGR_P (decl) == 0)
6091 && ! DECL_THIS_EXTERN (decl))
6092 error_at (DECL_SOURCE_LOCATION (decl),
6093 "%qD declared as reference but not initialized", decl);
6094 return NULL_TREE;
6097 tree ttype = TREE_TYPE (type);
6098 if (TREE_CODE (init) == TREE_LIST)
6100 /* This handles (C++20 only) code like
6102 const A& r(1, 2, 3);
6104 where we treat the parenthesized list as a CONSTRUCTOR. */
6105 if (TREE_TYPE (init) == NULL_TREE
6106 && CP_AGGREGATE_TYPE_P (ttype)
6107 && !DECL_DECOMPOSITION_P (decl)
6108 && (cxx_dialect >= cxx20))
6110 /* We don't know yet if we should treat const A& r(1) as
6111 const A& r{1}. */
6112 if (list_length (init) == 1)
6114 flags |= LOOKUP_AGGREGATE_PAREN_INIT;
6115 init = build_x_compound_expr_from_list (init, ELK_INIT,
6116 tf_warning_or_error);
6118 /* If the list had more than one element, the code is ill-formed
6119 pre-C++20, so we can build a constructor right away. */
6120 else
6121 init = do_aggregate_paren_init (init, ttype);
6123 else
6124 init = build_x_compound_expr_from_list (init, ELK_INIT,
6125 tf_warning_or_error);
6128 if (TREE_CODE (ttype) != ARRAY_TYPE
6129 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
6130 /* Note: default conversion is only called in very special cases. */
6131 init = decay_conversion (init, tf_warning_or_error);
6133 /* check_initializer handles this for non-reference variables, but for
6134 references we need to do it here or the initializer will get the
6135 incomplete array type and confuse later calls to
6136 cp_complete_array_type. */
6137 if (TREE_CODE (ttype) == ARRAY_TYPE
6138 && TYPE_DOMAIN (ttype) == NULL_TREE
6139 && (BRACE_ENCLOSED_INITIALIZER_P (init)
6140 || TREE_CODE (init) == STRING_CST))
6142 cp_complete_array_type (&ttype, init, false);
6143 if (ttype != TREE_TYPE (type))
6144 type = cp_build_reference_type (ttype, TYPE_REF_IS_RVALUE (type));
6147 /* Convert INIT to the reference type TYPE. This may involve the
6148 creation of a temporary, whose lifetime must be the same as that
6149 of the reference. If so, a DECL_EXPR for the temporary will be
6150 added just after the DECL_EXPR for DECL. That's why we don't set
6151 DECL_INITIAL for local references (instead assigning to them
6152 explicitly); we need to allow the temporary to be initialized
6153 first. */
6154 return initialize_reference (type, init, flags,
6155 tf_warning_or_error);
6158 /* Designated initializers in arrays are not supported in GNU C++.
6159 The parser cannot detect this error since it does not know whether
6160 a given brace-enclosed initializer is for a class type or for an
6161 array. This function checks that CE does not use a designated
6162 initializer. If it does, an error is issued. Returns true if CE
6163 is valid, i.e., does not have a designated initializer. */
6165 bool
6166 check_array_designated_initializer (constructor_elt *ce,
6167 unsigned HOST_WIDE_INT index)
6169 /* Designated initializers for array elements are not supported. */
6170 if (ce->index)
6172 /* The parser only allows identifiers as designated
6173 initializers. */
6174 if (ce->index == error_mark_node)
6176 error ("name used in a GNU-style designated "
6177 "initializer for an array");
6178 return false;
6180 else if (identifier_p (ce->index))
6182 error ("name %qD used in a GNU-style designated "
6183 "initializer for an array", ce->index);
6184 return false;
6187 tree ce_index = build_expr_type_conversion (WANT_INT | WANT_ENUM,
6188 ce->index, true);
6189 if (ce_index
6190 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ce_index))
6191 && (TREE_CODE (ce_index = fold_non_dependent_expr (ce_index))
6192 == INTEGER_CST))
6194 /* A C99 designator is OK if it matches the current index. */
6195 if (wi::to_wide (ce_index) == index)
6197 ce->index = ce_index;
6198 return true;
6200 else
6201 sorry ("non-trivial designated initializers not supported");
6203 else
6204 error_at (cp_expr_loc_or_input_loc (ce->index),
6205 "C99 designator %qE is not an integral constant-expression",
6206 ce->index);
6208 return false;
6211 return true;
6214 /* When parsing `int a[] = {1, 2};' we don't know the size of the
6215 array until we finish parsing the initializer. If that's the
6216 situation we're in, update DECL accordingly. */
6218 static void
6219 maybe_deduce_size_from_array_init (tree decl, tree init)
6221 tree type = TREE_TYPE (decl);
6223 if (TREE_CODE (type) == ARRAY_TYPE
6224 && TYPE_DOMAIN (type) == NULL_TREE
6225 && TREE_CODE (decl) != TYPE_DECL)
6227 /* do_default is really a C-ism to deal with tentative definitions.
6228 But let's leave it here to ease the eventual merge. */
6229 int do_default = !DECL_EXTERNAL (decl);
6230 tree initializer = init ? init : DECL_INITIAL (decl);
6231 int failure = 0;
6233 /* Check that there are no designated initializers in INIT, as
6234 those are not supported in GNU C++, and as the middle-end
6235 will crash if presented with a non-numeric designated
6236 initializer. */
6237 if (initializer && BRACE_ENCLOSED_INITIALIZER_P (initializer))
6239 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initializer);
6240 constructor_elt *ce;
6241 HOST_WIDE_INT i;
6242 FOR_EACH_VEC_SAFE_ELT (v, i, ce)
6244 if (instantiation_dependent_expression_p (ce->index))
6245 return;
6246 if (!check_array_designated_initializer (ce, i))
6247 failure = 1;
6248 /* If an un-designated initializer is type-dependent, we can't
6249 check brace elision yet. */
6250 if (ce->index == NULL_TREE
6251 && type_dependent_expression_p (ce->value))
6252 return;
6256 if (failure)
6257 TREE_TYPE (decl) = error_mark_node;
6258 else
6260 failure = cp_complete_array_type (&TREE_TYPE (decl), initializer,
6261 do_default);
6262 if (failure == 1)
6264 error_at (cp_expr_loc_or_loc (initializer,
6265 DECL_SOURCE_LOCATION (decl)),
6266 "initializer fails to determine size of %qD", decl);
6268 else if (failure == 2)
6270 if (do_default)
6272 error_at (DECL_SOURCE_LOCATION (decl),
6273 "array size missing in %qD", decl);
6275 /* If a `static' var's size isn't known, make it extern as
6276 well as static, so it does not get allocated. If it's not
6277 `static', then don't mark it extern; finish_incomplete_decl
6278 will give it a default size and it will get allocated. */
6279 else if (!pedantic && TREE_STATIC (decl) && !TREE_PUBLIC (decl))
6280 DECL_EXTERNAL (decl) = 1;
6282 else if (failure == 3)
6284 error_at (DECL_SOURCE_LOCATION (decl),
6285 "zero-size array %qD", decl);
6289 cp_apply_type_quals_to_decl (cp_type_quals (TREE_TYPE (decl)), decl);
6291 relayout_decl (decl);
6295 /* Set DECL_SIZE, DECL_ALIGN, etc. for DECL (a VAR_DECL), and issue
6296 any appropriate error messages regarding the layout. */
6298 static void
6299 layout_var_decl (tree decl)
6301 tree type;
6303 type = TREE_TYPE (decl);
6304 if (type == error_mark_node)
6305 return;
6307 /* If we haven't already laid out this declaration, do so now.
6308 Note that we must not call complete type for an external object
6309 because it's type might involve templates that we are not
6310 supposed to instantiate yet. (And it's perfectly valid to say
6311 `extern X x' for some incomplete type `X'.) */
6312 if (!DECL_EXTERNAL (decl))
6313 complete_type (type);
6314 if (!DECL_SIZE (decl)
6315 && TREE_TYPE (decl) != error_mark_node
6316 && complete_or_array_type_p (type))
6317 layout_decl (decl, 0);
6319 if (!DECL_EXTERNAL (decl) && DECL_SIZE (decl) == NULL_TREE)
6321 /* An automatic variable with an incomplete type: that is an error.
6322 Don't talk about array types here, since we took care of that
6323 message in grokdeclarator. */
6324 error_at (DECL_SOURCE_LOCATION (decl),
6325 "storage size of %qD isn%'t known", decl);
6326 TREE_TYPE (decl) = error_mark_node;
6328 #if 0
6329 /* Keep this code around in case we later want to control debug info
6330 based on whether a type is "used". (jason 1999-11-11) */
6332 else if (!DECL_EXTERNAL (decl) && MAYBE_CLASS_TYPE_P (ttype))
6333 /* Let debugger know it should output info for this type. */
6334 note_debug_info_needed (ttype);
6336 if (TREE_STATIC (decl) && DECL_CLASS_SCOPE_P (decl))
6337 note_debug_info_needed (DECL_CONTEXT (decl));
6338 #endif
6340 if ((DECL_EXTERNAL (decl) || TREE_STATIC (decl))
6341 && DECL_SIZE (decl) != NULL_TREE
6342 && ! TREE_CONSTANT (DECL_SIZE (decl)))
6344 if (TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST
6345 && !DECL_LOCAL_DECL_P (decl))
6346 constant_expression_warning (DECL_SIZE (decl));
6347 else
6349 error_at (DECL_SOURCE_LOCATION (decl),
6350 "storage size of %qD isn%'t constant", decl);
6351 TREE_TYPE (decl) = error_mark_node;
6352 type = error_mark_node;
6356 /* If the final element initializes a flexible array field, add the size of
6357 that initializer to DECL's size. */
6358 if (type != error_mark_node
6359 && DECL_INITIAL (decl)
6360 && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
6361 && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl)))
6362 && DECL_SIZE (decl) != NULL_TREE
6363 && TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST
6364 && TYPE_SIZE (type) != NULL_TREE
6365 && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST
6366 && tree_int_cst_equal (DECL_SIZE (decl), TYPE_SIZE (type)))
6368 constructor_elt &elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ();
6369 if (elt.index)
6371 tree itype = TREE_TYPE (elt.index);
6372 tree vtype = TREE_TYPE (elt.value);
6373 if (TREE_CODE (itype) == ARRAY_TYPE
6374 && TYPE_DOMAIN (itype) == NULL
6375 && TREE_CODE (vtype) == ARRAY_TYPE
6376 && COMPLETE_TYPE_P (vtype))
6378 DECL_SIZE (decl)
6379 = size_binop (PLUS_EXPR, DECL_SIZE (decl), TYPE_SIZE (vtype));
6380 DECL_SIZE_UNIT (decl)
6381 = size_binop (PLUS_EXPR, DECL_SIZE_UNIT (decl),
6382 TYPE_SIZE_UNIT (vtype));
6388 /* If a local static variable is declared in an inline function, or if
6389 we have a weak definition, we must endeavor to create only one
6390 instance of the variable at link-time. */
6392 void
6393 maybe_commonize_var (tree decl)
6395 /* Don't mess with __FUNCTION__ and similar. */
6396 if (DECL_ARTIFICIAL (decl))
6397 return;
6399 /* Static data in a function with comdat linkage also has comdat
6400 linkage. */
6401 if ((TREE_STATIC (decl)
6402 && DECL_FUNCTION_SCOPE_P (decl)
6403 && vague_linkage_p (DECL_CONTEXT (decl)))
6404 || (TREE_PUBLIC (decl) && DECL_INLINE_VAR_P (decl)))
6406 if (flag_weak)
6408 /* With weak symbols, we simply make the variable COMDAT;
6409 that will cause copies in multiple translations units to
6410 be merged. */
6411 comdat_linkage (decl);
6413 else
6415 if (DECL_INITIAL (decl) == NULL_TREE
6416 || DECL_INITIAL (decl) == error_mark_node)
6418 /* Without weak symbols, we can use COMMON to merge
6419 uninitialized variables. */
6420 TREE_PUBLIC (decl) = 1;
6421 DECL_COMMON (decl) = 1;
6423 else
6425 /* While for initialized variables, we must use internal
6426 linkage -- which means that multiple copies will not
6427 be merged. */
6428 TREE_PUBLIC (decl) = 0;
6429 DECL_COMMON (decl) = 0;
6430 DECL_INTERFACE_KNOWN (decl) = 1;
6431 const char *msg;
6432 if (DECL_INLINE_VAR_P (decl))
6433 msg = G_("sorry: semantics of inline variable "
6434 "%q#D are wrong (you%'ll wind up with "
6435 "multiple copies)");
6436 else
6437 msg = G_("sorry: semantics of inline function "
6438 "static data %q#D are wrong (you%'ll wind "
6439 "up with multiple copies)");
6440 if (warning_at (DECL_SOURCE_LOCATION (decl), 0,
6441 msg, decl))
6442 inform (DECL_SOURCE_LOCATION (decl),
6443 "you can work around this by removing the initializer");
6449 /* Issue an error message if DECL is an uninitialized const variable.
6450 CONSTEXPR_CONTEXT_P is true when the function is called in a constexpr
6451 context from potential_constant_expression. Returns true if all is well,
6452 false otherwise. */
6454 bool
6455 check_for_uninitialized_const_var (tree decl, bool constexpr_context_p,
6456 tsubst_flags_t complain)
6458 tree type = strip_array_types (TREE_TYPE (decl));
6460 /* ``Unless explicitly declared extern, a const object does not have
6461 external linkage and must be initialized. ($8.4; $12.1)'' ARM
6462 7.1.6 */
6463 if (VAR_P (decl)
6464 && !TYPE_REF_P (type)
6465 && (CP_TYPE_CONST_P (type)
6466 /* C++20 permits trivial default initialization in constexpr
6467 context (P1331R2). */
6468 || (cxx_dialect < cxx20
6469 && (constexpr_context_p
6470 || var_in_constexpr_fn (decl))))
6471 && !DECL_NONTRIVIALLY_INITIALIZED_P (decl))
6473 tree field = default_init_uninitialized_part (type);
6474 if (!field)
6475 return true;
6477 bool show_notes = true;
6479 if (!constexpr_context_p || cxx_dialect >= cxx20)
6481 if (CP_TYPE_CONST_P (type))
6483 if (complain & tf_error)
6484 show_notes = permerror (DECL_SOURCE_LOCATION (decl),
6485 "uninitialized %<const %D%>", decl);
6487 else
6489 if (!is_instantiation_of_constexpr (current_function_decl)
6490 && (complain & tf_error))
6491 error_at (DECL_SOURCE_LOCATION (decl),
6492 "uninitialized variable %qD in %<constexpr%> "
6493 "function", decl);
6494 else
6495 show_notes = false;
6496 cp_function_chain->invalid_constexpr = true;
6499 else if (complain & tf_error)
6500 error_at (DECL_SOURCE_LOCATION (decl),
6501 "uninitialized variable %qD in %<constexpr%> context",
6502 decl);
6504 if (show_notes && CLASS_TYPE_P (type) && (complain & tf_error))
6506 tree defaulted_ctor;
6508 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)),
6509 "%q#T has no user-provided default constructor", type);
6510 defaulted_ctor = in_class_defaulted_default_constructor (type);
6511 if (defaulted_ctor)
6512 inform (DECL_SOURCE_LOCATION (defaulted_ctor),
6513 "constructor is not user-provided because it is "
6514 "explicitly defaulted in the class body");
6515 inform (DECL_SOURCE_LOCATION (field),
6516 "and the implicitly-defined constructor does not "
6517 "initialize %q#D", field);
6520 return false;
6523 return true;
6526 /* Structure holding the current initializer being processed by reshape_init.
6527 CUR is a pointer to the current element being processed, END is a pointer
6528 after the last element present in the initializer. */
6529 struct reshape_iter
6531 constructor_elt *cur;
6532 constructor_elt *end;
6535 static tree reshape_init_r (tree, reshape_iter *, tree, tsubst_flags_t);
6537 /* FIELD is an element of TYPE_FIELDS or NULL. In the former case, the value
6538 returned is the next FIELD_DECL (possibly FIELD itself) that can be
6539 initialized as if for an aggregate class. If there are no more such fields,
6540 the return value will be NULL. */
6542 tree
6543 next_aggregate_field (tree field)
6545 while (field
6546 && (TREE_CODE (field) != FIELD_DECL
6547 || DECL_UNNAMED_BIT_FIELD (field)
6548 || (DECL_ARTIFICIAL (field)
6549 /* In C++17, aggregates can have bases. */
6550 && !(cxx_dialect >= cxx17 && DECL_FIELD_IS_BASE (field)))))
6551 field = DECL_CHAIN (field);
6553 return field;
6556 /* FIELD is an element of TYPE_FIELDS or NULL. In the former case, the value
6557 returned is the next FIELD_DECL (possibly FIELD itself) that corresponds
6558 to a subobject. If there are no more such fields, the return value will be
6559 NULL. */
6561 tree
6562 next_subobject_field (tree field)
6564 while (field
6565 && (TREE_CODE (field) != FIELD_DECL
6566 || DECL_UNNAMED_BIT_FIELD (field)
6567 || (DECL_ARTIFICIAL (field)
6568 && !DECL_FIELD_IS_BASE (field)
6569 && !DECL_VIRTUAL_P (field))))
6570 field = DECL_CHAIN (field);
6572 return field;
6575 /* Return true for [dcl.init.list] direct-list-initialization from
6576 single element of enumeration with a fixed underlying type. */
6578 bool
6579 is_direct_enum_init (tree type, tree init)
6581 if (cxx_dialect >= cxx17
6582 && TREE_CODE (type) == ENUMERAL_TYPE
6583 && ENUM_FIXED_UNDERLYING_TYPE_P (type)
6584 && TREE_CODE (init) == CONSTRUCTOR
6585 && CONSTRUCTOR_IS_DIRECT_INIT (init)
6586 && CONSTRUCTOR_NELTS (init) == 1
6587 /* DR 2374: The single element needs to be implicitly
6588 convertible to the underlying type of the enum. */
6589 && can_convert_arg (ENUM_UNDERLYING_TYPE (type),
6590 TREE_TYPE (CONSTRUCTOR_ELT (init, 0)->value),
6591 CONSTRUCTOR_ELT (init, 0)->value,
6592 LOOKUP_IMPLICIT, tf_none))
6593 return true;
6594 return false;
6597 /* Subroutine of reshape_init_array and reshape_init_vector, which does
6598 the actual work. ELT_TYPE is the element type of the array. MAX_INDEX is an
6599 INTEGER_CST representing the size of the array minus one (the maximum index),
6600 or NULL_TREE if the array was declared without specifying the size. D is
6601 the iterator within the constructor. */
6603 static tree
6604 reshape_init_array_1 (tree elt_type, tree max_index, reshape_iter *d,
6605 tree first_initializer_p, tsubst_flags_t complain)
6607 tree new_init;
6608 bool sized_array_p = (max_index && TREE_CONSTANT (max_index));
6609 unsigned HOST_WIDE_INT max_index_cst = 0;
6610 unsigned HOST_WIDE_INT index;
6612 /* The initializer for an array is always a CONSTRUCTOR. If this is the
6613 outermost CONSTRUCTOR and the element type is non-aggregate, we don't need
6614 to build a new one. But don't reuse if not complaining; if this is
6615 tentative, we might also reshape to another type (95319). */
6616 bool reuse = (first_initializer_p
6617 && (complain & tf_error)
6618 && !CP_AGGREGATE_TYPE_P (elt_type)
6619 && !TREE_SIDE_EFFECTS (first_initializer_p));
6620 if (reuse)
6621 new_init = first_initializer_p;
6622 else
6623 new_init = build_constructor (init_list_type_node, NULL);
6625 if (sized_array_p)
6627 /* Minus 1 is used for zero sized arrays. */
6628 if (integer_all_onesp (max_index))
6629 return new_init;
6631 if (tree_fits_uhwi_p (max_index))
6632 max_index_cst = tree_to_uhwi (max_index);
6633 /* sizetype is sign extended, not zero extended. */
6634 else
6635 max_index_cst = tree_to_uhwi (fold_convert (size_type_node, max_index));
6638 /* Loop until there are no more initializers. */
6639 for (index = 0;
6640 d->cur != d->end && (!sized_array_p || index <= max_index_cst);
6641 ++index)
6643 tree elt_init;
6644 constructor_elt *old_cur = d->cur;
6646 if (d->cur->index)
6647 CONSTRUCTOR_IS_DESIGNATED_INIT (new_init) = true;
6648 check_array_designated_initializer (d->cur, index);
6649 elt_init = reshape_init_r (elt_type, d,
6650 /*first_initializer_p=*/NULL_TREE,
6651 complain);
6652 if (elt_init == error_mark_node)
6653 return error_mark_node;
6654 tree idx = size_int (index);
6655 if (reuse)
6657 old_cur->index = idx;
6658 old_cur->value = elt_init;
6660 else
6661 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
6662 idx, elt_init);
6663 if (!TREE_CONSTANT (elt_init))
6664 TREE_CONSTANT (new_init) = false;
6666 /* This can happen with an invalid initializer (c++/54501). */
6667 if (d->cur == old_cur && !sized_array_p)
6668 break;
6671 return new_init;
6674 /* Subroutine of reshape_init_r, processes the initializers for arrays.
6675 Parameters are the same of reshape_init_r. */
6677 static tree
6678 reshape_init_array (tree type, reshape_iter *d, tree first_initializer_p,
6679 tsubst_flags_t complain)
6681 tree max_index = NULL_TREE;
6683 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
6685 if (TYPE_DOMAIN (type))
6686 max_index = array_type_nelts (type);
6688 return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6689 first_initializer_p, complain);
6692 /* Subroutine of reshape_init_r, processes the initializers for vectors.
6693 Parameters are the same of reshape_init_r. */
6695 static tree
6696 reshape_init_vector (tree type, reshape_iter *d, tsubst_flags_t complain)
6698 tree max_index = NULL_TREE;
6700 gcc_assert (VECTOR_TYPE_P (type));
6702 if (COMPOUND_LITERAL_P (d->cur->value))
6704 tree value = d->cur->value;
6705 if (!same_type_p (TREE_TYPE (value), type))
6707 if (complain & tf_error)
6708 error ("invalid type %qT as initializer for a vector of type %qT",
6709 TREE_TYPE (d->cur->value), type);
6710 value = error_mark_node;
6712 ++d->cur;
6713 return value;
6716 /* For a vector, we initialize it as an array of the appropriate size. */
6717 if (VECTOR_TYPE_P (type))
6718 max_index = size_int (TYPE_VECTOR_SUBPARTS (type) - 1);
6720 return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6721 NULL_TREE, complain);
6724 /* Subroutine of reshape_init*: We're initializing an element with TYPE from
6725 INIT, in isolation from any designator or other initializers. */
6727 static tree
6728 reshape_single_init (tree type, tree init, tsubst_flags_t complain)
6730 /* We could also implement this by wrapping init in a new CONSTRUCTOR and
6731 calling reshape_init, but this way can just live on the stack. */
6732 constructor_elt elt = { /*index=*/NULL_TREE, init };
6733 reshape_iter iter = { &elt, &elt + 1 };
6734 return reshape_init_r (type, &iter,
6735 /*first_initializer_p=*/NULL_TREE,
6736 complain);
6739 /* Subroutine of reshape_init_r, processes the initializers for classes
6740 or union. Parameters are the same of reshape_init_r. */
6742 static tree
6743 reshape_init_class (tree type, reshape_iter *d, bool first_initializer_p,
6744 tsubst_flags_t complain)
6746 tree field;
6747 tree new_init;
6749 gcc_assert (CLASS_TYPE_P (type));
6751 /* The initializer for a class is always a CONSTRUCTOR. */
6752 new_init = build_constructor (init_list_type_node, NULL);
6754 int binfo_idx = -1;
6755 tree binfo = TYPE_BINFO (type);
6756 tree base_binfo = NULL_TREE;
6757 if (cxx_dialect >= cxx17 && uses_template_parms (type))
6759 /* We get here from maybe_aggr_guide for C++20 class template argument
6760 deduction. In this case we need to look through the binfo because a
6761 template doesn't have base fields. */
6762 binfo_idx = 0;
6763 BINFO_BASE_ITERATE (binfo, binfo_idx, base_binfo);
6765 if (base_binfo)
6766 field = base_binfo;
6767 else
6768 field = next_aggregate_field (TYPE_FIELDS (type));
6770 if (!field)
6772 /* [dcl.init.aggr]
6774 An initializer for an aggregate member that is an
6775 empty class shall have the form of an empty
6776 initializer-list {}. */
6777 if (!first_initializer_p)
6779 if (complain & tf_error)
6780 error ("initializer for %qT must be brace-enclosed", type);
6781 return error_mark_node;
6783 return new_init;
6786 /* For C++20 CTAD, handle pack expansions in the base list. */
6787 tree last_was_pack_expansion = NULL_TREE;
6789 /* Loop through the initializable fields, gathering initializers. */
6790 while (d->cur != d->end)
6792 tree field_init;
6793 constructor_elt *old_cur = d->cur;
6794 bool direct_desig = false;
6796 /* Handle C++20 designated initializers. */
6797 if (d->cur->index)
6799 if (d->cur->index == error_mark_node)
6800 return error_mark_node;
6802 if (TREE_CODE (d->cur->index) == FIELD_DECL)
6804 /* We already reshaped this; we should have returned early from
6805 reshape_init. */
6806 gcc_checking_assert (false);
6807 if (field != d->cur->index)
6809 if (tree id = DECL_NAME (d->cur->index))
6810 gcc_checking_assert (d->cur->index
6811 == get_class_binding (type, id));
6812 field = d->cur->index;
6815 else if (TREE_CODE (d->cur->index) == IDENTIFIER_NODE)
6817 CONSTRUCTOR_IS_DESIGNATED_INIT (new_init) = true;
6818 field = get_class_binding (type, d->cur->index);
6819 direct_desig = true;
6821 else
6823 if (complain & tf_error)
6824 error ("%<[%E] =%> used in a GNU-style designated initializer"
6825 " for class %qT", d->cur->index, type);
6826 return error_mark_node;
6829 if (!field && ANON_AGGR_TYPE_P (type))
6830 /* Apparently the designator isn't for a member of this anonymous
6831 struct, so head back to the enclosing class. */
6832 break;
6834 if (!field || TREE_CODE (field) != FIELD_DECL)
6836 if (complain & tf_error)
6837 error ("%qT has no non-static data member named %qD", type,
6838 d->cur->index);
6839 return error_mark_node;
6842 /* If the element is an anonymous union object and the initializer
6843 list is a designated-initializer-list, the anonymous union object
6844 is initialized by the designated-initializer-list { D }, where D
6845 is the designated-initializer-clause naming a member of the
6846 anonymous union object. */
6847 tree ictx = DECL_CONTEXT (field);
6848 if (!same_type_ignoring_top_level_qualifiers_p (ictx, type))
6850 /* Find the anon aggr that is a direct member of TYPE. */
6851 while (ANON_AGGR_TYPE_P (ictx))
6853 tree cctx = TYPE_CONTEXT (ictx);
6854 if (same_type_ignoring_top_level_qualifiers_p (cctx, type))
6855 goto found;
6856 ictx = cctx;
6859 /* Not found, e.g. FIELD is a member of a base class. */
6860 if (complain & tf_error)
6861 error ("%qD is not a direct member of %qT", field, type);
6862 return error_mark_node;
6864 found:
6865 /* Now find the TYPE member with that anon aggr type. */
6866 tree aafield = TYPE_FIELDS (type);
6867 for (; aafield; aafield = TREE_CHAIN (aafield))
6868 if (TREE_TYPE (aafield) == ictx)
6869 break;
6870 gcc_assert (aafield);
6871 field = aafield;
6872 direct_desig = false;
6876 /* If we processed all the member of the class, we are done. */
6877 if (!field)
6878 break;
6880 last_was_pack_expansion = (PACK_EXPANSION_P (TREE_TYPE (field))
6881 ? field : NULL_TREE);
6882 if (last_was_pack_expansion)
6883 /* Each non-trailing aggregate element that is a pack expansion is
6884 assumed to correspond to no elements of the initializer list. */
6885 goto continue_;
6887 if (direct_desig)
6889 /* The designated field F is initialized from this one element.
6891 Note that we don't want to do this if we found the designator
6892 inside an anon aggr above; we use the normal code to implement:
6894 "If the element is an anonymous union member and the initializer
6895 list is a brace-enclosed designated- initializer-list, the element
6896 is initialized by the designated-initializer-list { D }, where D
6897 is the designated- initializer-clause naming a member of the
6898 anonymous union member." */
6899 field_init = reshape_single_init (TREE_TYPE (field),
6900 d->cur->value, complain);
6901 d->cur++;
6903 else
6904 field_init = reshape_init_r (TREE_TYPE (field), d,
6905 /*first_initializer_p=*/NULL_TREE,
6906 complain);
6908 if (field_init == error_mark_node)
6909 return error_mark_node;
6911 if (d->cur == old_cur && d->cur->index)
6913 /* This can happen with an invalid initializer for a flexible
6914 array member (c++/54441). */
6915 if (complain & tf_error)
6916 error ("invalid initializer for %q#D", field);
6917 return error_mark_node;
6920 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init), field, field_init);
6922 /* [dcl.init.aggr]
6924 When a union is initialized with a brace-enclosed
6925 initializer, the braces shall only contain an
6926 initializer for the first member of the union. */
6927 if (TREE_CODE (type) == UNION_TYPE)
6928 break;
6930 continue_:
6931 if (base_binfo)
6933 if (BINFO_BASE_ITERATE (binfo, ++binfo_idx, base_binfo))
6934 field = base_binfo;
6935 else
6936 field = next_aggregate_field (TYPE_FIELDS (type));
6938 else
6939 field = next_aggregate_field (DECL_CHAIN (field));
6942 /* A trailing aggregate element that is a pack expansion is assumed to
6943 correspond to all remaining elements of the initializer list (if any). */
6944 if (last_was_pack_expansion)
6946 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
6947 last_was_pack_expansion, d->cur->value);
6948 while (d->cur != d->end)
6949 d->cur++;
6952 return new_init;
6955 /* Subroutine of reshape_init_r. We're in a context where C99 initializer
6956 designators are not valid; either complain or return true to indicate
6957 that reshape_init_r should return error_mark_node. */
6959 static bool
6960 has_designator_problem (reshape_iter *d, tsubst_flags_t complain)
6962 if (d->cur->index)
6964 if (complain & tf_error)
6965 error_at (cp_expr_loc_or_input_loc (d->cur->index),
6966 "C99 designator %qE outside aggregate initializer",
6967 d->cur->index);
6968 else
6969 return true;
6971 return false;
6974 /* Subroutine of reshape_init, which processes a single initializer (part of
6975 a CONSTRUCTOR). TYPE is the type of the variable being initialized, D is the
6976 iterator within the CONSTRUCTOR which points to the initializer to process.
6977 If this is the first initializer of the outermost CONSTRUCTOR node,
6978 FIRST_INITIALIZER_P is that CONSTRUCTOR; otherwise, it is NULL_TREE. */
6980 static tree
6981 reshape_init_r (tree type, reshape_iter *d, tree first_initializer_p,
6982 tsubst_flags_t complain)
6984 tree init = d->cur->value;
6986 if (error_operand_p (init))
6987 return error_mark_node;
6989 if (first_initializer_p && !CP_AGGREGATE_TYPE_P (type)
6990 && has_designator_problem (d, complain))
6991 return error_mark_node;
6993 tree stripped_init = tree_strip_any_location_wrapper (init);
6995 if (TREE_CODE (type) == COMPLEX_TYPE)
6997 /* A complex type can be initialized from one or two initializers,
6998 but braces are not elided. */
6999 d->cur++;
7000 if (BRACE_ENCLOSED_INITIALIZER_P (stripped_init))
7002 if (CONSTRUCTOR_NELTS (stripped_init) > 2)
7004 if (complain & tf_error)
7005 error ("too many initializers for %qT", type);
7006 else
7007 return error_mark_node;
7010 else if (first_initializer_p && d->cur != d->end)
7012 vec<constructor_elt, va_gc> *v = 0;
7013 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
7014 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, d->cur->value);
7015 if (has_designator_problem (d, complain))
7016 return error_mark_node;
7017 d->cur++;
7018 init = build_constructor (init_list_type_node, v);
7020 return init;
7023 /* A non-aggregate type is always initialized with a single
7024 initializer. */
7025 if (!CP_AGGREGATE_TYPE_P (type)
7026 /* As is an array with dependent bound, which we can see
7027 during C++20 aggregate CTAD. */
7028 || (cxx_dialect >= cxx20
7029 && TREE_CODE (type) == ARRAY_TYPE
7030 && uses_template_parms (TYPE_DOMAIN (type))))
7032 /* It is invalid to initialize a non-aggregate type with a
7033 brace-enclosed initializer before C++0x.
7034 We need to check for BRACE_ENCLOSED_INITIALIZER_P here because
7035 of g++.old-deja/g++.mike/p7626.C: a pointer-to-member constant is
7036 a CONSTRUCTOR (with a record type). */
7037 if (TREE_CODE (stripped_init) == CONSTRUCTOR
7038 /* Don't complain about a capture-init. */
7039 && !CONSTRUCTOR_IS_DIRECT_INIT (stripped_init)
7040 && BRACE_ENCLOSED_INITIALIZER_P (stripped_init)) /* p7626.C */
7042 if (SCALAR_TYPE_P (type))
7044 if (cxx_dialect < cxx11)
7046 if (complain & tf_error)
7047 error ("braces around scalar initializer for type %qT",
7048 type);
7049 init = error_mark_node;
7051 else if (first_initializer_p
7052 || (CONSTRUCTOR_NELTS (stripped_init) > 0
7053 && (BRACE_ENCLOSED_INITIALIZER_P
7054 (CONSTRUCTOR_ELT (stripped_init,0)->value))))
7056 if (complain & tf_error)
7057 error ("too many braces around scalar initializer "
7058 "for type %qT", type);
7059 init = error_mark_node;
7062 else
7063 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
7066 d->cur++;
7067 return init;
7070 /* "If T is a class type and the initializer list has a single element of
7071 type cv U, where U is T or a class derived from T, the object is
7072 initialized from that element." Even if T is an aggregate. */
7073 if (cxx_dialect >= cxx11 && (CLASS_TYPE_P (type) || VECTOR_TYPE_P (type))
7074 && first_initializer_p
7075 /* But not if it's a designated init. */
7076 && !d->cur->index
7077 && d->end - d->cur == 1
7078 && reference_related_p (type, TREE_TYPE (init)))
7080 d->cur++;
7081 return init;
7084 /* [dcl.init.aggr]
7086 All implicit type conversions (clause _conv_) are considered when
7087 initializing the aggregate member with an initializer from an
7088 initializer-list. If the initializer can initialize a member,
7089 the member is initialized. Otherwise, if the member is itself a
7090 non-empty subaggregate, brace elision is assumed and the
7091 initializer is considered for the initialization of the first
7092 member of the subaggregate. */
7093 if ((TREE_CODE (init) != CONSTRUCTOR || COMPOUND_LITERAL_P (init))
7094 /* But don't try this for the first initializer, since that would be
7095 looking through the outermost braces; A a2 = { a1 }; is not a
7096 valid aggregate initialization. */
7097 && !first_initializer_p
7098 && (same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (init))
7099 || can_convert_arg (type, TREE_TYPE (init), init, LOOKUP_NORMAL,
7100 complain)))
7102 d->cur++;
7103 return init;
7106 /* [dcl.init.string]
7108 A char array (whether plain char, signed char, or unsigned char)
7109 can be initialized by a string-literal (optionally enclosed in
7110 braces); a wchar_t array can be initialized by a wide
7111 string-literal (optionally enclosed in braces). */
7112 if (TREE_CODE (type) == ARRAY_TYPE
7113 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type))))
7115 tree str_init = init;
7116 tree stripped_str_init = stripped_init;
7117 reshape_iter stripd = {};
7119 /* Strip one level of braces if and only if they enclose a single
7120 element (as allowed by [dcl.init.string]). */
7121 if (!first_initializer_p
7122 && TREE_CODE (stripped_str_init) == CONSTRUCTOR
7123 && CONSTRUCTOR_NELTS (stripped_str_init) == 1)
7125 stripd.cur = CONSTRUCTOR_ELT (stripped_str_init, 0);
7126 str_init = stripd.cur->value;
7127 stripped_str_init = tree_strip_any_location_wrapper (str_init);
7130 /* If it's a string literal, then it's the initializer for the array
7131 as a whole. Otherwise, continue with normal initialization for
7132 array types (one value per array element). */
7133 if (TREE_CODE (stripped_str_init) == STRING_CST)
7135 if ((first_initializer_p && has_designator_problem (d, complain))
7136 || (stripd.cur && has_designator_problem (&stripd, complain)))
7137 return error_mark_node;
7138 d->cur++;
7139 return str_init;
7143 /* The following cases are about aggregates. If we are not within a full
7144 initializer already, and there is not a CONSTRUCTOR, it means that there
7145 is a missing set of braces (that is, we are processing the case for
7146 which reshape_init exists). */
7147 bool braces_elided_p = false;
7148 if (!first_initializer_p)
7150 if (TREE_CODE (stripped_init) == CONSTRUCTOR)
7152 tree init_type = TREE_TYPE (init);
7153 if (init_type && TYPE_PTRMEMFUNC_P (init_type))
7154 /* There is no need to call reshape_init for pointer-to-member
7155 function initializers, as they are always constructed correctly
7156 by the front end. Here we have e.g. {.__pfn=0B, .__delta=0},
7157 which is missing outermost braces. We should warn below, and
7158 one of the routines below will wrap it in additional { }. */;
7159 /* For a nested compound literal, proceed to specialized routines,
7160 to handle initialization of arrays and similar. */
7161 else if (COMPOUND_LITERAL_P (stripped_init))
7162 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
7163 /* If we have an unresolved designator, we need to find the member it
7164 designates within TYPE, so proceed to the routines below. For
7165 FIELD_DECL or INTEGER_CST designators, we're already initializing
7166 the designated element. */
7167 else if (d->cur->index
7168 && TREE_CODE (d->cur->index) == IDENTIFIER_NODE)
7169 /* Brace elision with designators is only permitted for anonymous
7170 aggregates. */
7171 gcc_checking_assert (ANON_AGGR_TYPE_P (type));
7172 /* A CONSTRUCTOR of the target's type is a previously
7173 digested initializer. */
7174 else if (same_type_ignoring_top_level_qualifiers_p (type, init_type))
7176 ++d->cur;
7177 return init;
7179 else
7181 /* Something that hasn't been reshaped yet. */
7182 ++d->cur;
7183 gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
7184 return reshape_init (type, init, complain);
7188 if (complain & tf_warning)
7189 warning (OPT_Wmissing_braces,
7190 "missing braces around initializer for %qT",
7191 type);
7192 braces_elided_p = true;
7195 /* Dispatch to specialized routines. */
7196 tree new_init;
7197 if (CLASS_TYPE_P (type))
7198 new_init = reshape_init_class (type, d, first_initializer_p, complain);
7199 else if (TREE_CODE (type) == ARRAY_TYPE)
7200 new_init = reshape_init_array (type, d, first_initializer_p, complain);
7201 else if (VECTOR_TYPE_P (type))
7202 new_init = reshape_init_vector (type, d, complain);
7203 else
7204 gcc_unreachable();
7206 if (braces_elided_p
7207 && TREE_CODE (new_init) == CONSTRUCTOR)
7208 CONSTRUCTOR_BRACES_ELIDED_P (new_init) = true;
7210 return new_init;
7213 /* Undo the brace-elision allowed by [dcl.init.aggr] in a
7214 brace-enclosed aggregate initializer.
7216 INIT is the CONSTRUCTOR containing the list of initializers describing
7217 a brace-enclosed initializer for an entity of the indicated aggregate TYPE.
7218 It may not presently match the shape of the TYPE; for example:
7220 struct S { int a; int b; };
7221 struct S a[] = { 1, 2, 3, 4 };
7223 Here INIT will hold a vector of four elements, rather than a
7224 vector of two elements, each itself a vector of two elements. This
7225 routine transforms INIT from the former form into the latter. The
7226 revised CONSTRUCTOR node is returned. */
7228 tree
7229 reshape_init (tree type, tree init, tsubst_flags_t complain)
7231 vec<constructor_elt, va_gc> *v;
7232 reshape_iter d;
7233 tree new_init;
7235 gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (init));
7237 v = CONSTRUCTOR_ELTS (init);
7239 /* An empty constructor does not need reshaping, and it is always a valid
7240 initializer. */
7241 if (vec_safe_is_empty (v))
7242 return init;
7244 if ((*v)[0].index && TREE_CODE ((*v)[0].index) == FIELD_DECL)
7245 /* Already reshaped. */
7246 return init;
7248 /* Brace elision is not performed for a CONSTRUCTOR representing
7249 parenthesized aggregate initialization. */
7250 if (CONSTRUCTOR_IS_PAREN_INIT (init))
7252 tree elt = (*v)[0].value;
7253 /* If we're initializing a char array from a string-literal that is
7254 enclosed in braces, unwrap it here. */
7255 if (TREE_CODE (type) == ARRAY_TYPE
7256 && vec_safe_length (v) == 1
7257 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
7258 && TREE_CODE (tree_strip_any_location_wrapper (elt)) == STRING_CST)
7259 return elt;
7260 return init;
7263 /* Handle [dcl.init.list] direct-list-initialization from
7264 single element of enumeration with a fixed underlying type. */
7265 if (is_direct_enum_init (type, init))
7267 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
7268 type = cv_unqualified (type);
7269 if (check_narrowing (ENUM_UNDERLYING_TYPE (type), elt, complain))
7271 warning_sentinel w (warn_useless_cast);
7272 warning_sentinel w2 (warn_ignored_qualifiers);
7273 return cp_build_c_cast (input_location, type, elt,
7274 tf_warning_or_error);
7276 else
7277 return error_mark_node;
7280 /* Recurse on this CONSTRUCTOR. */
7281 d.cur = &(*v)[0];
7282 d.end = d.cur + v->length ();
7284 new_init = reshape_init_r (type, &d, init, complain);
7285 if (new_init == error_mark_node)
7286 return error_mark_node;
7288 /* Make sure all the element of the constructor were used. Otherwise,
7289 issue an error about exceeding initializers. */
7290 if (d.cur != d.end)
7292 if (complain & tf_error)
7293 error ("too many initializers for %qT", type);
7294 return error_mark_node;
7297 if (CONSTRUCTOR_IS_DIRECT_INIT (init)
7298 && BRACE_ENCLOSED_INITIALIZER_P (new_init))
7299 CONSTRUCTOR_IS_DIRECT_INIT (new_init) = true;
7300 if (CONSTRUCTOR_IS_DESIGNATED_INIT (init)
7301 && BRACE_ENCLOSED_INITIALIZER_P (new_init))
7302 gcc_checking_assert (CONSTRUCTOR_IS_DESIGNATED_INIT (new_init)
7303 || seen_error ());
7305 return new_init;
7308 /* Verify array initializer. Returns true if errors have been reported. */
7310 bool
7311 check_array_initializer (tree decl, tree type, tree init)
7313 tree element_type = TREE_TYPE (type);
7315 /* Structured binding when initialized with an array type needs
7316 to have complete type. */
7317 if (decl
7318 && DECL_DECOMPOSITION_P (decl)
7319 && !DECL_DECOMP_BASE (decl)
7320 && !COMPLETE_TYPE_P (type))
7322 error_at (DECL_SOURCE_LOCATION (decl),
7323 "structured binding has incomplete type %qT", type);
7324 TREE_TYPE (decl) = error_mark_node;
7325 return true;
7328 /* The array type itself need not be complete, because the
7329 initializer may tell us how many elements are in the array.
7330 But, the elements of the array must be complete. */
7331 if (!COMPLETE_TYPE_P (complete_type (element_type)))
7333 if (decl)
7334 error_at (DECL_SOURCE_LOCATION (decl),
7335 "elements of array %q#D have incomplete type", decl);
7336 else
7337 error ("elements of array %q#T have incomplete type", type);
7338 return true;
7341 location_t loc = (decl ? location_of (decl) : input_location);
7342 if (!verify_type_context (loc, TCTX_ARRAY_ELEMENT, element_type))
7343 return true;
7345 /* A compound literal can't have variable size. */
7346 if (init && !decl
7347 && ((COMPLETE_TYPE_P (type) && !TREE_CONSTANT (TYPE_SIZE (type)))
7348 || !TREE_CONSTANT (TYPE_SIZE (element_type))))
7350 error ("variable-sized compound literal");
7351 return true;
7353 return false;
7356 /* Subroutine of check_initializer; args are passed down from that function.
7357 Set stmts_are_full_exprs_p to 1 across a call to build_aggr_init. */
7359 static tree
7360 build_aggr_init_full_exprs (tree decl, tree init, int flags)
7362 gcc_assert (stmts_are_full_exprs_p ());
7363 if (init)
7364 maybe_warn_pessimizing_move (init, TREE_TYPE (decl), /*return_p*/false);
7365 return build_aggr_init (decl, init, flags, tf_warning_or_error);
7368 /* Verify INIT (the initializer for DECL), and record the
7369 initialization in DECL_INITIAL, if appropriate. CLEANUP is as for
7370 grok_reference_init.
7372 If the return value is non-NULL, it is an expression that must be
7373 evaluated dynamically to initialize DECL. */
7375 static tree
7376 check_initializer (tree decl, tree init, int flags, vec<tree, va_gc> **cleanups)
7378 tree type;
7379 tree init_code = NULL;
7380 tree core_type;
7382 /* Things that are going to be initialized need to have complete
7383 type. */
7384 TREE_TYPE (decl) = type = complete_type (TREE_TYPE (decl));
7386 if (DECL_HAS_VALUE_EXPR_P (decl))
7388 /* A variable with DECL_HAS_VALUE_EXPR_P set is just a placeholder,
7389 it doesn't have storage to be initialized. */
7390 gcc_assert (init == NULL_TREE);
7391 return NULL_TREE;
7394 if (type == error_mark_node)
7395 /* We will have already complained. */
7396 return NULL_TREE;
7398 if (TREE_CODE (type) == ARRAY_TYPE)
7400 if (check_array_initializer (decl, type, init))
7401 return NULL_TREE;
7403 else if (!COMPLETE_TYPE_P (type))
7405 error_at (DECL_SOURCE_LOCATION (decl),
7406 "%q#D has incomplete type", decl);
7407 TREE_TYPE (decl) = error_mark_node;
7408 return NULL_TREE;
7410 else
7411 /* There is no way to make a variable-sized class type in GNU C++. */
7412 gcc_assert (TREE_CONSTANT (TYPE_SIZE (type)));
7414 if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
7416 int init_len = CONSTRUCTOR_NELTS (init);
7417 if (SCALAR_TYPE_P (type))
7419 if (init_len == 0)
7421 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
7422 init = build_zero_init (type, NULL_TREE, false);
7424 else if (init_len != 1 && TREE_CODE (type) != COMPLEX_TYPE)
7426 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
7427 "scalar object %qD requires one element in "
7428 "initializer", decl);
7429 TREE_TYPE (decl) = error_mark_node;
7430 return NULL_TREE;
7435 if (TREE_CODE (decl) == CONST_DECL)
7437 gcc_assert (!TYPE_REF_P (type));
7439 DECL_INITIAL (decl) = init;
7441 gcc_assert (init != NULL_TREE);
7442 init = NULL_TREE;
7444 else if (!init && DECL_REALLY_EXTERN (decl))
7446 else if (init || type_build_ctor_call (type)
7447 || TYPE_REF_P (type))
7449 if (TYPE_REF_P (type))
7451 init = grok_reference_init (decl, type, init, flags);
7452 flags |= LOOKUP_ALREADY_DIGESTED;
7454 else if (!init)
7455 check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
7456 tf_warning_or_error);
7457 /* Do not reshape constructors of vectors (they don't need to be
7458 reshaped. */
7459 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
7461 if (is_std_init_list (type))
7463 init = perform_implicit_conversion (type, init,
7464 tf_warning_or_error);
7465 flags |= LOOKUP_ALREADY_DIGESTED;
7467 else if (TYPE_NON_AGGREGATE_CLASS (type))
7469 /* Don't reshape if the class has constructors. */
7470 if (cxx_dialect == cxx98)
7471 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
7472 "in C++98 %qD must be initialized by "
7473 "constructor, not by %<{...}%>",
7474 decl);
7476 else if (VECTOR_TYPE_P (type) && TYPE_VECTOR_OPAQUE (type))
7478 error ("opaque vector types cannot be initialized");
7479 init = error_mark_node;
7481 else
7483 init = reshape_init (type, init, tf_warning_or_error);
7484 flags |= LOOKUP_NO_NARROWING;
7487 /* [dcl.init] "Otherwise, if the destination type is an array, the object
7488 is initialized as follows..." So handle things like
7490 int a[](1, 2, 3);
7492 which is permitted in C++20 by P0960. */
7493 else if (TREE_CODE (init) == TREE_LIST
7494 && TREE_TYPE (init) == NULL_TREE
7495 && TREE_CODE (type) == ARRAY_TYPE
7496 && !DECL_DECOMPOSITION_P (decl)
7497 && (cxx_dialect >= cxx20))
7498 init = do_aggregate_paren_init (init, type);
7499 else if (TREE_CODE (init) == TREE_LIST
7500 && TREE_TYPE (init) != unknown_type_node
7501 && !MAYBE_CLASS_TYPE_P (type))
7503 gcc_assert (TREE_CODE (decl) != RESULT_DECL);
7505 /* We get here with code like `int a (2);' */
7506 init = build_x_compound_expr_from_list (init, ELK_INIT,
7507 tf_warning_or_error);
7510 /* If DECL has an array type without a specific bound, deduce the
7511 array size from the initializer. */
7512 maybe_deduce_size_from_array_init (decl, init);
7513 type = TREE_TYPE (decl);
7514 if (type == error_mark_node)
7515 return NULL_TREE;
7517 if (((type_build_ctor_call (type) || CLASS_TYPE_P (type))
7518 && !(flags & LOOKUP_ALREADY_DIGESTED)
7519 && !(init && BRACE_ENCLOSED_INITIALIZER_P (init)
7520 && CP_AGGREGATE_TYPE_P (type)
7521 && (CLASS_TYPE_P (type)
7522 /* The call to build_aggr_init below could end up
7523 calling build_vec_init, which may break when we
7524 are processing a template. */
7525 || processing_template_decl
7526 || !TYPE_NEEDS_CONSTRUCTING (type)
7527 || type_has_extended_temps (type))))
7528 || (DECL_DECOMPOSITION_P (decl) && TREE_CODE (type) == ARRAY_TYPE))
7530 init_code = build_aggr_init_full_exprs (decl, init, flags);
7532 /* A constructor call is a non-trivial initializer even if
7533 it isn't explicitly written. */
7534 if (TREE_SIDE_EFFECTS (init_code))
7535 DECL_NONTRIVIALLY_INITIALIZED_P (decl) = true;
7537 /* If this is a constexpr initializer, expand_default_init will
7538 have returned an INIT_EXPR rather than a CALL_EXPR. In that
7539 case, pull the initializer back out and pass it down into
7540 store_init_value. */
7541 while (true)
7543 if (TREE_CODE (init_code) == EXPR_STMT
7544 || TREE_CODE (init_code) == STMT_EXPR
7545 || TREE_CODE (init_code) == CONVERT_EXPR)
7546 init_code = TREE_OPERAND (init_code, 0);
7547 else if (TREE_CODE (init_code) == BIND_EXPR)
7548 init_code = BIND_EXPR_BODY (init_code);
7549 else
7550 break;
7552 if (TREE_CODE (init_code) == INIT_EXPR)
7554 /* In C++20, the call to build_aggr_init could have created
7555 an INIT_EXPR with a CONSTRUCTOR as the RHS to handle
7556 A(1, 2). */
7557 tree rhs = TREE_OPERAND (init_code, 1);
7558 if (processing_template_decl && TREE_CODE (rhs) == TARGET_EXPR)
7559 /* Avoid leaking TARGET_EXPR into template trees. */
7560 rhs = build_implicit_conv_flags (type, init, flags);
7561 init = rhs;
7563 init_code = NULL_TREE;
7564 /* Don't call digest_init; it's unnecessary and will complain
7565 about aggregate initialization of non-aggregate classes. */
7566 flags |= LOOKUP_ALREADY_DIGESTED;
7568 else if (DECL_DECLARED_CONSTEXPR_P (decl)
7569 || DECL_DECLARED_CONSTINIT_P (decl))
7571 /* Declared constexpr or constinit, but no suitable initializer;
7572 massage init appropriately so we can pass it into
7573 store_init_value for the error. */
7574 tree new_init = NULL_TREE;
7575 if (!processing_template_decl
7576 && TREE_CODE (init_code) == CALL_EXPR)
7577 new_init = build_cplus_new (type, init_code, tf_none);
7578 else if (CLASS_TYPE_P (type)
7579 && (!init || TREE_CODE (init) == TREE_LIST))
7580 new_init = build_functional_cast (input_location, type,
7581 init, tf_none);
7582 if (new_init)
7584 init = new_init;
7585 if (TREE_CODE (init) == TARGET_EXPR
7586 && !(flags & LOOKUP_ONLYCONVERTING))
7587 TARGET_EXPR_DIRECT_INIT_P (init) = true;
7589 init_code = NULL_TREE;
7591 else
7592 init = NULL_TREE;
7595 if (init && TREE_CODE (init) != TREE_VEC)
7597 init_code = store_init_value (decl, init, cleanups, flags);
7599 if (DECL_INITIAL (decl)
7600 && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
7601 && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl))))
7603 tree elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ().value;
7604 if (TREE_CODE (TREE_TYPE (elt)) == ARRAY_TYPE
7605 && TYPE_SIZE (TREE_TYPE (elt)) == NULL_TREE)
7606 cp_complete_array_type (&TREE_TYPE (elt), elt, false);
7609 if (pedantic && TREE_CODE (type) == ARRAY_TYPE
7610 && DECL_INITIAL (decl)
7611 && TREE_CODE (DECL_INITIAL (decl)) == STRING_CST
7612 && PAREN_STRING_LITERAL_P (DECL_INITIAL (decl)))
7613 warning_at (cp_expr_loc_or_loc (DECL_INITIAL (decl),
7614 DECL_SOURCE_LOCATION (decl)),
7615 0, "array %qD initialized by parenthesized "
7616 "string literal %qE",
7617 decl, DECL_INITIAL (decl));
7618 init = NULL_TREE;
7621 else
7623 if (CLASS_TYPE_P (core_type = strip_array_types (type))
7624 && (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type)
7625 || CLASSTYPE_REF_FIELDS_NEED_INIT (core_type)))
7626 diagnose_uninitialized_cst_or_ref_member (core_type, /*using_new=*/false,
7627 /*complain=*/true);
7629 check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
7630 tf_warning_or_error);
7633 if (init && init != error_mark_node)
7634 init_code = cp_build_init_expr (decl, init);
7636 if (init_code && !TREE_SIDE_EFFECTS (init_code)
7637 && init_code != error_mark_node)
7638 init_code = NULL_TREE;
7640 if (init_code)
7642 /* We might have set these in cp_finish_decl. */
7643 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = false;
7644 TREE_CONSTANT (decl) = false;
7647 if (init_code
7648 && DECL_IN_AGGR_P (decl)
7649 && DECL_INITIALIZED_IN_CLASS_P (decl))
7651 static int explained = 0;
7653 if (cxx_dialect < cxx11)
7654 error ("initializer invalid for static member with constructor");
7655 else if (cxx_dialect < cxx17)
7656 error ("non-constant in-class initialization invalid for static "
7657 "member %qD", decl);
7658 else
7659 error ("non-constant in-class initialization invalid for non-inline "
7660 "static member %qD", decl);
7661 if (!explained)
7663 inform (input_location,
7664 "(an out of class initialization is required)");
7665 explained = 1;
7667 return NULL_TREE;
7670 return init_code;
7673 /* If DECL is not a local variable, give it RTL. */
7675 static void
7676 make_rtl_for_nonlocal_decl (tree decl, tree init, const char* asmspec)
7678 int toplev = toplevel_bindings_p ();
7679 int defer_p;
7681 /* Set the DECL_ASSEMBLER_NAME for the object. */
7682 if (asmspec)
7684 /* The `register' keyword, when used together with an
7685 asm-specification, indicates that the variable should be
7686 placed in a particular register. */
7687 if (VAR_P (decl) && DECL_REGISTER (decl))
7689 set_user_assembler_name (decl, asmspec);
7690 DECL_HARD_REGISTER (decl) = 1;
7692 else
7694 if (TREE_CODE (decl) == FUNCTION_DECL
7695 && fndecl_built_in_p (decl, BUILT_IN_NORMAL))
7696 set_builtin_user_assembler_name (decl, asmspec);
7697 set_user_assembler_name (decl, asmspec);
7698 if (DECL_LOCAL_DECL_P (decl))
7699 if (auto ns_decl = DECL_LOCAL_DECL_ALIAS (decl))
7700 /* We have to propagate the name to the ns-alias.
7701 This is horrible, as we're affecting a
7702 possibly-shared decl. Again, a one-true-decl
7703 model breaks down. */
7704 if (ns_decl != error_mark_node)
7705 set_user_assembler_name (ns_decl, asmspec);
7709 /* Handle non-variables up front. */
7710 if (!VAR_P (decl))
7712 rest_of_decl_compilation (decl, toplev, at_eof);
7713 return;
7716 /* If we see a class member here, it should be a static data
7717 member. */
7718 if (DECL_LANG_SPECIFIC (decl) && DECL_IN_AGGR_P (decl))
7720 gcc_assert (TREE_STATIC (decl));
7721 /* An in-class declaration of a static data member should be
7722 external; it is only a declaration, and not a definition. */
7723 if (init == NULL_TREE)
7724 gcc_assert (DECL_EXTERNAL (decl)
7725 || !TREE_PUBLIC (decl));
7728 /* We don't create any RTL for local variables. */
7729 if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
7730 return;
7732 /* We defer emission of local statics until the corresponding
7733 DECL_EXPR is expanded. But with constexpr its function might never
7734 be expanded, so go ahead and tell cgraph about the variable now. */
7735 defer_p = ((DECL_FUNCTION_SCOPE_P (decl)
7736 && !var_in_maybe_constexpr_fn (decl))
7737 || DECL_VIRTUAL_P (decl));
7739 /* Defer template instantiations. */
7740 if (DECL_LANG_SPECIFIC (decl)
7741 && DECL_IMPLICIT_INSTANTIATION (decl))
7742 defer_p = 1;
7744 /* If we're not deferring, go ahead and assemble the variable. */
7745 if (!defer_p)
7746 rest_of_decl_compilation (decl, toplev, at_eof);
7749 /* walk_tree helper for wrap_temporary_cleanups, below. */
7751 static tree
7752 wrap_cleanups_r (tree *stmt_p, int *walk_subtrees, void *data)
7754 /* Stop at types or full-expression boundaries. */
7755 if (TYPE_P (*stmt_p)
7756 || TREE_CODE (*stmt_p) == CLEANUP_POINT_EXPR)
7758 *walk_subtrees = 0;
7759 return NULL_TREE;
7762 if (TREE_CODE (*stmt_p) == TARGET_EXPR)
7764 tree guard = (tree)data;
7765 tree tcleanup = TARGET_EXPR_CLEANUP (*stmt_p);
7767 if (tcleanup && !CLEANUP_EH_ONLY (*stmt_p)
7768 && !expr_noexcept_p (tcleanup, tf_none))
7770 tcleanup = build2 (TRY_CATCH_EXPR, void_type_node, tcleanup, guard);
7771 /* Tell honor_protect_cleanup_actions to handle this as a separate
7772 cleanup. */
7773 TRY_CATCH_IS_CLEANUP (tcleanup) = 1;
7774 TARGET_EXPR_CLEANUP (*stmt_p) = tcleanup;
7778 return NULL_TREE;
7781 /* We're initializing a local variable which has a cleanup GUARD. If there
7782 are any temporaries used in the initializer INIT of this variable, we
7783 need to wrap their cleanups with TRY_CATCH_EXPR (, GUARD) so that the
7784 variable will be cleaned up properly if one of them throws.
7786 Unfortunately, there's no way to express this properly in terms of
7787 nesting, as the regions for the temporaries overlap the region for the
7788 variable itself; if there are two temporaries, the variable needs to be
7789 the first thing destroyed if either of them throws. However, we only
7790 want to run the variable's cleanup if it actually got constructed. So
7791 we need to guard the temporary cleanups with the variable's cleanup if
7792 they are run on the normal path, but not if they are run on the
7793 exceptional path. We implement this by telling
7794 honor_protect_cleanup_actions to strip the variable cleanup from the
7795 exceptional path.
7797 Another approach could be to make the variable cleanup region enclose
7798 initialization, but depend on a flag to indicate that the variable is
7799 initialized; that's effectively what we do for arrays. But the current
7800 approach works fine for non-arrays, and has no code overhead in the usual
7801 case where the temporary destructors are noexcept. */
7803 static void
7804 wrap_temporary_cleanups (tree init, tree guard)
7806 if (TREE_CODE (guard) == BIND_EXPR)
7808 /* An array cleanup region already encloses any temporary cleanups,
7809 don't wrap it around them again. */
7810 gcc_checking_assert (BIND_EXPR_VEC_DTOR (guard));
7811 return;
7813 cp_walk_tree_without_duplicates (&init, wrap_cleanups_r, (void *)guard);
7816 /* Generate code to initialize DECL (a local variable). */
7818 static void
7819 initialize_local_var (tree decl, tree init)
7821 tree type = TREE_TYPE (decl);
7822 tree cleanup;
7823 int already_used;
7825 gcc_assert (VAR_P (decl)
7826 || TREE_CODE (decl) == RESULT_DECL);
7827 gcc_assert (!TREE_STATIC (decl));
7829 if (DECL_SIZE (decl) == NULL_TREE)
7831 /* If we used it already as memory, it must stay in memory. */
7832 DECL_INITIAL (decl) = NULL_TREE;
7833 TREE_ADDRESSABLE (decl) = TREE_USED (decl);
7834 return;
7837 if (type == error_mark_node)
7838 return;
7840 /* Compute and store the initial value. */
7841 already_used = TREE_USED (decl) || TREE_USED (type);
7842 if (TREE_USED (type))
7843 DECL_READ_P (decl) = 1;
7845 /* Generate a cleanup, if necessary. */
7846 cleanup = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
7848 /* Perform the initialization. */
7849 if (init)
7851 tree rinit = (TREE_CODE (init) == INIT_EXPR
7852 ? TREE_OPERAND (init, 1) : NULL_TREE);
7853 if (rinit && !TREE_SIDE_EFFECTS (rinit)
7854 && TREE_OPERAND (init, 0) == decl)
7856 /* Stick simple initializers in DECL_INITIAL so that
7857 -Wno-init-self works (c++/34772). */
7858 DECL_INITIAL (decl) = rinit;
7860 if (warn_init_self && TYPE_REF_P (type))
7862 STRIP_NOPS (rinit);
7863 if (rinit == decl)
7864 warning_at (DECL_SOURCE_LOCATION (decl),
7865 OPT_Winit_self,
7866 "reference %qD is initialized with itself", decl);
7869 else
7871 int saved_stmts_are_full_exprs_p;
7873 /* If we're only initializing a single object, guard the
7874 destructors of any temporaries used in its initializer with
7875 its destructor. */
7876 if (cleanup)
7877 wrap_temporary_cleanups (init, cleanup);
7879 gcc_assert (building_stmt_list_p ());
7880 saved_stmts_are_full_exprs_p = stmts_are_full_exprs_p ();
7881 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
7882 finish_expr_stmt (init);
7883 current_stmt_tree ()->stmts_are_full_exprs_p =
7884 saved_stmts_are_full_exprs_p;
7888 /* Set this to 0 so we can tell whether an aggregate which was
7889 initialized was ever used. Don't do this if it has a
7890 destructor, so we don't complain about the 'resource
7891 allocation is initialization' idiom. Now set
7892 attribute((unused)) on types so decls of that type will be
7893 marked used. (see TREE_USED, above.) */
7894 if (TYPE_NEEDS_CONSTRUCTING (type)
7895 && ! already_used
7896 && TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
7897 && DECL_NAME (decl))
7898 TREE_USED (decl) = 0;
7899 else if (already_used)
7900 TREE_USED (decl) = 1;
7902 if (cleanup)
7903 finish_decl_cleanup (decl, cleanup);
7906 /* DECL is a VAR_DECL for a compiler-generated variable with static
7907 storage duration (like a virtual table) whose initializer is a
7908 compile-time constant. Initialize the variable and provide it to the
7909 back end. */
7911 void
7912 initialize_artificial_var (tree decl, vec<constructor_elt, va_gc> *v)
7914 tree init;
7915 gcc_assert (DECL_ARTIFICIAL (decl));
7916 init = build_constructor (TREE_TYPE (decl), v);
7917 gcc_assert (TREE_CODE (init) == CONSTRUCTOR);
7918 DECL_INITIAL (decl) = init;
7919 DECL_INITIALIZED_P (decl) = 1;
7920 /* Mark the decl as constexpr so that we can access its content
7921 at compile time. */
7922 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
7923 DECL_DECLARED_CONSTEXPR_P (decl) = true;
7924 determine_visibility (decl);
7925 layout_var_decl (decl);
7926 maybe_commonize_var (decl);
7927 make_rtl_for_nonlocal_decl (decl, init, /*asmspec=*/NULL);
7930 /* INIT is the initializer for a variable, as represented by the
7931 parser. Returns true iff INIT is value-dependent. */
7933 static bool
7934 value_dependent_init_p (tree init)
7936 if (TREE_CODE (init) == TREE_LIST)
7937 /* A parenthesized initializer, e.g.: int i (3, 2); ? */
7938 return any_value_dependent_elements_p (init);
7939 else if (TREE_CODE (init) == CONSTRUCTOR)
7940 /* A brace-enclosed initializer, e.g.: int i = { 3 }; ? */
7942 if (dependent_type_p (TREE_TYPE (init)))
7943 return true;
7945 vec<constructor_elt, va_gc> *elts;
7946 size_t nelts;
7947 size_t i;
7949 elts = CONSTRUCTOR_ELTS (init);
7950 nelts = vec_safe_length (elts);
7951 for (i = 0; i < nelts; ++i)
7952 if (value_dependent_init_p ((*elts)[i].value))
7953 return true;
7955 else
7956 /* It must be a simple expression, e.g., int i = 3; */
7957 return value_dependent_expression_p (init);
7959 return false;
7962 // Returns true if a DECL is VAR_DECL with the concept specifier.
7963 static inline bool
7964 is_concept_var (tree decl)
7966 return (VAR_P (decl)
7967 // Not all variables have DECL_LANG_SPECIFIC.
7968 && DECL_LANG_SPECIFIC (decl)
7969 && DECL_DECLARED_CONCEPT_P (decl));
7972 /* A helper function to be called via walk_tree. If any label exists
7973 under *TP, it is (going to be) forced. Set has_forced_label_in_static. */
7975 static tree
7976 notice_forced_label_r (tree *tp, int *walk_subtrees, void *)
7978 if (TYPE_P (*tp))
7979 *walk_subtrees = 0;
7980 if (TREE_CODE (*tp) == LABEL_DECL)
7981 cfun->has_forced_label_in_static = 1;
7982 return NULL_TREE;
7985 /* Return true if DECL has either a trivial destructor, or for C++20
7986 is constexpr and has a constexpr destructor. */
7988 static bool
7989 decl_maybe_constant_destruction (tree decl, tree type)
7991 return (TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
7992 || (cxx_dialect >= cxx20
7993 && VAR_P (decl)
7994 && DECL_DECLARED_CONSTEXPR_P (decl)
7995 && type_has_constexpr_destructor (strip_array_types (type))));
7998 static tree declare_simd_adjust_this (tree *, int *, void *);
8000 /* Helper function of omp_declare_variant_finalize. Finalize one
8001 "omp declare variant base" attribute. Return true if it should be
8002 removed. */
8004 static bool
8005 omp_declare_variant_finalize_one (tree decl, tree attr)
8007 if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
8009 walk_tree (&TREE_VALUE (TREE_VALUE (attr)), declare_simd_adjust_this,
8010 DECL_ARGUMENTS (decl), NULL);
8011 walk_tree (&TREE_PURPOSE (TREE_VALUE (attr)), declare_simd_adjust_this,
8012 DECL_ARGUMENTS (decl), NULL);
8015 tree ctx = TREE_VALUE (TREE_VALUE (attr));
8016 tree simd = omp_get_context_selector (ctx, "construct", "simd");
8017 if (simd)
8019 TREE_VALUE (simd)
8020 = c_omp_declare_simd_clauses_to_numbers (DECL_ARGUMENTS (decl),
8021 TREE_VALUE (simd));
8022 /* FIXME, adjusting simd args unimplemented. */
8023 return true;
8026 tree chain = TREE_CHAIN (TREE_VALUE (attr));
8027 location_t varid_loc
8028 = cp_expr_loc_or_input_loc (TREE_PURPOSE (TREE_CHAIN (chain)));
8029 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
8030 cp_id_kind idk = (cp_id_kind) tree_to_uhwi (TREE_VALUE (chain));
8031 tree variant = TREE_PURPOSE (TREE_VALUE (attr));
8033 location_t save_loc = input_location;
8034 input_location = varid_loc;
8036 releasing_vec args;
8037 tree parm = DECL_ARGUMENTS (decl);
8038 if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
8039 parm = DECL_CHAIN (parm);
8040 for (; parm; parm = DECL_CHAIN (parm))
8041 if (type_dependent_expression_p (parm))
8042 vec_safe_push (args, build_constructor (TREE_TYPE (parm), NULL));
8043 else if (MAYBE_CLASS_TYPE_P (TREE_TYPE (parm)))
8044 vec_safe_push (args, build_local_temp (TREE_TYPE (parm)));
8045 else
8046 vec_safe_push (args, build_zero_cst (TREE_TYPE (parm)));
8048 bool koenig_p = false;
8049 if (idk == CP_ID_KIND_UNQUALIFIED || idk == CP_ID_KIND_TEMPLATE_ID)
8051 if (identifier_p (variant)
8052 /* In C++20, we may need to perform ADL for a template
8053 name. */
8054 || (TREE_CODE (variant) == TEMPLATE_ID_EXPR
8055 && identifier_p (TREE_OPERAND (variant, 0))))
8057 if (!args->is_empty ())
8059 koenig_p = true;
8060 if (!any_type_dependent_arguments_p (args))
8061 variant = perform_koenig_lookup (variant, args,
8062 tf_warning_or_error);
8064 else
8065 variant = unqualified_fn_lookup_error (variant);
8067 else if (!args->is_empty () && is_overloaded_fn (variant))
8069 tree fn = get_first_fn (variant);
8070 fn = STRIP_TEMPLATE (fn);
8071 if (!((TREE_CODE (fn) == USING_DECL && DECL_DEPENDENT_P (fn))
8072 || DECL_FUNCTION_MEMBER_P (fn)
8073 || DECL_LOCAL_DECL_P (fn)))
8075 koenig_p = true;
8076 if (!any_type_dependent_arguments_p (args))
8077 variant = perform_koenig_lookup (variant, args,
8078 tf_warning_or_error);
8083 if (idk == CP_ID_KIND_QUALIFIED)
8084 variant = finish_call_expr (variant, &args, /*disallow_virtual=*/true,
8085 koenig_p, tf_warning_or_error);
8086 else
8087 variant = finish_call_expr (variant, &args, /*disallow_virtual=*/false,
8088 koenig_p, tf_warning_or_error);
8089 if (variant == error_mark_node && !processing_template_decl)
8090 return true;
8092 variant = cp_get_callee_fndecl_nofold (variant);
8093 input_location = save_loc;
8095 if (variant)
8097 const char *varname = IDENTIFIER_POINTER (DECL_NAME (variant));
8098 if (!comptypes (TREE_TYPE (decl), TREE_TYPE (variant), 0))
8100 error_at (varid_loc, "variant %qD and base %qD have incompatible "
8101 "types", variant, decl);
8102 return true;
8104 if (fndecl_built_in_p (variant)
8105 && (startswith (varname, "__builtin_")
8106 || startswith (varname, "__sync_")
8107 || startswith (varname, "__atomic_")))
8109 error_at (varid_loc, "variant %qD is a built-in", variant);
8110 return true;
8112 else
8114 tree construct = omp_get_context_selector (ctx, "construct", NULL);
8115 omp_mark_declare_variant (match_loc, variant, construct);
8116 if (!omp_context_selector_matches (ctx))
8117 return true;
8118 TREE_PURPOSE (TREE_VALUE (attr)) = variant;
8121 else if (!processing_template_decl)
8123 error_at (varid_loc, "could not find variant declaration");
8124 return true;
8127 return false;
8130 /* Helper function, finish up "omp declare variant base" attribute
8131 now that there is a DECL. ATTR is the first "omp declare variant base"
8132 attribute. */
8134 void
8135 omp_declare_variant_finalize (tree decl, tree attr)
8137 size_t attr_len = strlen ("omp declare variant base");
8138 tree *list = &DECL_ATTRIBUTES (decl);
8139 bool remove_all = false;
8140 location_t match_loc = DECL_SOURCE_LOCATION (decl);
8141 if (TREE_CHAIN (TREE_VALUE (attr))
8142 && TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))
8143 && EXPR_HAS_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))))
8144 match_loc = EXPR_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr))));
8145 if (DECL_CONSTRUCTOR_P (decl))
8147 error_at (match_loc, "%<declare variant%> on constructor %qD", decl);
8148 remove_all = true;
8150 else if (DECL_DESTRUCTOR_P (decl))
8152 error_at (match_loc, "%<declare variant%> on destructor %qD", decl);
8153 remove_all = true;
8155 else if (DECL_DEFAULTED_FN (decl))
8157 error_at (match_loc, "%<declare variant%> on defaulted %qD", decl);
8158 remove_all = true;
8160 else if (DECL_DELETED_FN (decl))
8162 error_at (match_loc, "%<declare variant%> on deleted %qD", decl);
8163 remove_all = true;
8165 else if (DECL_VIRTUAL_P (decl))
8167 error_at (match_loc, "%<declare variant%> on virtual %qD", decl);
8168 remove_all = true;
8170 /* This loop is like private_lookup_attribute, except that it works
8171 with tree * rather than tree, as we might want to remove the
8172 attributes that are diagnosed as errorneous. */
8173 while (*list)
8175 tree attr = get_attribute_name (*list);
8176 size_t ident_len = IDENTIFIER_LENGTH (attr);
8177 if (cmp_attribs ("omp declare variant base", attr_len,
8178 IDENTIFIER_POINTER (attr), ident_len))
8180 if (remove_all || omp_declare_variant_finalize_one (decl, *list))
8182 *list = TREE_CHAIN (*list);
8183 continue;
8186 list = &TREE_CHAIN (*list);
8190 /* Finish processing of a declaration;
8191 install its line number and initial value.
8192 If the length of an array type is not known before,
8193 it must be determined now, from the initial value, or it is an error.
8195 INIT is the initializer (if any) for DECL. If INIT_CONST_EXPR_P is
8196 true, then INIT is an integral constant expression.
8198 FLAGS is LOOKUP_ONLYCONVERTING if the = init syntax was used, else 0
8199 if the (init) syntax was used. */
8201 void
8202 cp_finish_decl (tree decl, tree init, bool init_const_expr_p,
8203 tree asmspec_tree, int flags)
8205 tree type;
8206 vec<tree, va_gc> *cleanups = NULL;
8207 const char *asmspec = NULL;
8208 int was_readonly = 0;
8209 bool var_definition_p = false;
8210 tree auto_node;
8212 if (decl == error_mark_node)
8213 return;
8214 else if (! decl)
8216 if (init)
8217 error ("assignment (not initialization) in declaration");
8218 return;
8221 gcc_assert (TREE_CODE (decl) != RESULT_DECL);
8222 /* Parameters are handled by store_parm_decls, not cp_finish_decl. */
8223 gcc_assert (TREE_CODE (decl) != PARM_DECL);
8225 type = TREE_TYPE (decl);
8226 if (type == error_mark_node)
8227 return;
8229 if (VAR_P (decl) && is_copy_initialization (init))
8230 flags |= LOOKUP_ONLYCONVERTING;
8232 /* Warn about register storage specifiers except when in GNU global
8233 or local register variable extension. */
8234 if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec_tree == NULL_TREE)
8236 if (cxx_dialect >= cxx17)
8237 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
8238 "ISO C++17 does not allow %<register%> storage "
8239 "class specifier");
8240 else
8241 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
8242 "%<register%> storage class specifier used");
8245 /* If a name was specified, get the string. */
8246 if (at_namespace_scope_p ())
8247 asmspec_tree = maybe_apply_renaming_pragma (decl, asmspec_tree);
8248 if (asmspec_tree && asmspec_tree != error_mark_node)
8249 asmspec = TREE_STRING_POINTER (asmspec_tree);
8251 bool in_class_decl
8252 = (current_class_type
8253 && CP_DECL_CONTEXT (decl) == current_class_type
8254 && TYPE_BEING_DEFINED (current_class_type)
8255 && !CLASSTYPE_TEMPLATE_INSTANTIATION (current_class_type));
8257 if (in_class_decl
8258 && (DECL_INITIAL (decl) || init))
8259 DECL_INITIALIZED_IN_CLASS_P (decl) = 1;
8261 if (VAR_P (decl)
8262 && (auto_node = type_uses_auto (type)))
8264 tree d_init;
8265 if (init == NULL_TREE)
8267 if (DECL_LANG_SPECIFIC (decl)
8268 && DECL_TEMPLATE_INSTANTIATION (decl)
8269 && !DECL_TEMPLATE_INSTANTIATED (decl))
8271 /* init is null because we're deferring instantiating the
8272 initializer until we need it. Well, we need it now. */
8273 instantiate_decl (decl, /*defer_ok*/true, /*expl*/false);
8274 return;
8277 gcc_assert (CLASS_PLACEHOLDER_TEMPLATE (auto_node));
8279 d_init = init;
8280 if (d_init)
8282 if (TREE_CODE (d_init) == TREE_LIST
8283 && !CLASS_PLACEHOLDER_TEMPLATE (auto_node))
8284 d_init = build_x_compound_expr_from_list (d_init, ELK_INIT,
8285 tf_warning_or_error);
8286 d_init = resolve_nondeduced_context (d_init, tf_warning_or_error);
8287 /* Force auto deduction now. Use tf_none to avoid redundant warnings
8288 on deprecated-14.C. */
8289 mark_single_function (d_init, tf_none);
8291 enum auto_deduction_context adc = adc_variable_type;
8292 if (DECL_DECOMPOSITION_P (decl))
8293 adc = adc_decomp_type;
8294 tree outer_targs = NULL_TREE;
8295 if (PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node)
8296 && DECL_LANG_SPECIFIC (decl)
8297 && DECL_TEMPLATE_INFO (decl)
8298 && !DECL_FUNCTION_SCOPE_P (decl))
8299 /* The outer template arguments might be needed for satisfaction.
8300 (For function scope variables, do_auto_deduction will obtain the
8301 outer template arguments from current_function_decl.) */
8302 outer_targs = DECL_TI_ARGS (decl);
8303 type = TREE_TYPE (decl) = do_auto_deduction (type, d_init, auto_node,
8304 tf_warning_or_error, adc,
8305 outer_targs, flags);
8306 if (type == error_mark_node)
8307 return;
8308 if (TREE_CODE (type) == FUNCTION_TYPE)
8310 error ("initializer for %<decltype(auto) %D%> has function type; "
8311 "did you forget the %<()%>?", decl);
8312 TREE_TYPE (decl) = error_mark_node;
8313 return;
8315 /* As in start_decl_1, complete so TREE_READONLY is set properly. */
8316 if (!processing_template_decl
8317 && !type_uses_auto (type)
8318 && !COMPLETE_TYPE_P (complete_type (type)))
8320 error_at (location_of (decl),
8321 "deduced type %qT for %qD is incomplete", type, decl);
8322 cxx_incomplete_type_inform (type);
8323 TREE_TYPE (decl) = error_mark_node;
8324 return;
8326 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
8328 /* Update the type of the corresponding TEMPLATE_DECL to match. */
8329 if (DECL_LANG_SPECIFIC (decl)
8330 && DECL_TEMPLATE_INFO (decl)
8331 && DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (decl)) == decl)
8332 TREE_TYPE (DECL_TI_TEMPLATE (decl)) = type;
8335 if (ensure_literal_type_for_constexpr_object (decl) == error_mark_node)
8337 DECL_DECLARED_CONSTEXPR_P (decl) = 0;
8338 if (VAR_P (decl) && DECL_CLASS_SCOPE_P (decl))
8340 init = NULL_TREE;
8341 DECL_EXTERNAL (decl) = 1;
8345 if (VAR_P (decl)
8346 && DECL_CLASS_SCOPE_P (decl)
8347 && verify_type_context (DECL_SOURCE_LOCATION (decl),
8348 TCTX_STATIC_STORAGE, type)
8349 && DECL_INITIALIZED_IN_CLASS_P (decl))
8350 check_static_variable_definition (decl, type);
8352 if (!processing_template_decl && VAR_P (decl) && is_global_var (decl))
8354 type_context_kind context = (DECL_THREAD_LOCAL_P (decl)
8355 ? TCTX_THREAD_STORAGE
8356 : TCTX_STATIC_STORAGE);
8357 verify_type_context (input_location, context, TREE_TYPE (decl));
8360 if (init && TREE_CODE (decl) == FUNCTION_DECL)
8362 tree clone;
8363 if (init == ridpointers[(int)RID_DELETE])
8365 /* FIXME check this is 1st decl. */
8366 DECL_DELETED_FN (decl) = 1;
8367 DECL_DECLARED_INLINE_P (decl) = 1;
8368 DECL_INITIAL (decl) = error_mark_node;
8369 FOR_EACH_CLONE (clone, decl)
8371 DECL_DELETED_FN (clone) = 1;
8372 DECL_DECLARED_INLINE_P (clone) = 1;
8373 DECL_INITIAL (clone) = error_mark_node;
8375 init = NULL_TREE;
8377 else if (init == ridpointers[(int)RID_DEFAULT])
8379 if (defaultable_fn_check (decl))
8380 DECL_DEFAULTED_FN (decl) = 1;
8381 else
8382 DECL_INITIAL (decl) = NULL_TREE;
8386 if (init && VAR_P (decl))
8388 DECL_NONTRIVIALLY_INITIALIZED_P (decl) = 1;
8389 /* If DECL is a reference, then we want to know whether init is a
8390 reference constant; init_const_expr_p as passed tells us whether
8391 it's an rvalue constant. */
8392 if (TYPE_REF_P (type))
8393 init_const_expr_p = potential_constant_expression (init);
8394 if (init_const_expr_p)
8396 /* Set these flags now for templates. We'll update the flags in
8397 store_init_value for instantiations. */
8398 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
8399 if (decl_maybe_constant_var_p (decl)
8400 /* FIXME setting TREE_CONSTANT on refs breaks the back end. */
8401 && !TYPE_REF_P (type))
8402 TREE_CONSTANT (decl) = 1;
8404 /* This is handled mostly by gimplify.cc, but we have to deal with
8405 not warning about int x = x; as it is a GCC extension to turn off
8406 this warning but only if warn_init_self is zero. */
8407 if (!DECL_EXTERNAL (decl)
8408 && !TREE_STATIC (decl)
8409 && decl == tree_strip_any_location_wrapper (init)
8410 && !warning_enabled_at (DECL_SOURCE_LOCATION (decl), OPT_Winit_self))
8411 suppress_warning (decl, OPT_Winit_self);
8414 if (flag_openmp
8415 && TREE_CODE (decl) == FUNCTION_DECL
8416 /* #pragma omp declare variant on methods handled in finish_struct
8417 instead. */
8418 && (!DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
8419 || COMPLETE_TYPE_P (DECL_CONTEXT (decl))))
8420 if (tree attr = lookup_attribute ("omp declare variant base",
8421 DECL_ATTRIBUTES (decl)))
8422 omp_declare_variant_finalize (decl, attr);
8424 if (processing_template_decl)
8426 bool type_dependent_p;
8428 /* Add this declaration to the statement-tree. */
8429 if (at_function_scope_p ())
8430 add_decl_expr (decl);
8432 type_dependent_p = dependent_type_p (type);
8434 if (check_for_bare_parameter_packs (init))
8436 init = NULL_TREE;
8437 DECL_INITIAL (decl) = NULL_TREE;
8440 /* Generally, initializers in templates are expanded when the
8441 template is instantiated. But, if DECL is a variable constant
8442 then it can be used in future constant expressions, so its value
8443 must be available. */
8445 bool dep_init = false;
8447 if (!VAR_P (decl) || type_dependent_p)
8448 /* We can't do anything if the decl has dependent type. */;
8449 else if (!init && is_concept_var (decl))
8451 error ("variable concept has no initializer");
8452 init = boolean_true_node;
8454 else if (init
8455 && (init_const_expr_p || DECL_DECLARED_CONSTEXPR_P (decl))
8456 && !TYPE_REF_P (type)
8457 && decl_maybe_constant_var_p (decl)
8458 && !(dep_init = value_dependent_init_p (init)))
8460 /* This variable seems to be a non-dependent constant, so process
8461 its initializer. If check_initializer returns non-null the
8462 initialization wasn't constant after all. */
8463 tree init_code;
8464 cleanups = make_tree_vector ();
8465 init_code = check_initializer (decl, init, flags, &cleanups);
8466 if (init_code == NULL_TREE)
8467 init = NULL_TREE;
8468 release_tree_vector (cleanups);
8470 else
8472 gcc_assert (!DECL_PRETTY_FUNCTION_P (decl));
8473 /* Try to deduce array size. */
8474 maybe_deduce_size_from_array_init (decl, init);
8475 /* And complain about multiple initializers. */
8476 if (init && TREE_CODE (init) == TREE_LIST && TREE_CHAIN (init)
8477 && !MAYBE_CLASS_TYPE_P (type))
8478 init = build_x_compound_expr_from_list (init, ELK_INIT,
8479 tf_warning_or_error);
8482 if (init)
8483 DECL_INITIAL (decl) = init;
8485 if (dep_init)
8487 retrofit_lang_decl (decl);
8488 SET_DECL_DEPENDENT_INIT_P (decl, true);
8491 if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec)
8493 set_user_assembler_name (decl, asmspec);
8494 DECL_HARD_REGISTER (decl) = 1;
8496 return;
8499 /* Just store non-static data member initializers for later. */
8500 if (init && TREE_CODE (decl) == FIELD_DECL)
8501 DECL_INITIAL (decl) = init;
8503 /* Take care of TYPE_DECLs up front. */
8504 if (TREE_CODE (decl) == TYPE_DECL)
8506 if (type != error_mark_node
8507 && MAYBE_CLASS_TYPE_P (type) && DECL_NAME (decl))
8509 if (TREE_TYPE (DECL_NAME (decl)) && TREE_TYPE (decl) != type)
8510 warning (0, "shadowing previous type declaration of %q#D", decl);
8511 set_identifier_type_value (DECL_NAME (decl), decl);
8514 /* If we have installed this as the canonical typedef for this
8515 type, and that type has not been defined yet, delay emitting
8516 the debug information for it, as we will emit it later. */
8517 if (TYPE_MAIN_DECL (TREE_TYPE (decl)) == decl
8518 && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
8519 TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
8521 rest_of_decl_compilation (decl, DECL_FILE_SCOPE_P (decl),
8522 at_eof);
8523 return;
8526 /* A reference will be modified here, as it is initialized. */
8527 if (! DECL_EXTERNAL (decl)
8528 && TREE_READONLY (decl)
8529 && TYPE_REF_P (type))
8531 was_readonly = 1;
8532 TREE_READONLY (decl) = 0;
8535 /* This needs to happen before extend_ref_init_temps. */
8536 if (VAR_OR_FUNCTION_DECL_P (decl))
8538 if (VAR_P (decl))
8539 maybe_commonize_var (decl);
8540 determine_visibility (decl);
8543 if (VAR_P (decl))
8545 duration_kind dk = decl_storage_duration (decl);
8546 /* [dcl.constinit]/1 "The constinit specifier shall be applied
8547 only to a declaration of a variable with static or thread storage
8548 duration." */
8549 if (DECL_DECLARED_CONSTINIT_P (decl)
8550 && !(dk == dk_thread || dk == dk_static))
8552 error_at (DECL_SOURCE_LOCATION (decl),
8553 "%<constinit%> can only be applied to a variable with "
8554 "static or thread storage duration");
8555 return;
8558 /* If this is a local variable that will need a mangled name,
8559 register it now. We must do this before processing the
8560 initializer for the variable, since the initialization might
8561 require a guard variable, and since the mangled name of the
8562 guard variable will depend on the mangled name of this
8563 variable. */
8564 if (DECL_FUNCTION_SCOPE_P (decl)
8565 && TREE_STATIC (decl)
8566 && !DECL_ARTIFICIAL (decl))
8568 /* The variable holding an anonymous union will have had its
8569 discriminator set in finish_anon_union, after which it's
8570 NAME will have been cleared. */
8571 if (DECL_NAME (decl))
8572 determine_local_discriminator (decl);
8573 /* Normally has_forced_label_in_static is set during GIMPLE
8574 lowering, but [cd]tors are never actually compiled directly.
8575 We need to set this early so we can deal with the label
8576 address extension. */
8577 if ((DECL_CONSTRUCTOR_P (current_function_decl)
8578 || DECL_DESTRUCTOR_P (current_function_decl))
8579 && init)
8581 walk_tree (&init, notice_forced_label_r, NULL, NULL);
8582 add_local_decl (cfun, decl);
8584 /* And make sure it's in the symbol table for
8585 c_parse_final_cleanups to find. */
8586 varpool_node::get_create (decl);
8589 /* Convert the initializer to the type of DECL, if we have not
8590 already initialized DECL. */
8591 if (!DECL_INITIALIZED_P (decl)
8592 /* If !DECL_EXTERNAL then DECL is being defined. In the
8593 case of a static data member initialized inside the
8594 class-specifier, there can be an initializer even if DECL
8595 is *not* defined. */
8596 && (!DECL_EXTERNAL (decl) || init))
8598 cleanups = make_tree_vector ();
8599 init = check_initializer (decl, init, flags, &cleanups);
8601 /* Handle:
8603 [dcl.init]
8605 The memory occupied by any object of static storage
8606 duration is zero-initialized at program startup before
8607 any other initialization takes place.
8609 We cannot create an appropriate initializer until after
8610 the type of DECL is finalized. If DECL_INITIAL is set,
8611 then the DECL is statically initialized, and any
8612 necessary zero-initialization has already been performed. */
8613 if (TREE_STATIC (decl) && !DECL_INITIAL (decl))
8614 DECL_INITIAL (decl) = build_zero_init (TREE_TYPE (decl),
8615 /*nelts=*/NULL_TREE,
8616 /*static_storage_p=*/true);
8617 /* Remember that the initialization for this variable has
8618 taken place. */
8619 DECL_INITIALIZED_P (decl) = 1;
8620 /* This declaration is the definition of this variable,
8621 unless we are initializing a static data member within
8622 the class specifier. */
8623 if (!DECL_EXTERNAL (decl))
8624 var_definition_p = true;
8626 /* If the variable has an array type, lay out the type, even if
8627 there is no initializer. It is valid to index through the
8628 array, and we must get TYPE_ALIGN set correctly on the array
8629 type. */
8630 else if (TREE_CODE (type) == ARRAY_TYPE)
8631 layout_type (type);
8633 if (TREE_STATIC (decl)
8634 && !at_function_scope_p ()
8635 && current_function_decl == NULL)
8636 /* So decl is a global variable or a static member of a
8637 non local class. Record the types it uses
8638 so that we can decide later to emit debug info for them. */
8639 record_types_used_by_current_var_decl (decl);
8642 /* Add this declaration to the statement-tree. This needs to happen
8643 after the call to check_initializer so that the DECL_EXPR for a
8644 reference temp is added before the DECL_EXPR for the reference itself. */
8645 if (DECL_FUNCTION_SCOPE_P (decl))
8647 /* If we're building a variable sized type, and we might be
8648 reachable other than via the top of the current binding
8649 level, then create a new BIND_EXPR so that we deallocate
8650 the object at the right time. */
8651 if (VAR_P (decl)
8652 && DECL_SIZE (decl)
8653 && !TREE_CONSTANT (DECL_SIZE (decl))
8654 && STATEMENT_LIST_HAS_LABEL (cur_stmt_list))
8656 tree bind;
8657 bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL);
8658 TREE_SIDE_EFFECTS (bind) = 1;
8659 add_stmt (bind);
8660 BIND_EXPR_BODY (bind) = push_stmt_list ();
8662 add_decl_expr (decl);
8665 /* Let the middle end know about variables and functions -- but not
8666 static data members in uninstantiated class templates. */
8667 if (VAR_OR_FUNCTION_DECL_P (decl))
8669 if (VAR_P (decl))
8671 layout_var_decl (decl);
8672 if (!flag_weak)
8673 /* Check again now that we have an initializer. */
8674 maybe_commonize_var (decl);
8675 /* A class-scope constexpr variable with an out-of-class declaration.
8676 C++17 makes them implicitly inline, but still force it out. */
8677 if (DECL_INLINE_VAR_P (decl)
8678 && !DECL_VAR_DECLARED_INLINE_P (decl)
8679 && !DECL_TEMPLATE_INSTANTIATION (decl)
8680 && !in_class_decl)
8681 mark_needed (decl);
8684 if (var_definition_p
8685 /* With -fmerge-all-constants, gimplify_init_constructor
8686 might add TREE_STATIC to the variable. */
8687 && (TREE_STATIC (decl) || flag_merge_constants >= 2))
8689 /* If a TREE_READONLY variable needs initialization
8690 at runtime, it is no longer readonly and we need to
8691 avoid MEM_READONLY_P being set on RTL created for it. */
8692 if (init)
8694 if (TREE_READONLY (decl))
8695 TREE_READONLY (decl) = 0;
8696 was_readonly = 0;
8698 else if (was_readonly)
8699 TREE_READONLY (decl) = 1;
8701 /* Likewise if it needs destruction. */
8702 if (!decl_maybe_constant_destruction (decl, type))
8703 TREE_READONLY (decl) = 0;
8706 make_rtl_for_nonlocal_decl (decl, init, asmspec);
8708 /* Check for abstractness of the type. */
8709 if (var_definition_p)
8710 abstract_virtuals_error (decl, type);
8712 if (TREE_TYPE (decl) == error_mark_node)
8713 /* No initialization required. */
8715 else if (TREE_CODE (decl) == FUNCTION_DECL)
8717 if (init)
8719 if (init == ridpointers[(int)RID_DEFAULT])
8721 /* An out-of-class default definition is defined at
8722 the point where it is explicitly defaulted. */
8723 if (DECL_DELETED_FN (decl))
8724 maybe_explain_implicit_delete (decl);
8725 else if (DECL_INITIAL (decl) == error_mark_node)
8726 synthesize_method (decl);
8728 else
8729 error_at (cp_expr_loc_or_loc (init,
8730 DECL_SOURCE_LOCATION (decl)),
8731 "function %q#D is initialized like a variable",
8732 decl);
8734 /* else no initialization required. */
8736 else if (DECL_EXTERNAL (decl)
8737 && ! (DECL_LANG_SPECIFIC (decl)
8738 && DECL_NOT_REALLY_EXTERN (decl)))
8740 /* check_initializer will have done any constant initialization. */
8742 /* A variable definition. */
8743 else if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
8744 /* Initialize the local variable. */
8745 initialize_local_var (decl, init);
8747 /* If a variable is defined, and then a subsequent
8748 definition with external linkage is encountered, we will
8749 get here twice for the same variable. We want to avoid
8750 calling expand_static_init more than once. For variables
8751 that are not static data members, we can call
8752 expand_static_init only when we actually process the
8753 initializer. It is not legal to redeclare a static data
8754 member, so this issue does not arise in that case. */
8755 else if (var_definition_p && TREE_STATIC (decl))
8756 expand_static_init (decl, init);
8759 /* If a CLEANUP_STMT was created to destroy a temporary bound to a
8760 reference, insert it in the statement-tree now. */
8761 if (cleanups)
8763 for (tree t : *cleanups)
8765 push_cleanup (NULL_TREE, t, false);
8766 /* As in initialize_local_var. */
8767 wrap_temporary_cleanups (init, t);
8769 release_tree_vector (cleanups);
8772 if (was_readonly)
8773 TREE_READONLY (decl) = 1;
8775 if (flag_openmp
8776 && VAR_P (decl)
8777 && lookup_attribute ("omp declare target implicit",
8778 DECL_ATTRIBUTES (decl)))
8780 DECL_ATTRIBUTES (decl)
8781 = remove_attribute ("omp declare target implicit",
8782 DECL_ATTRIBUTES (decl));
8783 complete_type (TREE_TYPE (decl));
8784 if (!omp_mappable_type (TREE_TYPE (decl)))
8786 error ("%q+D in declare target directive does not have mappable"
8787 " type", decl);
8788 if (TREE_TYPE (decl) != error_mark_node
8789 && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
8790 cxx_incomplete_type_inform (TREE_TYPE (decl));
8792 else if (!lookup_attribute ("omp declare target",
8793 DECL_ATTRIBUTES (decl))
8794 && !lookup_attribute ("omp declare target link",
8795 DECL_ATTRIBUTES (decl)))
8797 DECL_ATTRIBUTES (decl)
8798 = tree_cons (get_identifier ("omp declare target"),
8799 NULL_TREE, DECL_ATTRIBUTES (decl));
8800 symtab_node *node = symtab_node::get (decl);
8801 if (node != NULL)
8803 node->offloadable = 1;
8804 if (ENABLE_OFFLOADING)
8806 g->have_offload = true;
8807 if (is_a <varpool_node *> (node))
8808 vec_safe_push (offload_vars, decl);
8814 /* This is the last point we can lower alignment so give the target the
8815 chance to do so. */
8816 if (VAR_P (decl)
8817 && !is_global_var (decl)
8818 && !DECL_HARD_REGISTER (decl))
8819 targetm.lower_local_decl_alignment (decl);
8821 invoke_plugin_callbacks (PLUGIN_FINISH_DECL, decl);
8824 /* For class TYPE return itself or some its bases that contain
8825 any direct non-static data members. Return error_mark_node if an
8826 error has been diagnosed. */
8828 static tree
8829 find_decomp_class_base (location_t loc, tree type, tree ret)
8831 bool member_seen = false;
8832 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
8833 if (TREE_CODE (field) != FIELD_DECL
8834 || DECL_ARTIFICIAL (field)
8835 || DECL_UNNAMED_BIT_FIELD (field))
8836 continue;
8837 else if (ret)
8838 return type;
8839 else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
8841 if (TREE_CODE (TREE_TYPE (field)) == RECORD_TYPE)
8842 error_at (loc, "cannot decompose class type %qT because it has an "
8843 "anonymous struct member", type);
8844 else
8845 error_at (loc, "cannot decompose class type %qT because it has an "
8846 "anonymous union member", type);
8847 inform (DECL_SOURCE_LOCATION (field), "declared here");
8848 return error_mark_node;
8850 else if (!accessible_p (type, field, true))
8852 error_at (loc, "cannot decompose inaccessible member %qD of %qT",
8853 field, type);
8854 inform (DECL_SOURCE_LOCATION (field),
8855 TREE_PRIVATE (field)
8856 ? G_("declared private here")
8857 : G_("declared protected here"));
8858 return error_mark_node;
8860 else
8861 member_seen = true;
8863 tree base_binfo, binfo;
8864 tree orig_ret = ret;
8865 int i;
8866 if (member_seen)
8867 ret = type;
8868 for (binfo = TYPE_BINFO (type), i = 0;
8869 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
8871 tree t = find_decomp_class_base (loc, TREE_TYPE (base_binfo), ret);
8872 if (t == error_mark_node)
8873 return error_mark_node;
8874 if (t != NULL_TREE && t != ret)
8876 if (ret == type)
8878 error_at (loc, "cannot decompose class type %qT: both it and "
8879 "its base class %qT have non-static data members",
8880 type, t);
8881 return error_mark_node;
8883 else if (orig_ret != NULL_TREE)
8884 return t;
8885 else if (ret != NULL_TREE)
8887 error_at (loc, "cannot decompose class type %qT: its base "
8888 "classes %qT and %qT have non-static data "
8889 "members", type, ret, t);
8890 return error_mark_node;
8892 else
8893 ret = t;
8896 return ret;
8899 /* Return std::tuple_size<TYPE>::value. */
8901 static tree
8902 get_tuple_size (tree type)
8904 tree args = make_tree_vec (1);
8905 TREE_VEC_ELT (args, 0) = type;
8906 tree inst = lookup_template_class (tuple_size_identifier, args,
8907 /*in_decl*/NULL_TREE,
8908 /*context*/std_node,
8909 /*entering_scope*/false, tf_none);
8910 inst = complete_type (inst);
8911 if (inst == error_mark_node || !COMPLETE_TYPE_P (inst))
8912 return NULL_TREE;
8913 tree val = lookup_qualified_name (inst, value_identifier,
8914 LOOK_want::NORMAL, /*complain*/false);
8915 if (TREE_CODE (val) == VAR_DECL || TREE_CODE (val) == CONST_DECL)
8916 val = maybe_constant_value (val);
8917 if (TREE_CODE (val) == INTEGER_CST)
8918 return val;
8919 else
8920 return error_mark_node;
8923 /* Return std::tuple_element<I,TYPE>::type. */
8925 static tree
8926 get_tuple_element_type (tree type, unsigned i)
8928 tree args = make_tree_vec (2);
8929 TREE_VEC_ELT (args, 0) = build_int_cst (integer_type_node, i);
8930 TREE_VEC_ELT (args, 1) = type;
8931 tree inst = lookup_template_class (tuple_element_identifier, args,
8932 /*in_decl*/NULL_TREE,
8933 /*context*/std_node,
8934 /*entering_scope*/false,
8935 tf_warning_or_error);
8936 return make_typename_type (inst, type_identifier,
8937 none_type, tf_warning_or_error);
8940 /* Return e.get<i>() or get<i>(e). */
8942 static tree
8943 get_tuple_decomp_init (tree decl, unsigned i)
8945 tree targs = make_tree_vec (1);
8946 TREE_VEC_ELT (targs, 0) = build_int_cst (integer_type_node, i);
8948 tree etype = TREE_TYPE (decl);
8949 tree e = convert_from_reference (decl);
8951 /* [The id-expression] e is an lvalue if the type of the entity e is an
8952 lvalue reference and an xvalue otherwise. */
8953 if (!TYPE_REF_P (etype)
8954 || TYPE_REF_IS_RVALUE (etype))
8955 e = move (e);
8957 tree fns = lookup_qualified_name (TREE_TYPE (e), get__identifier,
8958 LOOK_want::NORMAL, /*complain*/false);
8959 bool use_member_get = false;
8961 /* To use a member get, member lookup must find at least one
8962 declaration that is a function template
8963 whose first template parameter is a non-type parameter. */
8964 for (lkp_iterator iter (MAYBE_BASELINK_FUNCTIONS (fns)); iter; ++iter)
8966 tree fn = *iter;
8967 if (TREE_CODE (fn) == TEMPLATE_DECL)
8969 tree tparms = DECL_TEMPLATE_PARMS (fn);
8970 tree parm = TREE_VEC_ELT (INNERMOST_TEMPLATE_PARMS (tparms), 0);
8971 if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
8973 use_member_get = true;
8974 break;
8979 if (use_member_get)
8981 fns = lookup_template_function (fns, targs);
8982 return build_new_method_call (e, fns, /*args*/NULL,
8983 /*path*/NULL_TREE, LOOKUP_NORMAL,
8984 /*fn_p*/NULL, tf_warning_or_error);
8986 else
8988 releasing_vec args (make_tree_vector_single (e));
8989 fns = lookup_template_function (get__identifier, targs);
8990 fns = perform_koenig_lookup (fns, args, tf_warning_or_error);
8991 return finish_call_expr (fns, &args, /*novirt*/false,
8992 /*koenig*/true, tf_warning_or_error);
8996 /* It's impossible to recover the decltype of a tuple decomposition variable
8997 based on the actual type of the variable, so store it in a hash table. */
8999 static GTY((cache)) decl_tree_cache_map *decomp_type_table;
9001 tree
9002 lookup_decomp_type (tree v)
9004 return *decomp_type_table->get (v);
9007 /* Mangle a decomposition declaration if needed. Arguments like
9008 in cp_finish_decomp. */
9010 void
9011 cp_maybe_mangle_decomp (tree decl, tree first, unsigned int count)
9013 if (!processing_template_decl
9014 && !error_operand_p (decl)
9015 && TREE_STATIC (decl))
9017 auto_vec<tree, 16> v;
9018 v.safe_grow (count, true);
9019 tree d = first;
9020 for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
9021 v[count - i - 1] = d;
9022 SET_DECL_ASSEMBLER_NAME (decl, mangle_decomp (decl, v));
9023 maybe_apply_pragma_weak (decl);
9027 /* Finish a decomposition declaration. DECL is the underlying declaration
9028 "e", FIRST is the head of a chain of decls for the individual identifiers
9029 chained through DECL_CHAIN in reverse order and COUNT is the number of
9030 those decls. */
9032 void
9033 cp_finish_decomp (tree decl, tree first, unsigned int count)
9035 if (error_operand_p (decl))
9037 error_out:
9038 while (count--)
9040 TREE_TYPE (first) = error_mark_node;
9041 if (DECL_HAS_VALUE_EXPR_P (first))
9043 SET_DECL_VALUE_EXPR (first, NULL_TREE);
9044 DECL_HAS_VALUE_EXPR_P (first) = 0;
9046 first = DECL_CHAIN (first);
9048 if (DECL_P (decl) && DECL_NAMESPACE_SCOPE_P (decl))
9049 SET_DECL_ASSEMBLER_NAME (decl, get_identifier ("<decomp>"));
9050 return;
9053 location_t loc = DECL_SOURCE_LOCATION (decl);
9054 if (type_dependent_expression_p (decl)
9055 /* This happens for range for when not in templates.
9056 Still add the DECL_VALUE_EXPRs for later processing. */
9057 || (!processing_template_decl
9058 && type_uses_auto (TREE_TYPE (decl))))
9060 for (unsigned int i = 0; i < count; i++)
9062 if (!DECL_HAS_VALUE_EXPR_P (first))
9064 tree v = build_nt (ARRAY_REF, decl,
9065 size_int (count - i - 1),
9066 NULL_TREE, NULL_TREE);
9067 SET_DECL_VALUE_EXPR (first, v);
9068 DECL_HAS_VALUE_EXPR_P (first) = 1;
9070 if (processing_template_decl)
9071 fit_decomposition_lang_decl (first, decl);
9072 first = DECL_CHAIN (first);
9074 return;
9077 auto_vec<tree, 16> v;
9078 v.safe_grow (count, true);
9079 tree d = first;
9080 for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
9082 v[count - i - 1] = d;
9083 fit_decomposition_lang_decl (d, decl);
9086 tree type = TREE_TYPE (decl);
9087 tree dexp = decl;
9089 if (TYPE_REF_P (type))
9091 dexp = convert_from_reference (dexp);
9092 type = complete_type (TREE_TYPE (type));
9093 if (type == error_mark_node)
9094 goto error_out;
9095 if (!COMPLETE_TYPE_P (type))
9097 error_at (loc, "structured binding refers to incomplete type %qT",
9098 type);
9099 goto error_out;
9103 tree eltype = NULL_TREE;
9104 unsigned HOST_WIDE_INT eltscnt = 0;
9105 if (TREE_CODE (type) == ARRAY_TYPE)
9107 tree nelts;
9108 nelts = array_type_nelts_top (type);
9109 if (nelts == error_mark_node)
9110 goto error_out;
9111 if (!tree_fits_uhwi_p (nelts))
9113 error_at (loc, "cannot decompose variable length array %qT", type);
9114 goto error_out;
9116 eltscnt = tree_to_uhwi (nelts);
9117 if (count != eltscnt)
9119 cnt_mismatch:
9120 if (count > eltscnt)
9121 error_n (loc, count,
9122 "%u name provided for structured binding",
9123 "%u names provided for structured binding", count);
9124 else
9125 error_n (loc, count,
9126 "only %u name provided for structured binding",
9127 "only %u names provided for structured binding", count);
9128 inform_n (loc, eltscnt,
9129 "while %qT decomposes into %wu element",
9130 "while %qT decomposes into %wu elements",
9131 type, eltscnt);
9132 goto error_out;
9134 eltype = TREE_TYPE (type);
9135 for (unsigned int i = 0; i < count; i++)
9137 TREE_TYPE (v[i]) = eltype;
9138 layout_decl (v[i], 0);
9139 if (processing_template_decl)
9140 continue;
9141 tree t = unshare_expr (dexp);
9142 t = build4 (ARRAY_REF, eltype, t, size_int (i), NULL_TREE, NULL_TREE);
9143 SET_DECL_VALUE_EXPR (v[i], t);
9144 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9147 /* 2 GNU extensions. */
9148 else if (TREE_CODE (type) == COMPLEX_TYPE)
9150 eltscnt = 2;
9151 if (count != eltscnt)
9152 goto cnt_mismatch;
9153 eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
9154 for (unsigned int i = 0; i < count; i++)
9156 TREE_TYPE (v[i]) = eltype;
9157 layout_decl (v[i], 0);
9158 if (processing_template_decl)
9159 continue;
9160 tree t = unshare_expr (dexp);
9161 t = build1 (i ? IMAGPART_EXPR : REALPART_EXPR, eltype, t);
9162 SET_DECL_VALUE_EXPR (v[i], t);
9163 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9166 else if (TREE_CODE (type) == VECTOR_TYPE)
9168 if (!TYPE_VECTOR_SUBPARTS (type).is_constant (&eltscnt))
9170 error_at (loc, "cannot decompose variable length vector %qT", type);
9171 goto error_out;
9173 if (count != eltscnt)
9174 goto cnt_mismatch;
9175 eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
9176 for (unsigned int i = 0; i < count; i++)
9178 TREE_TYPE (v[i]) = eltype;
9179 layout_decl (v[i], 0);
9180 if (processing_template_decl)
9181 continue;
9182 tree t = unshare_expr (dexp);
9183 convert_vector_to_array_for_subscript (DECL_SOURCE_LOCATION (v[i]),
9184 &t, size_int (i));
9185 t = build4 (ARRAY_REF, eltype, t, size_int (i), NULL_TREE, NULL_TREE);
9186 SET_DECL_VALUE_EXPR (v[i], t);
9187 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9190 else if (tree tsize = get_tuple_size (type))
9192 if (tsize == error_mark_node)
9194 error_at (loc, "%<std::tuple_size<%T>::value%> is not an integral "
9195 "constant expression", type);
9196 goto error_out;
9198 if (!tree_fits_uhwi_p (tsize))
9200 error_n (loc, count,
9201 "%u name provided for structured binding",
9202 "%u names provided for structured binding", count);
9203 inform (loc, "while %qT decomposes into %E elements",
9204 type, tsize);
9205 goto error_out;
9207 eltscnt = tree_to_uhwi (tsize);
9208 if (count != eltscnt)
9209 goto cnt_mismatch;
9210 int save_read = DECL_READ_P (decl);
9211 for (unsigned i = 0; i < count; ++i)
9213 location_t sloc = input_location;
9214 location_t dloc = DECL_SOURCE_LOCATION (v[i]);
9216 input_location = dloc;
9217 tree init = get_tuple_decomp_init (decl, i);
9218 tree eltype = (init == error_mark_node ? error_mark_node
9219 : get_tuple_element_type (type, i));
9220 input_location = sloc;
9222 if (VOID_TYPE_P (eltype))
9224 error ("%<std::tuple_element<%u, %T>::type%> is %<void%>",
9225 i, type);
9226 eltype = error_mark_node;
9228 if (init == error_mark_node || eltype == error_mark_node)
9230 inform (dloc, "in initialization of structured binding "
9231 "variable %qD", v[i]);
9232 goto error_out;
9234 /* Save the decltype away before reference collapse. */
9235 hash_map_safe_put<hm_ggc> (decomp_type_table, v[i], eltype);
9236 eltype = cp_build_reference_type (eltype, !lvalue_p (init));
9237 TREE_TYPE (v[i]) = eltype;
9238 layout_decl (v[i], 0);
9239 if (DECL_HAS_VALUE_EXPR_P (v[i]))
9241 /* In this case the names are variables, not just proxies. */
9242 SET_DECL_VALUE_EXPR (v[i], NULL_TREE);
9243 DECL_HAS_VALUE_EXPR_P (v[i]) = 0;
9245 if (!processing_template_decl)
9247 copy_linkage (v[i], decl);
9248 cp_finish_decl (v[i], init, /*constexpr*/false,
9249 /*asm*/NULL_TREE, LOOKUP_NORMAL);
9252 /* Ignore reads from the underlying decl performed during initialization
9253 of the individual variables. If those will be read, we'll mark
9254 the underlying decl as read at that point. */
9255 DECL_READ_P (decl) = save_read;
9257 else if (TREE_CODE (type) == UNION_TYPE)
9259 error_at (loc, "cannot decompose union type %qT", type);
9260 goto error_out;
9262 else if (!CLASS_TYPE_P (type))
9264 error_at (loc, "cannot decompose non-array non-class type %qT", type);
9265 goto error_out;
9267 else if (LAMBDA_TYPE_P (type))
9269 error_at (loc, "cannot decompose lambda closure type %qT", type);
9270 goto error_out;
9272 else if (processing_template_decl && complete_type (type) == error_mark_node)
9273 goto error_out;
9274 else if (processing_template_decl && !COMPLETE_TYPE_P (type))
9275 pedwarn (loc, 0, "structured binding refers to incomplete class type %qT",
9276 type);
9277 else
9279 tree btype = find_decomp_class_base (loc, type, NULL_TREE);
9280 if (btype == error_mark_node)
9281 goto error_out;
9282 else if (btype == NULL_TREE)
9284 error_at (loc, "cannot decompose class type %qT without non-static "
9285 "data members", type);
9286 goto error_out;
9288 for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
9289 if (TREE_CODE (field) != FIELD_DECL
9290 || DECL_ARTIFICIAL (field)
9291 || DECL_UNNAMED_BIT_FIELD (field))
9292 continue;
9293 else
9294 eltscnt++;
9295 if (count != eltscnt)
9296 goto cnt_mismatch;
9297 tree t = dexp;
9298 if (type != btype)
9300 t = convert_to_base (t, btype, /*check_access*/true,
9301 /*nonnull*/false, tf_warning_or_error);
9302 type = btype;
9304 unsigned int i = 0;
9305 for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
9306 if (TREE_CODE (field) != FIELD_DECL
9307 || DECL_ARTIFICIAL (field)
9308 || DECL_UNNAMED_BIT_FIELD (field))
9309 continue;
9310 else
9312 tree tt = finish_non_static_data_member (field, unshare_expr (t),
9313 NULL_TREE);
9314 if (REFERENCE_REF_P (tt))
9315 tt = TREE_OPERAND (tt, 0);
9316 TREE_TYPE (v[i]) = TREE_TYPE (tt);
9317 layout_decl (v[i], 0);
9318 if (!processing_template_decl)
9320 SET_DECL_VALUE_EXPR (v[i], tt);
9321 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9323 i++;
9326 if (processing_template_decl)
9328 for (unsigned int i = 0; i < count; i++)
9329 if (!DECL_HAS_VALUE_EXPR_P (v[i]))
9331 tree a = build_nt (ARRAY_REF, decl, size_int (i),
9332 NULL_TREE, NULL_TREE);
9333 SET_DECL_VALUE_EXPR (v[i], a);
9334 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9339 /* Returns a declaration for a VAR_DECL as if:
9341 extern "C" TYPE NAME;
9343 had been seen. Used to create compiler-generated global
9344 variables. */
9346 static tree
9347 declare_global_var (tree name, tree type)
9349 auto cookie = push_abi_namespace (global_namespace);
9350 tree decl = build_decl (input_location, VAR_DECL, name, type);
9351 TREE_PUBLIC (decl) = 1;
9352 DECL_EXTERNAL (decl) = 1;
9353 DECL_ARTIFICIAL (decl) = 1;
9354 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
9355 /* If the user has explicitly declared this variable (perhaps
9356 because the code we are compiling is part of a low-level runtime
9357 library), then it is possible that our declaration will be merged
9358 with theirs by pushdecl. */
9359 decl = pushdecl (decl);
9360 cp_finish_decl (decl, NULL_TREE, false, NULL_TREE, 0);
9361 pop_abi_namespace (cookie, global_namespace);
9363 return decl;
9366 /* Returns the type for the argument to "__cxa_atexit" (or "atexit",
9367 if "__cxa_atexit" is not being used) corresponding to the function
9368 to be called when the program exits. */
9370 static tree
9371 get_atexit_fn_ptr_type (void)
9373 tree fn_type;
9375 if (!atexit_fn_ptr_type_node)
9377 tree arg_type;
9378 if (flag_use_cxa_atexit
9379 && !targetm.cxx.use_atexit_for_cxa_atexit ())
9380 /* The parameter to "__cxa_atexit" is "void (*)(void *)". */
9381 arg_type = ptr_type_node;
9382 else
9383 /* The parameter to "atexit" is "void (*)(void)". */
9384 arg_type = NULL_TREE;
9386 fn_type = build_function_type_list (void_type_node,
9387 arg_type, NULL_TREE);
9388 atexit_fn_ptr_type_node = build_pointer_type (fn_type);
9391 return atexit_fn_ptr_type_node;
9394 /* Returns a pointer to the `atexit' function. Note that if
9395 FLAG_USE_CXA_ATEXIT is nonzero, then this will actually be the new
9396 `__cxa_atexit' function specified in the IA64 C++ ABI. */
9398 static tree
9399 get_atexit_node (void)
9401 tree atexit_fndecl;
9402 tree fn_type;
9403 tree fn_ptr_type;
9404 const char *name;
9405 bool use_aeabi_atexit;
9406 tree ctx = global_namespace;
9408 if (atexit_node)
9409 return atexit_node;
9411 if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
9413 /* The declaration for `__cxa_atexit' is:
9415 int __cxa_atexit (void (*)(void *), void *, void *)
9417 We build up the argument types and then the function type
9418 itself. */
9419 tree argtype0, argtype1, argtype2;
9421 use_aeabi_atexit = targetm.cxx.use_aeabi_atexit ();
9422 /* First, build the pointer-to-function type for the first
9423 argument. */
9424 fn_ptr_type = get_atexit_fn_ptr_type ();
9425 /* Then, build the rest of the argument types. */
9426 argtype2 = ptr_type_node;
9427 if (use_aeabi_atexit)
9429 argtype1 = fn_ptr_type;
9430 argtype0 = ptr_type_node;
9432 else
9434 argtype1 = ptr_type_node;
9435 argtype0 = fn_ptr_type;
9437 /* And the final __cxa_atexit type. */
9438 fn_type = build_function_type_list (integer_type_node,
9439 argtype0, argtype1, argtype2,
9440 NULL_TREE);
9441 /* ... which needs noexcept. */
9442 fn_type = build_exception_variant (fn_type, noexcept_true_spec);
9443 if (use_aeabi_atexit)
9445 name = "__aeabi_atexit";
9446 push_to_top_level ();
9447 int n = push_namespace (get_identifier ("__aeabiv1"), false);
9448 ctx = current_namespace;
9449 while (n--)
9450 pop_namespace ();
9451 pop_from_top_level ();
9453 else
9455 name = "__cxa_atexit";
9456 ctx = abi_node;
9459 else
9461 /* The declaration for `atexit' is:
9463 int atexit (void (*)());
9465 We build up the argument types and then the function type
9466 itself. */
9467 fn_ptr_type = get_atexit_fn_ptr_type ();
9468 /* Build the final atexit type. */
9469 fn_type = build_function_type_list (integer_type_node,
9470 fn_ptr_type, NULL_TREE);
9471 /* ... which needs noexcept. */
9472 fn_type = build_exception_variant (fn_type, noexcept_true_spec);
9473 name = "atexit";
9476 /* Now, build the function declaration. */
9477 push_lang_context (lang_name_c);
9478 auto cookie = push_abi_namespace (ctx);
9479 atexit_fndecl = build_library_fn_ptr (name, fn_type, ECF_LEAF | ECF_NOTHROW);
9480 DECL_CONTEXT (atexit_fndecl) = FROB_CONTEXT (current_namespace);
9481 /* Install as hidden builtin so we're (a) more relaxed about
9482 exception spec matching and (b) will not give a confusing location
9483 in diagnostic and (c) won't magically appear in user-visible name
9484 lookups. */
9485 DECL_SOURCE_LOCATION (atexit_fndecl) = BUILTINS_LOCATION;
9486 atexit_fndecl = pushdecl (atexit_fndecl, /*hiding=*/true);
9487 pop_abi_namespace (cookie, ctx);
9488 mark_used (atexit_fndecl);
9489 pop_lang_context ();
9490 atexit_node = decay_conversion (atexit_fndecl, tf_warning_or_error);
9492 return atexit_node;
9495 /* Like get_atexit_node, but for thread-local cleanups. */
9497 static tree
9498 get_thread_atexit_node (void)
9500 /* The declaration for `__cxa_thread_atexit' is:
9502 int __cxa_thread_atexit (void (*)(void *), void *, void *) */
9503 tree fn_type = build_function_type_list (integer_type_node,
9504 get_atexit_fn_ptr_type (),
9505 ptr_type_node, ptr_type_node,
9506 NULL_TREE);
9508 /* Now, build the function declaration. */
9509 tree atexit_fndecl = build_library_fn_ptr ("__cxa_thread_atexit", fn_type,
9510 ECF_LEAF | ECF_NOTHROW);
9511 return decay_conversion (atexit_fndecl, tf_warning_or_error);
9514 /* Returns the __dso_handle VAR_DECL. */
9516 static tree
9517 get_dso_handle_node (void)
9519 if (dso_handle_node)
9520 return dso_handle_node;
9522 /* Declare the variable. */
9523 dso_handle_node = declare_global_var (get_identifier ("__dso_handle"),
9524 ptr_type_node);
9526 #ifdef HAVE_GAS_HIDDEN
9527 if (dso_handle_node != error_mark_node)
9529 DECL_VISIBILITY (dso_handle_node) = VISIBILITY_HIDDEN;
9530 DECL_VISIBILITY_SPECIFIED (dso_handle_node) = 1;
9532 #endif
9534 return dso_handle_node;
9537 /* Begin a new function with internal linkage whose job will be simply
9538 to destroy some particular variable. */
9540 static GTY(()) int start_cleanup_cnt;
9542 static tree
9543 start_cleanup_fn (void)
9545 char name[32];
9547 push_to_top_level ();
9549 /* No need to mangle this. */
9550 push_lang_context (lang_name_c);
9552 /* Build the name of the function. */
9553 sprintf (name, "__tcf_%d", start_cleanup_cnt++);
9554 /* Build the function declaration. */
9555 tree fntype = TREE_TYPE (get_atexit_fn_ptr_type ());
9556 tree fndecl = build_lang_decl (FUNCTION_DECL, get_identifier (name), fntype);
9557 DECL_CONTEXT (fndecl) = FROB_CONTEXT (current_namespace);
9558 /* It's a function with internal linkage, generated by the
9559 compiler. */
9560 TREE_PUBLIC (fndecl) = 0;
9561 DECL_ARTIFICIAL (fndecl) = 1;
9562 /* Make the function `inline' so that it is only emitted if it is
9563 actually needed. It is unlikely that it will be inlined, since
9564 it is only called via a function pointer, but we avoid unnecessary
9565 emissions this way. */
9566 DECL_DECLARED_INLINE_P (fndecl) = 1;
9567 DECL_INTERFACE_KNOWN (fndecl) = 1;
9568 if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
9570 /* Build the parameter. */
9571 tree parmdecl = cp_build_parm_decl (fndecl, NULL_TREE, ptr_type_node);
9572 TREE_USED (parmdecl) = 1;
9573 DECL_READ_P (parmdecl) = 1;
9574 DECL_ARGUMENTS (fndecl) = parmdecl;
9577 fndecl = pushdecl (fndecl, /*hidden=*/true);
9578 start_preparsed_function (fndecl, NULL_TREE, SF_PRE_PARSED);
9580 pop_lang_context ();
9582 return current_function_decl;
9585 /* Finish the cleanup function begun by start_cleanup_fn. */
9587 static void
9588 end_cleanup_fn (void)
9590 expand_or_defer_fn (finish_function (/*inline_p=*/false));
9592 pop_from_top_level ();
9595 /* Generate code to handle the destruction of DECL, an object with
9596 static storage duration. */
9598 tree
9599 register_dtor_fn (tree decl)
9601 tree cleanup;
9602 tree addr;
9603 tree compound_stmt;
9604 tree fcall;
9605 tree type;
9606 bool ob_parm, dso_parm, use_dtor;
9607 tree arg0, arg1, arg2;
9608 tree atex_node;
9610 type = TREE_TYPE (decl);
9611 if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
9612 return void_node;
9614 if (decl_maybe_constant_destruction (decl, type)
9615 && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
9617 cxx_maybe_build_cleanup (decl, tf_warning_or_error);
9618 return void_node;
9621 /* If we're using "__cxa_atexit" (or "__cxa_thread_atexit" or
9622 "__aeabi_atexit"), and DECL is a class object, we can just pass the
9623 destructor to "__cxa_atexit"; we don't have to build a temporary
9624 function to do the cleanup. */
9625 dso_parm = (flag_use_cxa_atexit
9626 && !targetm.cxx.use_atexit_for_cxa_atexit ());
9627 ob_parm = (CP_DECL_THREAD_LOCAL_P (decl) || dso_parm);
9628 use_dtor = ob_parm && CLASS_TYPE_P (type);
9629 if (use_dtor)
9631 cleanup = get_class_binding (type, complete_dtor_identifier);
9633 /* Make sure it is accessible. */
9634 perform_or_defer_access_check (TYPE_BINFO (type), cleanup, cleanup,
9635 tf_warning_or_error);
9637 else
9639 /* Call build_cleanup before we enter the anonymous function so
9640 that any access checks will be done relative to the current
9641 scope, rather than the scope of the anonymous function. */
9642 build_cleanup (decl);
9644 /* Now start the function. */
9645 cleanup = start_cleanup_fn ();
9647 /* Now, recompute the cleanup. It may contain SAVE_EXPRs that refer
9648 to the original function, rather than the anonymous one. That
9649 will make the back end think that nested functions are in use,
9650 which causes confusion. */
9651 push_deferring_access_checks (dk_no_check);
9652 fcall = build_cleanup (decl);
9653 pop_deferring_access_checks ();
9655 /* Create the body of the anonymous function. */
9656 compound_stmt = begin_compound_stmt (BCS_FN_BODY);
9657 finish_expr_stmt (fcall);
9658 finish_compound_stmt (compound_stmt);
9659 end_cleanup_fn ();
9662 /* Call atexit with the cleanup function. */
9663 mark_used (cleanup);
9664 cleanup = build_address (cleanup);
9666 if (CP_DECL_THREAD_LOCAL_P (decl))
9667 atex_node = get_thread_atexit_node ();
9668 else
9669 atex_node = get_atexit_node ();
9671 if (use_dtor)
9673 /* We must convert CLEANUP to the type that "__cxa_atexit"
9674 expects. */
9675 cleanup = build_nop (get_atexit_fn_ptr_type (), cleanup);
9676 /* "__cxa_atexit" will pass the address of DECL to the
9677 cleanup function. */
9678 mark_used (decl);
9679 addr = build_address (decl);
9680 /* The declared type of the parameter to "__cxa_atexit" is
9681 "void *". For plain "T*", we could just let the
9682 machinery in cp_build_function_call convert it -- but if the
9683 type is "cv-qualified T *", then we need to convert it
9684 before passing it in, to avoid spurious errors. */
9685 addr = build_nop (ptr_type_node, addr);
9687 else
9688 /* Since the cleanup functions we build ignore the address
9689 they're given, there's no reason to pass the actual address
9690 in, and, in general, it's cheaper to pass NULL than any
9691 other value. */
9692 addr = null_pointer_node;
9694 if (dso_parm)
9695 arg2 = cp_build_addr_expr (get_dso_handle_node (),
9696 tf_warning_or_error);
9697 else if (ob_parm)
9698 /* Just pass NULL to the dso handle parm if we don't actually
9699 have a DSO handle on this target. */
9700 arg2 = null_pointer_node;
9701 else
9702 arg2 = NULL_TREE;
9704 if (ob_parm)
9706 if (!CP_DECL_THREAD_LOCAL_P (decl)
9707 && targetm.cxx.use_aeabi_atexit ())
9709 arg1 = cleanup;
9710 arg0 = addr;
9712 else
9714 arg1 = addr;
9715 arg0 = cleanup;
9718 else
9720 arg0 = cleanup;
9721 arg1 = NULL_TREE;
9723 return cp_build_function_call_nary (atex_node, tf_warning_or_error,
9724 arg0, arg1, arg2, NULL_TREE);
9727 /* DECL is a VAR_DECL with static storage duration. INIT, if present,
9728 is its initializer. Generate code to handle the construction
9729 and destruction of DECL. */
9731 static void
9732 expand_static_init (tree decl, tree init)
9734 gcc_assert (VAR_P (decl));
9735 gcc_assert (TREE_STATIC (decl));
9737 /* Some variables require no dynamic initialization. */
9738 if (decl_maybe_constant_destruction (decl, TREE_TYPE (decl)))
9740 /* Make sure the destructor is callable. */
9741 cxx_maybe_build_cleanup (decl, tf_warning_or_error);
9742 if (!init)
9743 return;
9746 if (CP_DECL_THREAD_LOCAL_P (decl) && DECL_GNU_TLS_P (decl)
9747 && !DECL_FUNCTION_SCOPE_P (decl))
9749 location_t dloc = DECL_SOURCE_LOCATION (decl);
9750 if (init)
9751 error_at (dloc, "non-local variable %qD declared %<__thread%> "
9752 "needs dynamic initialization", decl);
9753 else
9754 error_at (dloc, "non-local variable %qD declared %<__thread%> "
9755 "has a non-trivial destructor", decl);
9756 static bool informed;
9757 if (!informed)
9759 inform (dloc, "C++11 %<thread_local%> allows dynamic "
9760 "initialization and destruction");
9761 informed = true;
9763 return;
9766 if (DECL_FUNCTION_SCOPE_P (decl))
9768 /* Emit code to perform this initialization but once. */
9769 tree if_stmt = NULL_TREE, inner_if_stmt = NULL_TREE;
9770 tree then_clause = NULL_TREE, inner_then_clause = NULL_TREE;
9771 tree guard, guard_addr;
9772 tree flag, begin;
9773 /* We don't need thread-safety code for thread-local vars. */
9774 bool thread_guard = (flag_threadsafe_statics
9775 && !CP_DECL_THREAD_LOCAL_P (decl));
9777 /* Emit code to perform this initialization but once. This code
9778 looks like:
9780 static <type> guard;
9781 if (!__atomic_load (guard.first_byte)) {
9782 if (__cxa_guard_acquire (&guard)) {
9783 bool flag = false;
9784 try {
9785 // Do initialization.
9786 flag = true; __cxa_guard_release (&guard);
9787 // Register variable for destruction at end of program.
9788 } catch {
9789 if (!flag) __cxa_guard_abort (&guard);
9794 Note that the `flag' variable is only set to 1 *after* the
9795 initialization is complete. This ensures that an exception,
9796 thrown during the construction, will cause the variable to
9797 reinitialized when we pass through this code again, as per:
9799 [stmt.dcl]
9801 If the initialization exits by throwing an exception, the
9802 initialization is not complete, so it will be tried again
9803 the next time control enters the declaration.
9805 This process should be thread-safe, too; multiple threads
9806 should not be able to initialize the variable more than
9807 once. */
9809 /* Create the guard variable. */
9810 guard = get_guard (decl);
9812 /* Begin the conditional initialization. */
9813 if_stmt = begin_if_stmt ();
9815 finish_if_stmt_cond (get_guard_cond (guard, thread_guard), if_stmt);
9816 then_clause = begin_compound_stmt (BCS_NO_SCOPE);
9818 if (thread_guard)
9820 tree vfntype = NULL_TREE;
9821 tree acquire_name, release_name, abort_name;
9822 tree acquire_fn, release_fn, abort_fn;
9823 guard_addr = build_address (guard);
9825 acquire_name = get_identifier ("__cxa_guard_acquire");
9826 release_name = get_identifier ("__cxa_guard_release");
9827 abort_name = get_identifier ("__cxa_guard_abort");
9828 acquire_fn = get_global_binding (acquire_name);
9829 release_fn = get_global_binding (release_name);
9830 abort_fn = get_global_binding (abort_name);
9831 if (!acquire_fn)
9832 acquire_fn = push_library_fn
9833 (acquire_name, build_function_type_list (integer_type_node,
9834 TREE_TYPE (guard_addr),
9835 NULL_TREE),
9836 NULL_TREE, ECF_NOTHROW);
9837 if (!release_fn || !abort_fn)
9838 vfntype = build_function_type_list (void_type_node,
9839 TREE_TYPE (guard_addr),
9840 NULL_TREE);
9841 if (!release_fn)
9842 release_fn = push_library_fn (release_name, vfntype, NULL_TREE,
9843 ECF_NOTHROW);
9844 if (!abort_fn)
9845 abort_fn = push_library_fn (abort_name, vfntype, NULL_TREE,
9846 ECF_NOTHROW | ECF_LEAF);
9848 inner_if_stmt = begin_if_stmt ();
9849 finish_if_stmt_cond (build_call_n (acquire_fn, 1, guard_addr),
9850 inner_if_stmt);
9852 inner_then_clause = begin_compound_stmt (BCS_NO_SCOPE);
9853 begin = get_target_expr (boolean_false_node);
9854 flag = TARGET_EXPR_SLOT (begin);
9856 TARGET_EXPR_CLEANUP (begin)
9857 = build3 (COND_EXPR, void_type_node, flag,
9858 void_node,
9859 build_call_n (abort_fn, 1, guard_addr));
9860 CLEANUP_EH_ONLY (begin) = 1;
9862 /* Do the initialization itself. */
9863 init = add_stmt_to_compound (begin, init);
9864 init = add_stmt_to_compound (init,
9865 build2 (MODIFY_EXPR, void_type_node,
9866 flag, boolean_true_node));
9868 /* Use atexit to register a function for destroying this static
9869 variable. Do this before calling __cxa_guard_release. */
9870 init = add_stmt_to_compound (init, register_dtor_fn (decl));
9872 init = add_stmt_to_compound (init, build_call_n (release_fn, 1,
9873 guard_addr));
9875 else
9877 init = add_stmt_to_compound (init, set_guard (guard));
9879 /* Use atexit to register a function for destroying this static
9880 variable. */
9881 init = add_stmt_to_compound (init, register_dtor_fn (decl));
9884 finish_expr_stmt (init);
9886 if (thread_guard)
9888 finish_compound_stmt (inner_then_clause);
9889 finish_then_clause (inner_if_stmt);
9890 finish_if_stmt (inner_if_stmt);
9893 finish_compound_stmt (then_clause);
9894 finish_then_clause (if_stmt);
9895 finish_if_stmt (if_stmt);
9897 else if (CP_DECL_THREAD_LOCAL_P (decl))
9898 tls_aggregates = tree_cons (init, decl, tls_aggregates);
9899 else
9900 static_aggregates = tree_cons (init, decl, static_aggregates);
9904 /* Make TYPE a complete type based on INITIAL_VALUE.
9905 Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
9906 2 if there was no information (in which case assume 0 if DO_DEFAULT),
9907 3 if the initializer list is empty (in pedantic mode). */
9910 cp_complete_array_type (tree *ptype, tree initial_value, bool do_default)
9912 int failure;
9913 tree type, elt_type;
9915 /* Don't get confused by a CONSTRUCTOR for some other type. */
9916 if (initial_value && TREE_CODE (initial_value) == CONSTRUCTOR
9917 && !BRACE_ENCLOSED_INITIALIZER_P (initial_value)
9918 && TREE_CODE (TREE_TYPE (initial_value)) != ARRAY_TYPE)
9919 return 1;
9921 if (initial_value)
9923 /* An array of character type can be initialized from a
9924 brace-enclosed string constant so call reshape_init to
9925 remove the optional braces from a braced string literal. */
9926 if (char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (*ptype)))
9927 && BRACE_ENCLOSED_INITIALIZER_P (initial_value))
9928 initial_value = reshape_init (*ptype, initial_value,
9929 tf_warning_or_error);
9931 /* If any of the elements are parameter packs, we can't actually
9932 complete this type now because the array size is dependent. */
9933 if (TREE_CODE (initial_value) == CONSTRUCTOR)
9934 for (auto &e: CONSTRUCTOR_ELTS (initial_value))
9935 if (PACK_EXPANSION_P (e.value))
9936 return 0;
9939 failure = complete_array_type (ptype, initial_value, do_default);
9941 /* We can create the array before the element type is complete, which
9942 means that we didn't have these two bits set in the original type
9943 either. In completing the type, we are expected to propagate these
9944 bits. See also complete_type which does the same thing for arrays
9945 of fixed size. */
9946 type = *ptype;
9947 if (type != error_mark_node && TYPE_DOMAIN (type))
9949 elt_type = TREE_TYPE (type);
9950 TYPE_NEEDS_CONSTRUCTING (type) = TYPE_NEEDS_CONSTRUCTING (elt_type);
9951 TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
9952 = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (elt_type);
9955 return failure;
9958 /* As above, but either give an error or reject zero-size arrays, depending
9959 on COMPLAIN. */
9962 cp_complete_array_type_or_error (tree *ptype, tree initial_value,
9963 bool do_default, tsubst_flags_t complain)
9965 int failure;
9966 bool sfinae = !(complain & tf_error);
9967 /* In SFINAE context we can't be lenient about zero-size arrays. */
9968 if (sfinae)
9969 ++pedantic;
9970 failure = cp_complete_array_type (ptype, initial_value, do_default);
9971 if (sfinae)
9972 --pedantic;
9973 if (failure)
9975 if (sfinae)
9976 /* Not an error. */;
9977 else if (failure == 1)
9978 error ("initializer fails to determine size of %qT", *ptype);
9979 else if (failure == 2)
9981 if (do_default)
9982 error ("array size missing in %qT", *ptype);
9984 else if (failure == 3)
9985 error ("zero-size array %qT", *ptype);
9986 *ptype = error_mark_node;
9988 return failure;
9991 /* Return zero if something is declared to be a member of type
9992 CTYPE when in the context of CUR_TYPE. STRING is the error
9993 message to print in that case. Otherwise, quietly return 1. */
9995 static int
9996 member_function_or_else (tree ctype, tree cur_type, enum overload_flags flags)
9998 if (ctype && ctype != cur_type)
10000 if (flags == DTOR_FLAG)
10001 error ("destructor for alien class %qT cannot be a member", ctype);
10002 else
10003 error ("constructor for alien class %qT cannot be a member", ctype);
10004 return 0;
10006 return 1;
10009 /* Subroutine of `grokdeclarator'. */
10011 /* Generate errors possibly applicable for a given set of specifiers.
10012 This is for ARM $7.1.2. */
10014 static void
10015 bad_specifiers (tree object,
10016 enum bad_spec_place type,
10017 int virtualp,
10018 int quals,
10019 int inlinep,
10020 int friendp,
10021 int raises,
10022 const location_t* locations)
10024 switch (type)
10026 case BSP_VAR:
10027 if (virtualp)
10028 error_at (locations[ds_virtual],
10029 "%qD declared as a %<virtual%> variable", object);
10030 if (quals)
10031 error ("%<const%> and %<volatile%> function specifiers on "
10032 "%qD invalid in variable declaration", object);
10033 break;
10034 case BSP_PARM:
10035 if (virtualp)
10036 error_at (locations[ds_virtual],
10037 "%qD declared as a %<virtual%> parameter", object);
10038 if (inlinep)
10039 error_at (locations[ds_inline],
10040 "%qD declared as an %<inline%> parameter", object);
10041 if (quals)
10042 error ("%<const%> and %<volatile%> function specifiers on "
10043 "%qD invalid in parameter declaration", object);
10044 break;
10045 case BSP_TYPE:
10046 if (virtualp)
10047 error_at (locations[ds_virtual],
10048 "%qD declared as a %<virtual%> type", object);
10049 if (inlinep)
10050 error_at (locations[ds_inline],
10051 "%qD declared as an %<inline%> type", object);
10052 if (quals)
10053 error ("%<const%> and %<volatile%> function specifiers on "
10054 "%qD invalid in type declaration", object);
10055 break;
10056 case BSP_FIELD:
10057 if (virtualp)
10058 error_at (locations[ds_virtual],
10059 "%qD declared as a %<virtual%> field", object);
10060 if (inlinep)
10061 error_at (locations[ds_inline],
10062 "%qD declared as an %<inline%> field", object);
10063 if (quals)
10064 error ("%<const%> and %<volatile%> function specifiers on "
10065 "%qD invalid in field declaration", object);
10066 break;
10067 default:
10068 gcc_unreachable();
10070 if (friendp)
10071 error ("%q+D declared as a friend", object);
10072 if (raises
10073 && !flag_noexcept_type
10074 && (TREE_CODE (object) == TYPE_DECL
10075 || (!TYPE_PTRFN_P (TREE_TYPE (object))
10076 && !TYPE_REFFN_P (TREE_TYPE (object))
10077 && !TYPE_PTRMEMFUNC_P (TREE_TYPE (object)))))
10078 error ("%q+D declared with an exception specification", object);
10081 /* DECL is a member function or static data member and is presently
10082 being defined. Check that the definition is taking place in a
10083 valid namespace. */
10085 static void
10086 check_class_member_definition_namespace (tree decl)
10088 /* These checks only apply to member functions and static data
10089 members. */
10090 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
10091 /* We check for problems with specializations in pt.cc in
10092 check_specialization_namespace, where we can issue better
10093 diagnostics. */
10094 if (processing_specialization)
10095 return;
10096 /* We check this in check_explicit_instantiation_namespace. */
10097 if (processing_explicit_instantiation)
10098 return;
10099 /* [class.mfct]
10101 A member function definition that appears outside of the
10102 class definition shall appear in a namespace scope enclosing
10103 the class definition.
10105 [class.static.data]
10107 The definition for a static data member shall appear in a
10108 namespace scope enclosing the member's class definition. */
10109 if (!is_ancestor (current_namespace, DECL_CONTEXT (decl)))
10110 permerror (input_location, "definition of %qD is not in namespace enclosing %qT",
10111 decl, DECL_CONTEXT (decl));
10114 /* Build a PARM_DECL for the "this" parameter of FN. TYPE is the
10115 METHOD_TYPE for a non-static member function; QUALS are the
10116 cv-qualifiers that apply to the function. */
10118 tree
10119 build_this_parm (tree fn, tree type, cp_cv_quals quals)
10121 tree this_type;
10122 tree qual_type;
10123 tree parm;
10124 cp_cv_quals this_quals;
10126 if (CLASS_TYPE_P (type))
10128 this_type
10129 = cp_build_qualified_type (type, quals & ~TYPE_QUAL_RESTRICT);
10130 this_type = build_pointer_type (this_type);
10132 else
10133 this_type = type_of_this_parm (type);
10134 /* The `this' parameter is implicitly `const'; it cannot be
10135 assigned to. */
10136 this_quals = (quals & TYPE_QUAL_RESTRICT) | TYPE_QUAL_CONST;
10137 qual_type = cp_build_qualified_type (this_type, this_quals);
10138 parm = build_artificial_parm (fn, this_identifier, qual_type);
10139 cp_apply_type_quals_to_decl (this_quals, parm);
10140 return parm;
10143 /* DECL is a static member function. Complain if it was declared
10144 with function-cv-quals. */
10146 static void
10147 check_static_quals (tree decl, cp_cv_quals quals)
10149 if (quals != TYPE_UNQUALIFIED)
10150 error ("static member function %q#D declared with type qualifiers",
10151 decl);
10154 // Check that FN takes no arguments and returns bool.
10155 static void
10156 check_concept_fn (tree fn)
10158 // A constraint is nullary.
10159 if (DECL_ARGUMENTS (fn))
10160 error_at (DECL_SOURCE_LOCATION (fn),
10161 "concept %q#D declared with function parameters", fn);
10163 // The declared return type of the concept shall be bool, and
10164 // it shall not be deduced from it definition.
10165 tree type = TREE_TYPE (TREE_TYPE (fn));
10166 if (is_auto (type))
10167 error_at (DECL_SOURCE_LOCATION (fn),
10168 "concept %q#D declared with a deduced return type", fn);
10169 else if (type != boolean_type_node)
10170 error_at (DECL_SOURCE_LOCATION (fn),
10171 "concept %q#D with non-%<bool%> return type %qT", fn, type);
10174 /* Helper function. Replace the temporary this parameter injected
10175 during cp_finish_omp_declare_simd with the real this parameter. */
10177 static tree
10178 declare_simd_adjust_this (tree *tp, int *walk_subtrees, void *data)
10180 tree this_parm = (tree) data;
10181 if (TREE_CODE (*tp) == PARM_DECL
10182 && DECL_NAME (*tp) == this_identifier
10183 && *tp != this_parm)
10184 *tp = this_parm;
10185 else if (TYPE_P (*tp))
10186 *walk_subtrees = 0;
10187 return NULL_TREE;
10190 /* CTYPE is class type, or null if non-class.
10191 TYPE is type this FUNCTION_DECL should have, either FUNCTION_TYPE
10192 or METHOD_TYPE.
10193 DECLARATOR is the function's name.
10194 PARMS is a chain of PARM_DECLs for the function.
10195 VIRTUALP is truthvalue of whether the function is virtual or not.
10196 FLAGS are to be passed through to `grokclassfn'.
10197 QUALS are qualifiers indicating whether the function is `const'
10198 or `volatile'.
10199 RAISES is a list of exceptions that this function can raise.
10200 CHECK is 1 if we must find this method in CTYPE, 0 if we should
10201 not look, and -1 if we should not call `grokclassfn' at all.
10203 SFK is the kind of special function (if any) for the new function.
10205 Returns `NULL_TREE' if something goes wrong, after issuing
10206 applicable error messages. */
10208 static tree
10209 grokfndecl (tree ctype,
10210 tree type,
10211 tree declarator,
10212 tree parms,
10213 tree orig_declarator,
10214 const cp_decl_specifier_seq *declspecs,
10215 tree decl_reqs,
10216 int virtualp,
10217 enum overload_flags flags,
10218 cp_cv_quals quals,
10219 cp_ref_qualifier rqual,
10220 tree raises,
10221 int check,
10222 int friendp,
10223 int publicp,
10224 int inlinep,
10225 bool deletedp,
10226 special_function_kind sfk,
10227 bool funcdef_flag,
10228 bool late_return_type_p,
10229 int template_count,
10230 tree in_namespace,
10231 tree* attrlist,
10232 location_t location)
10234 tree decl;
10235 int staticp = ctype && TREE_CODE (type) == FUNCTION_TYPE;
10236 tree t;
10238 if (location == UNKNOWN_LOCATION)
10239 location = input_location;
10241 /* Was the concept specifier present? */
10242 bool concept_p = inlinep & 4;
10244 /* Concept declarations must have a corresponding definition. */
10245 if (concept_p && !funcdef_flag)
10247 error_at (location, "concept %qD has no definition", declarator);
10248 return NULL_TREE;
10251 type = build_cp_fntype_variant (type, rqual, raises, late_return_type_p);
10253 decl = build_lang_decl_loc (location, FUNCTION_DECL, declarator, type);
10255 /* Set the constraints on the declaration. */
10256 if (flag_concepts)
10258 tree tmpl_reqs = NULL_TREE;
10259 tree ctx = friendp ? current_class_type : ctype;
10260 bool block_local = TREE_CODE (current_scope ()) == FUNCTION_DECL;
10261 bool memtmpl = (!block_local
10262 && (current_template_depth
10263 > template_class_depth (ctx)));
10264 if (memtmpl)
10266 if (!current_template_parms)
10267 /* If there are no template parameters, something must have
10268 gone wrong. */
10269 gcc_assert (seen_error ());
10270 else
10271 tmpl_reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
10273 tree ci = build_constraints (tmpl_reqs, decl_reqs);
10274 if (concept_p && ci)
10276 error_at (location, "a function concept cannot be constrained");
10277 ci = NULL_TREE;
10279 /* C++20 CA378: Remove non-templated constrained functions. */
10280 if (ci
10281 && (block_local
10282 || (!flag_concepts_ts
10283 && (!processing_template_decl
10284 || (friendp && !memtmpl && !funcdef_flag)))))
10286 error_at (location, "constraints on a non-templated function");
10287 ci = NULL_TREE;
10289 set_constraints (decl, ci);
10292 if (TREE_CODE (type) == METHOD_TYPE)
10294 tree parm = build_this_parm (decl, type, quals);
10295 DECL_CHAIN (parm) = parms;
10296 parms = parm;
10298 /* Allocate space to hold the vptr bit if needed. */
10299 SET_DECL_ALIGN (decl, MINIMUM_METHOD_BOUNDARY);
10302 DECL_ARGUMENTS (decl) = parms;
10303 for (t = parms; t; t = DECL_CHAIN (t))
10304 DECL_CONTEXT (t) = decl;
10306 /* Propagate volatile out from type to decl. */
10307 if (TYPE_VOLATILE (type))
10308 TREE_THIS_VOLATILE (decl) = 1;
10310 /* Setup decl according to sfk. */
10311 switch (sfk)
10313 case sfk_constructor:
10314 case sfk_copy_constructor:
10315 case sfk_move_constructor:
10316 DECL_CXX_CONSTRUCTOR_P (decl) = 1;
10317 DECL_NAME (decl) = ctor_identifier;
10318 break;
10319 case sfk_destructor:
10320 DECL_CXX_DESTRUCTOR_P (decl) = 1;
10321 DECL_NAME (decl) = dtor_identifier;
10322 break;
10323 default:
10324 break;
10327 if (friendp && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)
10329 if (funcdef_flag)
10330 error_at (location,
10331 "defining explicit specialization %qD in friend declaration",
10332 orig_declarator);
10333 else
10335 tree fns = TREE_OPERAND (orig_declarator, 0);
10336 tree args = TREE_OPERAND (orig_declarator, 1);
10338 if (PROCESSING_REAL_TEMPLATE_DECL_P ())
10340 /* Something like `template <class T> friend void f<T>()'. */
10341 error_at (location,
10342 "invalid use of template-id %qD in declaration "
10343 "of primary template",
10344 orig_declarator);
10345 return NULL_TREE;
10348 /* A friend declaration of the form friend void f<>(). Record
10349 the information in the TEMPLATE_ID_EXPR. */
10350 SET_DECL_IMPLICIT_INSTANTIATION (decl);
10352 gcc_assert (identifier_p (fns) || OVL_P (fns));
10353 DECL_TEMPLATE_INFO (decl) = build_template_info (fns, args);
10355 for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
10356 if (TREE_PURPOSE (t)
10357 && TREE_CODE (TREE_PURPOSE (t)) == DEFERRED_PARSE)
10359 error_at (defparse_location (TREE_PURPOSE (t)),
10360 "default arguments are not allowed in declaration "
10361 "of friend template specialization %qD",
10362 decl);
10363 return NULL_TREE;
10366 if (inlinep & 1)
10368 error_at (declspecs->locations[ds_inline],
10369 "%<inline%> is not allowed in declaration of friend "
10370 "template specialization %qD",
10371 decl);
10372 return NULL_TREE;
10377 /* C++17 11.3.6/4: "If a friend declaration specifies a default argument
10378 expression, that declaration shall be a definition..." */
10379 if (friendp && !funcdef_flag)
10381 for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
10382 t && t != void_list_node; t = TREE_CHAIN (t))
10383 if (TREE_PURPOSE (t))
10385 permerror (DECL_SOURCE_LOCATION (decl),
10386 "friend declaration of %qD specifies default "
10387 "arguments and isn%'t a definition", decl);
10388 break;
10392 /* If this decl has namespace scope, set that up. */
10393 if (in_namespace)
10394 set_decl_namespace (decl, in_namespace, friendp);
10395 else if (ctype)
10396 DECL_CONTEXT (decl) = ctype;
10397 else
10398 DECL_CONTEXT (decl) = FROB_CONTEXT (current_decl_namespace ());
10400 /* `main' and builtins have implicit 'C' linkage. */
10401 if (ctype == NULL_TREE
10402 && DECL_FILE_SCOPE_P (decl)
10403 && current_lang_name == lang_name_cplusplus
10404 && (MAIN_NAME_P (declarator)
10405 || (IDENTIFIER_LENGTH (declarator) > 10
10406 && IDENTIFIER_POINTER (declarator)[0] == '_'
10407 && IDENTIFIER_POINTER (declarator)[1] == '_'
10408 && startswith (IDENTIFIER_POINTER (declarator) + 2,
10409 "builtin_"))
10410 || (targetcm.cxx_implicit_extern_c
10411 && (targetcm.cxx_implicit_extern_c
10412 (IDENTIFIER_POINTER (declarator))))))
10413 SET_DECL_LANGUAGE (decl, lang_c);
10415 /* Should probably propagate const out from type to decl I bet (mrs). */
10416 if (staticp)
10418 DECL_STATIC_FUNCTION_P (decl) = 1;
10419 DECL_CONTEXT (decl) = ctype;
10422 if (deletedp)
10423 DECL_DELETED_FN (decl) = 1;
10425 if (ctype && funcdef_flag)
10426 check_class_member_definition_namespace (decl);
10428 if (ctype == NULL_TREE && DECL_MAIN_P (decl))
10430 if (PROCESSING_REAL_TEMPLATE_DECL_P())
10431 error_at (location, "cannot declare %<::main%> to be a template");
10432 if (inlinep & 1)
10433 error_at (declspecs->locations[ds_inline],
10434 "cannot declare %<::main%> to be inline");
10435 if (inlinep & 2)
10436 error_at (declspecs->locations[ds_constexpr],
10437 "cannot declare %<::main%> to be %qs", "constexpr");
10438 if (inlinep & 8)
10439 error_at (declspecs->locations[ds_consteval],
10440 "cannot declare %<::main%> to be %qs", "consteval");
10441 if (!publicp)
10442 error_at (location, "cannot declare %<::main%> to be static");
10443 inlinep = 0;
10444 publicp = 1;
10447 /* Members of anonymous types and local classes have no linkage; make
10448 them internal. If a typedef is made later, this will be changed. */
10449 if (ctype && (!TREE_PUBLIC (TYPE_MAIN_DECL (ctype))
10450 || decl_function_context (TYPE_MAIN_DECL (ctype))))
10451 publicp = 0;
10453 if (publicp && cxx_dialect == cxx98)
10455 /* [basic.link]: A name with no linkage (notably, the name of a class
10456 or enumeration declared in a local scope) shall not be used to
10457 declare an entity with linkage.
10459 DR 757 relaxes this restriction for C++0x. */
10460 no_linkage_error (decl);
10463 TREE_PUBLIC (decl) = publicp;
10464 if (! publicp)
10466 DECL_INTERFACE_KNOWN (decl) = 1;
10467 DECL_NOT_REALLY_EXTERN (decl) = 1;
10470 /* If the declaration was declared inline, mark it as such. */
10471 if (inlinep)
10473 DECL_DECLARED_INLINE_P (decl) = 1;
10474 if (publicp)
10475 DECL_COMDAT (decl) = 1;
10477 if (inlinep & 2)
10478 DECL_DECLARED_CONSTEXPR_P (decl) = true;
10479 else if (inlinep & 8)
10481 DECL_DECLARED_CONSTEXPR_P (decl) = true;
10482 SET_DECL_IMMEDIATE_FUNCTION_P (decl);
10485 // If the concept declaration specifier was found, check
10486 // that the declaration satisfies the necessary requirements.
10487 if (concept_p)
10489 DECL_DECLARED_CONCEPT_P (decl) = true;
10490 check_concept_fn (decl);
10493 DECL_EXTERNAL (decl) = 1;
10494 if (TREE_CODE (type) == FUNCTION_TYPE)
10496 if (quals || rqual)
10497 TREE_TYPE (decl) = apply_memfn_quals (TREE_TYPE (decl),
10498 TYPE_UNQUALIFIED,
10499 REF_QUAL_NONE);
10501 if (quals)
10503 error (ctype
10504 ? G_("static member function %qD cannot have cv-qualifier")
10505 : G_("non-member function %qD cannot have cv-qualifier"),
10506 decl);
10507 quals = TYPE_UNQUALIFIED;
10510 if (rqual)
10512 error (ctype
10513 ? G_("static member function %qD cannot have ref-qualifier")
10514 : G_("non-member function %qD cannot have ref-qualifier"),
10515 decl);
10516 rqual = REF_QUAL_NONE;
10520 if (deduction_guide_p (decl))
10522 tree type = TREE_TYPE (DECL_NAME (decl));
10523 if (in_namespace == NULL_TREE
10524 && CP_DECL_CONTEXT (decl) != CP_TYPE_CONTEXT (type))
10526 error_at (location, "deduction guide %qD must be declared in the "
10527 "same scope as %qT", decl, type);
10528 inform (location_of (type), " declared here");
10529 return NULL_TREE;
10531 if (DECL_CLASS_SCOPE_P (decl)
10532 && current_access_specifier != declared_access (TYPE_NAME (type)))
10534 error_at (location, "deduction guide %qD must have the same access "
10535 "as %qT", decl, type);
10536 inform (location_of (type), " declared here");
10538 if (funcdef_flag)
10539 error_at (location,
10540 "deduction guide %qD must not have a function body", decl);
10542 else if (IDENTIFIER_ANY_OP_P (DECL_NAME (decl))
10543 && !grok_op_properties (decl, /*complain=*/true))
10544 return NULL_TREE;
10545 else if (UDLIT_OPER_P (DECL_NAME (decl)))
10547 bool long_long_unsigned_p;
10548 bool long_double_p;
10549 const char *suffix = NULL;
10550 /* [over.literal]/6: Literal operators shall not have C linkage. */
10551 if (DECL_LANGUAGE (decl) == lang_c)
10553 error_at (location, "literal operator with C linkage");
10554 maybe_show_extern_c_location ();
10555 return NULL_TREE;
10558 if (DECL_NAMESPACE_SCOPE_P (decl))
10560 if (!check_literal_operator_args (decl, &long_long_unsigned_p,
10561 &long_double_p))
10563 error_at (location, "%qD has invalid argument list", decl);
10564 return NULL_TREE;
10567 suffix = UDLIT_OP_SUFFIX (DECL_NAME (decl));
10568 if (long_long_unsigned_p)
10570 if (cpp_interpret_int_suffix (parse_in, suffix, strlen (suffix)))
10571 warning_at (location, 0, "integer suffix %qs"
10572 " shadowed by implementation", suffix);
10574 else if (long_double_p)
10576 if (cpp_interpret_float_suffix (parse_in, suffix, strlen (suffix)))
10577 warning_at (location, 0, "floating-point suffix %qs"
10578 " shadowed by implementation", suffix);
10580 /* 17.6.3.3.5 */
10581 if (suffix[0] != '_'
10582 && !current_function_decl && !(friendp && !funcdef_flag))
10583 warning_at (location, OPT_Wliteral_suffix,
10584 "literal operator suffixes not preceded by %<_%>"
10585 " are reserved for future standardization");
10587 else
10589 error_at (location, "%qD must be a non-member function", decl);
10590 return NULL_TREE;
10594 if (funcdef_flag)
10595 /* Make the init_value nonzero so pushdecl knows this is not
10596 tentative. error_mark_node is replaced later with the BLOCK. */
10597 DECL_INITIAL (decl) = error_mark_node;
10599 if (TYPE_NOTHROW_P (type) || nothrow_libfn_p (decl))
10600 TREE_NOTHROW (decl) = 1;
10602 if (flag_openmp || flag_openmp_simd)
10604 /* Adjust "omp declare simd" attributes. */
10605 tree ods = lookup_attribute ("omp declare simd", *attrlist);
10606 if (ods)
10608 tree attr;
10609 for (attr = ods; attr;
10610 attr = lookup_attribute ("omp declare simd", TREE_CHAIN (attr)))
10612 if (TREE_CODE (type) == METHOD_TYPE)
10613 walk_tree (&TREE_VALUE (attr), declare_simd_adjust_this,
10614 DECL_ARGUMENTS (decl), NULL);
10615 if (TREE_VALUE (attr) != NULL_TREE)
10617 tree cl = TREE_VALUE (TREE_VALUE (attr));
10618 cl = c_omp_declare_simd_clauses_to_numbers
10619 (DECL_ARGUMENTS (decl), cl);
10620 if (cl)
10621 TREE_VALUE (TREE_VALUE (attr)) = cl;
10622 else
10623 TREE_VALUE (attr) = NULL_TREE;
10629 /* Caller will do the rest of this. */
10630 if (check < 0)
10631 return decl;
10633 if (ctype != NULL_TREE)
10634 grokclassfn (ctype, decl, flags);
10636 /* 12.4/3 */
10637 if (cxx_dialect >= cxx11
10638 && DECL_DESTRUCTOR_P (decl)
10639 && !TYPE_BEING_DEFINED (DECL_CONTEXT (decl))
10640 && !processing_template_decl)
10641 deduce_noexcept_on_destructor (decl);
10643 set_originating_module (decl);
10645 decl = check_explicit_specialization (orig_declarator, decl,
10646 template_count,
10647 2 * funcdef_flag +
10648 4 * (friendp != 0) +
10649 8 * concept_p,
10650 *attrlist);
10651 if (decl == error_mark_node)
10652 return NULL_TREE;
10654 if (DECL_STATIC_FUNCTION_P (decl))
10655 check_static_quals (decl, quals);
10657 if (attrlist)
10659 cplus_decl_attributes (&decl, *attrlist, 0);
10660 *attrlist = NULL_TREE;
10663 if (DECL_HAS_CONTRACTS_P (decl))
10664 rebuild_postconditions (decl);
10666 /* Check main's type after attributes have been applied. */
10667 if (ctype == NULL_TREE && DECL_MAIN_P (decl))
10669 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
10670 integer_type_node))
10672 tree oldtypeargs = TYPE_ARG_TYPES (TREE_TYPE (decl));
10673 tree newtype;
10674 error_at (declspecs->locations[ds_type_spec],
10675 "%<::main%> must return %<int%>");
10676 newtype = build_function_type (integer_type_node, oldtypeargs);
10677 TREE_TYPE (decl) = newtype;
10679 if (warn_main)
10680 check_main_parameter_types (decl);
10683 if (ctype != NULL_TREE && check)
10685 tree old_decl = check_classfn (ctype, decl,
10686 (current_template_depth
10687 > template_class_depth (ctype))
10688 ? current_template_parms
10689 : NULL_TREE);
10691 if (old_decl == error_mark_node)
10692 return NULL_TREE;
10694 if (old_decl)
10696 tree ok;
10697 tree pushed_scope;
10699 if (TREE_CODE (old_decl) == TEMPLATE_DECL)
10700 /* Because grokfndecl is always supposed to return a
10701 FUNCTION_DECL, we pull out the DECL_TEMPLATE_RESULT
10702 here. We depend on our callers to figure out that its
10703 really a template that's being returned. */
10704 old_decl = DECL_TEMPLATE_RESULT (old_decl);
10706 if (DECL_STATIC_FUNCTION_P (old_decl)
10707 && TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
10709 /* Remove the `this' parm added by grokclassfn. */
10710 revert_static_member_fn (decl);
10711 check_static_quals (decl, quals);
10713 if (DECL_ARTIFICIAL (old_decl))
10715 error ("definition of implicitly-declared %qD", old_decl);
10716 return NULL_TREE;
10718 else if (DECL_DEFAULTED_FN (old_decl))
10720 error ("definition of explicitly-defaulted %q+D", decl);
10721 inform (DECL_SOURCE_LOCATION (old_decl),
10722 "%q#D explicitly defaulted here", old_decl);
10723 return NULL_TREE;
10726 /* Since we've smashed OLD_DECL to its
10727 DECL_TEMPLATE_RESULT, we must do the same to DECL. */
10728 if (TREE_CODE (decl) == TEMPLATE_DECL)
10729 decl = DECL_TEMPLATE_RESULT (decl);
10731 /* Attempt to merge the declarations. This can fail, in
10732 the case of some invalid specialization declarations. */
10733 pushed_scope = push_scope (ctype);
10734 ok = duplicate_decls (decl, old_decl);
10735 if (pushed_scope)
10736 pop_scope (pushed_scope);
10737 if (!ok)
10739 error ("no %q#D member function declared in class %qT",
10740 decl, ctype);
10741 return NULL_TREE;
10743 if (ok == error_mark_node)
10744 return NULL_TREE;
10745 return old_decl;
10749 if (DECL_CONSTRUCTOR_P (decl) && !grok_ctor_properties (ctype, decl))
10750 return NULL_TREE;
10752 if (ctype == NULL_TREE || check)
10753 return decl;
10755 if (virtualp)
10756 DECL_VIRTUAL_P (decl) = 1;
10758 return decl;
10761 /* decl is a FUNCTION_DECL.
10762 specifiers are the parsed virt-specifiers.
10764 Set flags to reflect the virt-specifiers.
10766 Returns decl. */
10768 static tree
10769 set_virt_specifiers (tree decl, cp_virt_specifiers specifiers)
10771 if (decl == NULL_TREE)
10772 return decl;
10773 if (specifiers & VIRT_SPEC_OVERRIDE)
10774 DECL_OVERRIDE_P (decl) = 1;
10775 if (specifiers & VIRT_SPEC_FINAL)
10776 DECL_FINAL_P (decl) = 1;
10777 return decl;
10780 /* DECL is a VAR_DECL for a static data member. Set flags to reflect
10781 the linkage that DECL will receive in the object file. */
10783 static void
10784 set_linkage_for_static_data_member (tree decl)
10786 /* A static data member always has static storage duration and
10787 external linkage. Note that static data members are forbidden in
10788 local classes -- the only situation in which a class has
10789 non-external linkage. */
10790 TREE_PUBLIC (decl) = 1;
10791 TREE_STATIC (decl) = 1;
10792 /* For non-template classes, static data members are always put
10793 out in exactly those files where they are defined, just as
10794 with ordinary namespace-scope variables. */
10795 if (!processing_template_decl)
10796 DECL_INTERFACE_KNOWN (decl) = 1;
10799 /* Create a VAR_DECL named NAME with the indicated TYPE.
10801 If SCOPE is non-NULL, it is the class type or namespace containing
10802 the variable. If SCOPE is NULL, the variable should is created in
10803 the innermost enclosing scope. */
10805 static tree
10806 grokvardecl (tree type,
10807 tree name,
10808 tree orig_declarator,
10809 const cp_decl_specifier_seq *declspecs,
10810 int initialized,
10811 int type_quals,
10812 int inlinep,
10813 bool conceptp,
10814 int template_count,
10815 tree scope,
10816 location_t location)
10818 tree decl;
10819 tree explicit_scope;
10821 gcc_assert (!name || identifier_p (name));
10823 bool constp = (type_quals & TYPE_QUAL_CONST) != 0;
10824 bool volatilep = (type_quals & TYPE_QUAL_VOLATILE) != 0;
10826 /* Compute the scope in which to place the variable, but remember
10827 whether or not that scope was explicitly specified by the user. */
10828 explicit_scope = scope;
10829 if (!scope)
10831 /* An explicit "extern" specifier indicates a namespace-scope
10832 variable. */
10833 if (declspecs->storage_class == sc_extern)
10834 scope = current_decl_namespace ();
10835 else if (!at_function_scope_p ())
10836 scope = current_scope ();
10839 if (scope
10840 && (/* If the variable is a namespace-scope variable declared in a
10841 template, we need DECL_LANG_SPECIFIC. */
10842 (TREE_CODE (scope) == NAMESPACE_DECL && processing_template_decl)
10843 /* Similarly for namespace-scope variables with language linkage
10844 other than C++. */
10845 || (TREE_CODE (scope) == NAMESPACE_DECL
10846 && current_lang_name != lang_name_cplusplus)
10847 /* Similarly for static data members. */
10848 || TYPE_P (scope)
10849 /* Similarly for explicit specializations. */
10850 || (orig_declarator
10851 && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)))
10852 decl = build_lang_decl_loc (location, VAR_DECL, name, type);
10853 else
10854 decl = build_decl (location, VAR_DECL, name, type);
10856 if (explicit_scope && TREE_CODE (explicit_scope) == NAMESPACE_DECL)
10857 set_decl_namespace (decl, explicit_scope, 0);
10858 else
10859 DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
10861 if (declspecs->storage_class == sc_extern)
10863 DECL_THIS_EXTERN (decl) = 1;
10864 DECL_EXTERNAL (decl) = !initialized;
10867 if (DECL_CLASS_SCOPE_P (decl))
10869 set_linkage_for_static_data_member (decl);
10870 /* This function is only called with out-of-class definitions. */
10871 DECL_EXTERNAL (decl) = 0;
10872 check_class_member_definition_namespace (decl);
10874 /* At top level, either `static' or no s.c. makes a definition
10875 (perhaps tentative), and absence of `static' makes it public. */
10876 else if (toplevel_bindings_p ())
10878 TREE_PUBLIC (decl) = (declspecs->storage_class != sc_static
10879 && (DECL_THIS_EXTERN (decl)
10880 || ! constp
10881 || volatilep
10882 || inlinep));
10883 TREE_STATIC (decl) = ! DECL_EXTERNAL (decl);
10885 /* Not at top level, only `static' makes a static definition. */
10886 else
10888 TREE_STATIC (decl) = declspecs->storage_class == sc_static;
10889 TREE_PUBLIC (decl) = DECL_EXTERNAL (decl);
10892 set_originating_module (decl);
10894 if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
10896 if (DECL_EXTERNAL (decl) || TREE_STATIC (decl))
10898 CP_DECL_THREAD_LOCAL_P (decl) = true;
10899 if (!processing_template_decl)
10900 set_decl_tls_model (decl, decl_default_tls_model (decl));
10902 if (declspecs->gnu_thread_keyword_p)
10903 SET_DECL_GNU_TLS_P (decl);
10906 /* If the type of the decl has no linkage, make sure that we'll
10907 notice that in mark_used. */
10908 if (cxx_dialect > cxx98
10909 && decl_linkage (decl) != lk_none
10910 && DECL_LANG_SPECIFIC (decl) == NULL
10911 && !DECL_EXTERN_C_P (decl)
10912 && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
10913 retrofit_lang_decl (decl);
10915 if (TREE_PUBLIC (decl))
10917 /* [basic.link]: A name with no linkage (notably, the name of a class
10918 or enumeration declared in a local scope) shall not be used to
10919 declare an entity with linkage.
10921 DR 757 relaxes this restriction for C++0x. */
10922 if (cxx_dialect < cxx11)
10923 no_linkage_error (decl);
10925 else
10926 DECL_INTERFACE_KNOWN (decl) = 1;
10928 if (DECL_NAME (decl)
10929 && MAIN_NAME_P (DECL_NAME (decl))
10930 && scope == global_namespace)
10931 error_at (DECL_SOURCE_LOCATION (decl),
10932 "cannot declare %<::main%> to be a global variable");
10934 /* Check that the variable can be safely declared as a concept.
10935 Note that this also forbids explicit specializations. */
10936 if (conceptp)
10938 if (!processing_template_decl)
10940 error_at (declspecs->locations[ds_concept],
10941 "a non-template variable cannot be %<concept%>");
10942 return NULL_TREE;
10944 else if (!at_namespace_scope_p ())
10946 error_at (declspecs->locations[ds_concept],
10947 "concept must be defined at namespace scope");
10948 return NULL_TREE;
10950 else
10951 DECL_DECLARED_CONCEPT_P (decl) = true;
10952 if (!same_type_ignoring_top_level_qualifiers_p (type, boolean_type_node))
10953 error_at (declspecs->locations[ds_type_spec],
10954 "concept must have type %<bool%>");
10955 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
10957 error_at (location, "a variable concept cannot be constrained");
10958 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
10961 else if (flag_concepts
10962 && current_template_depth > template_class_depth (scope))
10964 tree ci = current_template_constraints ();
10965 set_constraints (decl, ci);
10968 // Handle explicit specializations and instantiations of variable templates.
10969 if (orig_declarator)
10970 decl = check_explicit_specialization (orig_declarator, decl,
10971 template_count, conceptp * 8);
10973 return decl != error_mark_node ? decl : NULL_TREE;
10976 /* Create and return a canonical pointer to member function type, for
10977 TYPE, which is a POINTER_TYPE to a METHOD_TYPE. */
10979 tree
10980 build_ptrmemfunc_type (tree type)
10982 tree field, fields;
10983 tree t;
10985 if (type == error_mark_node)
10986 return type;
10988 /* Make sure that we always have the unqualified pointer-to-member
10989 type first. */
10990 if (cp_cv_quals quals = cp_type_quals (type))
10992 tree unqual = build_ptrmemfunc_type (TYPE_MAIN_VARIANT (type));
10993 return cp_build_qualified_type (unqual, quals);
10996 /* If a canonical type already exists for this type, use it. We use
10997 this method instead of type_hash_canon, because it only does a
10998 simple equality check on the list of field members. */
11000 t = TYPE_PTRMEMFUNC_TYPE (type);
11001 if (t)
11002 return t;
11004 t = make_node (RECORD_TYPE);
11006 /* Let the front end know this is a pointer to member function. */
11007 TYPE_PTRMEMFUNC_FLAG (t) = 1;
11009 field = build_decl (input_location, FIELD_DECL, pfn_identifier, type);
11010 DECL_NONADDRESSABLE_P (field) = 1;
11011 fields = field;
11013 field = build_decl (input_location, FIELD_DECL, delta_identifier,
11014 delta_type_node);
11015 DECL_NONADDRESSABLE_P (field) = 1;
11016 DECL_CHAIN (field) = fields;
11017 fields = field;
11019 finish_builtin_struct (t, "__ptrmemfunc_type", fields, ptr_type_node);
11021 /* Zap out the name so that the back end will give us the debugging
11022 information for this anonymous RECORD_TYPE. */
11023 TYPE_NAME (t) = NULL_TREE;
11025 /* Cache this pointer-to-member type so that we can find it again
11026 later. */
11027 TYPE_PTRMEMFUNC_TYPE (type) = t;
11029 if (TYPE_STRUCTURAL_EQUALITY_P (type))
11030 SET_TYPE_STRUCTURAL_EQUALITY (t);
11031 else if (TYPE_CANONICAL (type) != type)
11032 TYPE_CANONICAL (t) = build_ptrmemfunc_type (TYPE_CANONICAL (type));
11034 return t;
11037 /* Create and return a pointer to data member type. */
11039 tree
11040 build_ptrmem_type (tree class_type, tree member_type)
11042 if (TREE_CODE (member_type) == METHOD_TYPE)
11044 cp_cv_quals quals = type_memfn_quals (member_type);
11045 cp_ref_qualifier rqual = type_memfn_rqual (member_type);
11046 member_type = build_memfn_type (member_type, class_type, quals, rqual);
11047 return build_ptrmemfunc_type (build_pointer_type (member_type));
11049 else
11051 gcc_assert (TREE_CODE (member_type) != FUNCTION_TYPE);
11052 return build_offset_type (class_type, member_type);
11056 /* DECL is a VAR_DECL defined in-class, whose TYPE is also given.
11057 Check to see that the definition is valid. Issue appropriate error
11058 messages. */
11060 static void
11061 check_static_variable_definition (tree decl, tree type)
11063 /* Avoid redundant diagnostics on out-of-class definitions. */
11064 if (!current_class_type || !TYPE_BEING_DEFINED (current_class_type))
11066 /* Can't check yet if we don't know the type. */
11067 else if (dependent_type_p (type))
11069 /* If DECL is declared constexpr, we'll do the appropriate checks
11070 in check_initializer. Similarly for inline static data members. */
11071 else if (DECL_P (decl)
11072 && (DECL_DECLARED_CONSTEXPR_P (decl)
11073 || DECL_VAR_DECLARED_INLINE_P (decl)))
11075 else if (cxx_dialect >= cxx11 && !INTEGRAL_OR_ENUMERATION_TYPE_P (type))
11077 if (!COMPLETE_TYPE_P (type))
11078 error_at (DECL_SOURCE_LOCATION (decl),
11079 "in-class initialization of static data member %q#D of "
11080 "incomplete type", decl);
11081 else if (literal_type_p (type))
11082 permerror (DECL_SOURCE_LOCATION (decl),
11083 "%<constexpr%> needed for in-class initialization of "
11084 "static data member %q#D of non-integral type", decl);
11085 else
11086 error_at (DECL_SOURCE_LOCATION (decl),
11087 "in-class initialization of static data member %q#D of "
11088 "non-literal type", decl);
11090 /* Motion 10 at San Diego: If a static const integral data member is
11091 initialized with an integral constant expression, the initializer
11092 may appear either in the declaration (within the class), or in
11093 the definition, but not both. If it appears in the class, the
11094 member is a member constant. The file-scope definition is always
11095 required. */
11096 else if (!ARITHMETIC_TYPE_P (type) && TREE_CODE (type) != ENUMERAL_TYPE)
11097 error_at (DECL_SOURCE_LOCATION (decl),
11098 "invalid in-class initialization of static data member "
11099 "of non-integral type %qT",
11100 type);
11101 else if (!CP_TYPE_CONST_P (type))
11102 error_at (DECL_SOURCE_LOCATION (decl),
11103 "ISO C++ forbids in-class initialization of non-const "
11104 "static member %qD",
11105 decl);
11106 else if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type))
11107 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
11108 "ISO C++ forbids initialization of member constant "
11109 "%qD of non-integral type %qT", decl, type);
11112 /* *expr_p is part of the TYPE_SIZE of a variably-sized array. If any
11113 SAVE_EXPRs in *expr_p wrap expressions with side-effects, break those
11114 expressions out into temporary variables so that walk_tree doesn't
11115 step into them (c++/15764). */
11117 static tree
11118 stabilize_save_expr_r (tree *expr_p, int *walk_subtrees, void *data)
11120 hash_set<tree> *pset = (hash_set<tree> *)data;
11121 tree expr = *expr_p;
11122 if (TREE_CODE (expr) == SAVE_EXPR)
11124 tree op = TREE_OPERAND (expr, 0);
11125 cp_walk_tree (&op, stabilize_save_expr_r, data, pset);
11126 if (TREE_SIDE_EFFECTS (op))
11127 TREE_OPERAND (expr, 0) = get_temp_regvar (TREE_TYPE (op), op);
11128 *walk_subtrees = 0;
11130 else if (!EXPR_P (expr) || !TREE_SIDE_EFFECTS (expr))
11131 *walk_subtrees = 0;
11132 return NULL;
11135 /* Entry point for the above. */
11137 static void
11138 stabilize_vla_size (tree size)
11140 hash_set<tree> pset;
11141 /* Break out any function calls into temporary variables. */
11142 cp_walk_tree (&size, stabilize_save_expr_r, &pset, &pset);
11145 /* Reduce a SIZEOF_EXPR to its value. */
11147 tree
11148 fold_sizeof_expr (tree t)
11150 tree r;
11151 if (SIZEOF_EXPR_TYPE_P (t))
11152 r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
11153 TREE_TYPE (TREE_OPERAND (t, 0)),
11154 SIZEOF_EXPR, false, false);
11155 else if (TYPE_P (TREE_OPERAND (t, 0)))
11156 r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
11157 TREE_OPERAND (t, 0), SIZEOF_EXPR,
11158 false, false);
11159 else
11160 r = cxx_sizeof_or_alignof_expr (EXPR_LOCATION (t),
11161 TREE_OPERAND (t, 0), SIZEOF_EXPR,
11162 false, false);
11163 if (r == error_mark_node)
11164 r = size_one_node;
11165 return r;
11168 /* Given the SIZE (i.e., number of elements) in an array, compute
11169 an appropriate index type for the array. If non-NULL, NAME is
11170 the name of the entity being declared. */
11172 static tree
11173 compute_array_index_type_loc (location_t name_loc, tree name, tree size,
11174 tsubst_flags_t complain)
11176 if (error_operand_p (size))
11177 return error_mark_node;
11179 /* The type of the index being computed. */
11180 tree itype;
11182 /* The original numeric size as seen in the source code before
11183 conversion to size_t. */
11184 tree origsize = size;
11186 location_t loc = cp_expr_loc_or_loc (size, name ? name_loc : input_location);
11188 if (!type_dependent_expression_p (size))
11190 origsize = size = mark_rvalue_use (size);
11192 if (cxx_dialect < cxx11 && TREE_CODE (size) == NOP_EXPR
11193 && TREE_SIDE_EFFECTS (size))
11194 /* In C++98, we mark a non-constant array bound with a magic
11195 NOP_EXPR with TREE_SIDE_EFFECTS; don't fold in that case. */;
11196 else
11198 size = build_converted_constant_expr (size_type_node, size, complain);
11199 /* Pedantically a constant expression is required here and so
11200 __builtin_is_constant_evaluated () should fold to true if it
11201 is successfully folded into a constant. */
11202 size = fold_non_dependent_expr (size, complain,
11203 /*manifestly_const_eval=*/true);
11205 if (!TREE_CONSTANT (size))
11206 size = origsize;
11209 if (error_operand_p (size))
11210 return error_mark_node;
11212 /* The array bound must be an integer type. */
11213 tree type = TREE_TYPE (size);
11214 if (!INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
11216 if (!(complain & tf_error))
11217 return error_mark_node;
11218 if (name)
11219 error_at (loc, "size of array %qD has non-integral type %qT",
11220 name, type);
11221 else
11222 error_at (loc, "size of array has non-integral type %qT", type);
11223 size = integer_one_node;
11227 /* A type is dependent if it is...an array type constructed from any
11228 dependent type or whose size is specified by a constant expression
11229 that is value-dependent. */
11230 /* We can only call value_dependent_expression_p on integral constant
11231 expressions. */
11232 if (processing_template_decl
11233 && potential_constant_expression (size)
11234 && value_dependent_expression_p (size))
11236 /* Just build the index type and mark that it requires
11237 structural equality checks. */
11238 in_template:
11239 itype = build_index_type (build_min (MINUS_EXPR, sizetype,
11240 size, size_one_node));
11241 TYPE_DEPENDENT_P (itype) = 1;
11242 TYPE_DEPENDENT_P_VALID (itype) = 1;
11243 SET_TYPE_STRUCTURAL_EQUALITY (itype);
11244 return itype;
11247 if (TREE_CODE (size) != INTEGER_CST)
11249 tree folded = cp_fully_fold (size);
11250 if (TREE_CODE (folded) == INTEGER_CST)
11252 if (name)
11253 pedwarn (loc, OPT_Wpedantic, "size of array %qD is not an "
11254 "integral constant-expression", name);
11255 else
11256 pedwarn (loc, OPT_Wpedantic,
11257 "size of array is not an integral constant-expression");
11259 if (TREE_CONSTANT (size) && !TREE_CONSTANT (folded))
11260 /* We might have lost the TREE_CONSTANT flag e.g. when we are
11261 folding a conversion from a pointer to integral type. In that
11262 case issue an error below and don't treat this as a VLA. */;
11263 else
11264 /* Use the folded result for VLAs, too; it will have resolved
11265 SIZEOF_EXPR. */
11266 size = folded;
11269 /* Normally, the array-bound will be a constant. */
11270 if (TREE_CODE (size) == INTEGER_CST)
11272 /* The size to use in diagnostics that reflects the constant
11273 size used in the source, rather than SIZE massaged above. */
11274 tree diagsize = size;
11276 /* If the original size before conversion to size_t was signed
11277 and negative, convert it to ssizetype to restore the sign. */
11278 if (!TYPE_UNSIGNED (TREE_TYPE (origsize))
11279 && TREE_CODE (size) == INTEGER_CST
11280 && tree_int_cst_sign_bit (size))
11282 diagsize = fold_convert (ssizetype, size);
11284 /* Clear the overflow bit that may have been set as a result
11285 of the conversion from the sizetype of the new size to
11286 ssizetype. */
11287 TREE_OVERFLOW (diagsize) = false;
11290 /* Verify that the array has a positive number of elements
11291 and issue the appropriate diagnostic if it doesn't. */
11292 if (!valid_array_size_p (loc, diagsize, name, (complain & tf_error)))
11294 if (!(complain & tf_error))
11295 return error_mark_node;
11296 size = integer_one_node;
11298 /* As an extension we allow zero-sized arrays. */
11299 else if (integer_zerop (size))
11301 if (!(complain & tf_error))
11302 /* We must fail if performing argument deduction (as
11303 indicated by the state of complain), so that
11304 another substitution can be found. */
11305 return error_mark_node;
11306 else if (name)
11307 pedwarn (loc, OPT_Wpedantic,
11308 "ISO C++ forbids zero-size array %qD", name);
11309 else
11310 pedwarn (loc, OPT_Wpedantic,
11311 "ISO C++ forbids zero-size array");
11314 else if (TREE_CONSTANT (size)
11315 /* We don't allow VLAs at non-function scopes, or during
11316 tentative template substitution. */
11317 || !at_function_scope_p ()
11318 || !(complain & tf_error))
11320 if (!(complain & tf_error))
11321 return error_mark_node;
11322 /* `(int) &fn' is not a valid array bound. */
11323 if (name)
11324 error_at (loc,
11325 "size of array %qD is not an integral constant-expression",
11326 name);
11327 else
11328 error_at (loc, "size of array is not an integral constant-expression");
11329 size = integer_one_node;
11331 else if (pedantic && warn_vla != 0)
11333 if (name)
11334 pedwarn (name_loc, OPT_Wvla,
11335 "ISO C++ forbids variable length array %qD", name);
11336 else
11337 pedwarn (input_location, OPT_Wvla,
11338 "ISO C++ forbids variable length array");
11340 else if (warn_vla > 0)
11342 if (name)
11343 warning_at (name_loc, OPT_Wvla,
11344 "variable length array %qD is used", name);
11345 else
11346 warning (OPT_Wvla,
11347 "variable length array is used");
11350 if (processing_template_decl && !TREE_CONSTANT (size))
11351 goto in_template;
11352 else
11354 if (!TREE_CONSTANT (size))
11356 /* A variable sized array. Arrange for the SAVE_EXPR on the inside
11357 of the MINUS_EXPR, which allows the -1 to get folded with the +1
11358 that happens when building TYPE_SIZE. */
11359 size = variable_size (size);
11360 stabilize_vla_size (size);
11363 /* Compute the index of the largest element in the array. It is
11364 one less than the number of elements in the array. We save
11365 and restore PROCESSING_TEMPLATE_DECL so that computations in
11366 cp_build_binary_op will be appropriately folded. */
11368 processing_template_decl_sentinel s;
11369 itype = cp_build_binary_op (input_location,
11370 MINUS_EXPR,
11371 cp_convert (ssizetype, size, complain),
11372 cp_convert (ssizetype, integer_one_node,
11373 complain),
11374 complain);
11375 itype = maybe_constant_value (itype, NULL_TREE, true);
11378 if (!TREE_CONSTANT (itype))
11380 if (sanitize_flags_p (SANITIZE_VLA)
11381 && current_function_decl != NULL_TREE)
11383 /* We have to add 1 -- in the ubsan routine we generate
11384 LE_EXPR rather than LT_EXPR. */
11385 tree t = fold_build2 (PLUS_EXPR, TREE_TYPE (itype), itype,
11386 build_one_cst (TREE_TYPE (itype)));
11387 t = ubsan_instrument_vla (input_location, t);
11388 finish_expr_stmt (t);
11391 /* Make sure that there was no overflow when creating to a signed
11392 index type. (For example, on a 32-bit machine, an array with
11393 size 2^32 - 1 is too big.) */
11394 else if (TREE_CODE (itype) == INTEGER_CST
11395 && TREE_OVERFLOW (itype))
11397 if (!(complain & tf_error))
11398 return error_mark_node;
11399 error ("overflow in array dimension");
11400 TREE_OVERFLOW (itype) = 0;
11404 /* Create and return the appropriate index type. */
11405 itype = build_index_type (itype);
11407 /* If the index type were dependent, we would have returned early, so
11408 remember that it isn't. */
11409 TYPE_DEPENDENT_P (itype) = 0;
11410 TYPE_DEPENDENT_P_VALID (itype) = 1;
11411 return itype;
11414 tree
11415 compute_array_index_type (tree name, tree size, tsubst_flags_t complain)
11417 return compute_array_index_type_loc (input_location, name, size, complain);
11420 /* Returns the scope (if any) in which the entity declared by
11421 DECLARATOR will be located. If the entity was declared with an
11422 unqualified name, NULL_TREE is returned. */
11424 tree
11425 get_scope_of_declarator (const cp_declarator *declarator)
11427 while (declarator && declarator->kind != cdk_id)
11428 declarator = declarator->declarator;
11430 /* If the declarator-id is a SCOPE_REF, the scope in which the
11431 declaration occurs is the first operand. */
11432 if (declarator
11433 && declarator->u.id.qualifying_scope)
11434 return declarator->u.id.qualifying_scope;
11436 /* Otherwise, the declarator is not a qualified name; the entity will
11437 be declared in the current scope. */
11438 return NULL_TREE;
11441 /* Returns an ARRAY_TYPE for an array with SIZE elements of the
11442 indicated TYPE. If non-NULL, NAME is the NAME of the declaration
11443 with this type. */
11445 static tree
11446 create_array_type_for_decl (tree name, tree type, tree size, location_t loc)
11448 tree itype = NULL_TREE;
11450 /* If things have already gone awry, bail now. */
11451 if (type == error_mark_node || size == error_mark_node)
11452 return error_mark_node;
11454 /* [dcl.type.class.deduct] prohibits forming an array of placeholder
11455 for a deduced class type. */
11456 if (template_placeholder_p (type))
11458 if (name)
11459 error_at (loc, "%qD declared as array of template placeholder "
11460 "type %qT", name, type);
11461 else
11462 error ("creating array of template placeholder type %qT", type);
11463 return error_mark_node;
11466 /* If there are some types which cannot be array elements,
11467 issue an error-message and return. */
11468 switch (TREE_CODE (type))
11470 case VOID_TYPE:
11471 if (name)
11472 error_at (loc, "declaration of %qD as array of void", name);
11473 else
11474 error ("creating array of void");
11475 return error_mark_node;
11477 case FUNCTION_TYPE:
11478 if (name)
11479 error_at (loc, "declaration of %qD as array of functions", name);
11480 else
11481 error ("creating array of functions");
11482 return error_mark_node;
11484 case REFERENCE_TYPE:
11485 if (name)
11486 error_at (loc, "declaration of %qD as array of references", name);
11487 else
11488 error ("creating array of references");
11489 return error_mark_node;
11491 case METHOD_TYPE:
11492 if (name)
11493 error_at (loc, "declaration of %qD as array of function members",
11494 name);
11495 else
11496 error ("creating array of function members");
11497 return error_mark_node;
11499 default:
11500 break;
11503 if (!verify_type_context (name ? loc : input_location,
11504 TCTX_ARRAY_ELEMENT, type))
11505 return error_mark_node;
11507 /* [dcl.array]
11509 The constant expressions that specify the bounds of the arrays
11510 can be omitted only for the first member of the sequence. */
11511 if (TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type))
11513 if (name)
11514 error_at (loc, "declaration of %qD as multidimensional array must "
11515 "have bounds for all dimensions except the first",
11516 name);
11517 else
11518 error ("multidimensional array must have bounds for all "
11519 "dimensions except the first");
11521 return error_mark_node;
11524 /* Figure out the index type for the array. */
11525 if (size)
11527 itype = compute_array_index_type_loc (loc, name, size,
11528 tf_warning_or_error);
11529 if (type_uses_auto (type)
11530 && variably_modified_type_p (itype, /*fn=*/NULL_TREE))
11532 sorry_at (loc, "variable-length array of %<auto%>");
11533 return error_mark_node;
11537 return build_cplus_array_type (type, itype);
11540 /* Returns the smallest location that is not UNKNOWN_LOCATION. */
11542 static location_t
11543 min_location (location_t loca, location_t locb)
11545 if (loca == UNKNOWN_LOCATION
11546 || (locb != UNKNOWN_LOCATION
11547 && linemap_location_before_p (line_table, locb, loca)))
11548 return locb;
11549 return loca;
11552 /* Returns the smallest location != UNKNOWN_LOCATION among the
11553 three stored in LOCATIONS[ds_const], LOCATIONS[ds_volatile],
11554 and LOCATIONS[ds_restrict]. */
11556 static location_t
11557 smallest_type_quals_location (int type_quals, const location_t* locations)
11559 location_t loc = UNKNOWN_LOCATION;
11561 if (type_quals & TYPE_QUAL_CONST)
11562 loc = locations[ds_const];
11564 if (type_quals & TYPE_QUAL_VOLATILE)
11565 loc = min_location (loc, locations[ds_volatile]);
11567 if (type_quals & TYPE_QUAL_RESTRICT)
11568 loc = min_location (loc, locations[ds_restrict]);
11570 return loc;
11573 /* Returns the smallest among the latter and locations[ds_type_spec]. */
11575 static location_t
11576 smallest_type_location (int type_quals, const location_t* locations)
11578 location_t loc = smallest_type_quals_location (type_quals, locations);
11579 return min_location (loc, locations[ds_type_spec]);
11582 static location_t
11583 smallest_type_location (const cp_decl_specifier_seq *declspecs)
11585 int type_quals = get_type_quals (declspecs);
11586 return smallest_type_location (type_quals, declspecs->locations);
11589 /* Check that it's OK to declare a function with the indicated TYPE
11590 and TYPE_QUALS. SFK indicates the kind of special function (if any)
11591 that this function is. OPTYPE is the type given in a conversion
11592 operator declaration, or the class type for a constructor/destructor.
11593 Returns the actual return type of the function; that may be different
11594 than TYPE if an error occurs, or for certain special functions. */
11596 static tree
11597 check_special_function_return_type (special_function_kind sfk,
11598 tree type,
11599 tree optype,
11600 int type_quals,
11601 const location_t* locations)
11603 switch (sfk)
11605 case sfk_constructor:
11606 if (type)
11607 error_at (smallest_type_location (type_quals, locations),
11608 "return type specification for constructor invalid");
11609 else if (type_quals != TYPE_UNQUALIFIED)
11610 error_at (smallest_type_quals_location (type_quals, locations),
11611 "qualifiers are not allowed on constructor declaration");
11613 if (targetm.cxx.cdtor_returns_this ())
11614 type = build_pointer_type (optype);
11615 else
11616 type = void_type_node;
11617 break;
11619 case sfk_destructor:
11620 if (type)
11621 error_at (smallest_type_location (type_quals, locations),
11622 "return type specification for destructor invalid");
11623 else if (type_quals != TYPE_UNQUALIFIED)
11624 error_at (smallest_type_quals_location (type_quals, locations),
11625 "qualifiers are not allowed on destructor declaration");
11627 /* We can't use the proper return type here because we run into
11628 problems with ambiguous bases and covariant returns. */
11629 if (targetm.cxx.cdtor_returns_this ())
11630 type = build_pointer_type (void_type_node);
11631 else
11632 type = void_type_node;
11633 break;
11635 case sfk_conversion:
11636 if (type)
11637 error_at (smallest_type_location (type_quals, locations),
11638 "return type specified for %<operator %T%>", optype);
11639 else if (type_quals != TYPE_UNQUALIFIED)
11640 error_at (smallest_type_quals_location (type_quals, locations),
11641 "qualifiers are not allowed on declaration of "
11642 "%<operator %T%>", optype);
11644 type = optype;
11645 break;
11647 case sfk_deduction_guide:
11648 if (type)
11649 error_at (smallest_type_location (type_quals, locations),
11650 "return type specified for deduction guide");
11651 else if (type_quals != TYPE_UNQUALIFIED)
11652 error_at (smallest_type_quals_location (type_quals, locations),
11653 "qualifiers are not allowed on declaration of "
11654 "deduction guide");
11655 if (TREE_CODE (optype) == TEMPLATE_TEMPLATE_PARM)
11657 error ("template template parameter %qT in declaration of "
11658 "deduction guide", optype);
11659 type = error_mark_node;
11661 else
11662 type = make_template_placeholder (CLASSTYPE_TI_TEMPLATE (optype));
11663 for (int i = 0; i < ds_last; ++i)
11664 if (i != ds_explicit && locations[i])
11665 error_at (locations[i],
11666 "%<decl-specifier%> in declaration of deduction guide");
11667 break;
11669 default:
11670 gcc_unreachable ();
11673 return type;
11676 /* A variable or data member (whose unqualified name is IDENTIFIER)
11677 has been declared with the indicated TYPE. If the TYPE is not
11678 acceptable, issue an error message and return a type to use for
11679 error-recovery purposes. */
11681 tree
11682 check_var_type (tree identifier, tree type, location_t loc)
11684 if (VOID_TYPE_P (type))
11686 if (!identifier)
11687 error_at (loc, "unnamed variable or field declared void");
11688 else if (identifier_p (identifier))
11690 gcc_assert (!IDENTIFIER_ANY_OP_P (identifier));
11691 error_at (loc, "variable or field %qE declared void",
11692 identifier);
11694 else
11695 error_at (loc, "variable or field declared void");
11696 type = error_mark_node;
11699 return type;
11702 /* Handle declaring DECL as an inline variable. */
11704 static void
11705 mark_inline_variable (tree decl, location_t loc)
11707 bool inlinep = true;
11708 if (! toplevel_bindings_p ())
11710 error_at (loc, "%<inline%> specifier invalid for variable "
11711 "%qD declared at block scope", decl);
11712 inlinep = false;
11714 else if (cxx_dialect < cxx17)
11715 pedwarn (loc, OPT_Wc__17_extensions, "inline variables are only available "
11716 "with %<-std=c++17%> or %<-std=gnu++17%>");
11717 if (inlinep)
11719 retrofit_lang_decl (decl);
11720 SET_DECL_VAR_DECLARED_INLINE_P (decl);
11725 /* Assign a typedef-given name to a class or enumeration type declared
11726 as anonymous at first. This was split out of grokdeclarator
11727 because it is also used in libcc1. */
11729 void
11730 name_unnamed_type (tree type, tree decl)
11732 gcc_assert (TYPE_UNNAMED_P (type));
11734 /* Replace the anonymous decl with the real decl. Be careful not to
11735 rename other typedefs (such as the self-reference) of type. */
11736 tree orig = TYPE_NAME (type);
11737 for (tree t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
11738 if (TYPE_NAME (t) == orig)
11739 TYPE_NAME (t) = decl;
11741 /* If this is a typedef within a template class, the nested
11742 type is a (non-primary) template. The name for the
11743 template needs updating as well. */
11744 if (TYPE_LANG_SPECIFIC (type) && CLASSTYPE_TEMPLATE_INFO (type))
11745 DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)) = DECL_NAME (decl);
11747 /* Adjust linkage now that we aren't unnamed anymore. */
11748 reset_type_linkage (type);
11750 /* FIXME remangle member functions; member functions of a
11751 type with external linkage have external linkage. */
11753 /* Check that our job is done, and that it would fail if we
11754 attempted to do it again. */
11755 gcc_assert (!TYPE_UNNAMED_P (type));
11758 /* Check that decltype(auto) was well-formed: only plain decltype(auto)
11759 is allowed. TYPE might contain a decltype(auto). Returns true if
11760 there was a problem, false otherwise. */
11762 static bool
11763 check_decltype_auto (location_t loc, tree type)
11765 if (tree a = type_uses_auto (type))
11767 if (AUTO_IS_DECLTYPE (a))
11769 if (a != type)
11771 error_at (loc, "%qT as type rather than plain "
11772 "%<decltype(auto)%>", type);
11773 return true;
11775 else if (TYPE_QUALS (type) != TYPE_UNQUALIFIED)
11777 error_at (loc, "%<decltype(auto)%> cannot be cv-qualified");
11778 return true;
11782 return false;
11785 /* Given declspecs and a declarator (abstract or otherwise), determine
11786 the name and type of the object declared and construct a DECL node
11787 for it.
11789 DECLSPECS points to the representation of declaration-specifier
11790 sequence that precedes declarator.
11792 DECL_CONTEXT says which syntactic context this declaration is in:
11793 NORMAL for most contexts. Make a VAR_DECL or FUNCTION_DECL or TYPE_DECL.
11794 FUNCDEF for a function definition. Like NORMAL but a few different
11795 error messages in each case. Return value may be zero meaning
11796 this definition is too screwy to try to parse.
11797 MEMFUNCDEF for a function definition. Like FUNCDEF but prepares to
11798 handle member functions (which have FIELD context).
11799 Return value may be zero meaning this definition is too screwy to
11800 try to parse.
11801 PARM for a parameter declaration (either within a function prototype
11802 or before a function body). Make a PARM_DECL, or return void_type_node.
11803 TPARM for a template parameter declaration.
11804 CATCHPARM for a parameter declaration before a catch clause.
11805 TYPENAME if for a typename (in a cast or sizeof).
11806 Don't make a DECL node; just return the ..._TYPE node.
11807 FIELD for a struct or union field; make a FIELD_DECL.
11808 BITFIELD for a field with specified width.
11810 INITIALIZED is as for start_decl.
11812 ATTRLIST is a pointer to the list of attributes, which may be NULL
11813 if there are none; *ATTRLIST may be modified if attributes from inside
11814 the declarator should be applied to the declaration.
11816 When this function is called, scoping variables (such as
11817 CURRENT_CLASS_TYPE) should reflect the scope in which the
11818 declaration occurs, not the scope in which the new declaration will
11819 be placed. For example, on:
11821 void S::f() { ... }
11823 when grokdeclarator is called for `S::f', the CURRENT_CLASS_TYPE
11824 should not be `S'.
11826 Returns a DECL (if a declarator is present), a TYPE (if there is no
11827 declarator, in cases like "struct S;"), or the ERROR_MARK_NODE if an
11828 error occurs. */
11830 tree
11831 grokdeclarator (const cp_declarator *declarator,
11832 cp_decl_specifier_seq *declspecs,
11833 enum decl_context decl_context,
11834 int initialized,
11835 tree* attrlist)
11837 tree type = NULL_TREE;
11838 int longlong = 0;
11839 int explicit_intN = 0;
11840 int int_n_alt = 0;
11841 int virtualp, explicitp, friendp, inlinep, staticp;
11842 int explicit_int = 0;
11843 int explicit_char = 0;
11844 int defaulted_int = 0;
11846 tree typedef_decl = NULL_TREE;
11847 const char *name = NULL;
11848 tree typedef_type = NULL_TREE;
11849 /* True if this declarator is a function definition. */
11850 bool funcdef_flag = false;
11851 cp_declarator_kind innermost_code = cdk_error;
11852 int bitfield = 0;
11853 #if 0
11854 /* See the code below that used this. */
11855 tree decl_attr = NULL_TREE;
11856 #endif
11858 /* Keep track of what sort of function is being processed
11859 so that we can warn about default return values, or explicit
11860 return values which do not match prescribed defaults. */
11861 special_function_kind sfk = sfk_none;
11863 tree dname = NULL_TREE;
11864 tree ctor_return_type = NULL_TREE;
11865 enum overload_flags flags = NO_SPECIAL;
11866 /* cv-qualifiers that apply to the declarator, for a declaration of
11867 a member function. */
11868 cp_cv_quals memfn_quals = TYPE_UNQUALIFIED;
11869 /* virt-specifiers that apply to the declarator, for a declaration of
11870 a member function. */
11871 cp_virt_specifiers virt_specifiers = VIRT_SPEC_UNSPECIFIED;
11872 /* ref-qualifier that applies to the declarator, for a declaration of
11873 a member function. */
11874 cp_ref_qualifier rqual = REF_QUAL_NONE;
11875 /* cv-qualifiers that apply to the type specified by the DECLSPECS. */
11876 int type_quals = get_type_quals (declspecs);
11877 tree raises = NULL_TREE;
11878 int template_count = 0;
11879 tree returned_attrs = NULL_TREE;
11880 tree parms = NULL_TREE;
11881 const cp_declarator *id_declarator;
11882 /* The unqualified name of the declarator; either an
11883 IDENTIFIER_NODE, BIT_NOT_EXPR, or TEMPLATE_ID_EXPR. */
11884 tree unqualified_id;
11885 /* The class type, if any, in which this entity is located,
11886 or NULL_TREE if none. Note that this value may be different from
11887 the current class type; for example if an attempt is made to declare
11888 "A::f" inside "B", this value will be "A". */
11889 tree ctype = current_class_type;
11890 /* The NAMESPACE_DECL for the namespace in which this entity is
11891 located. If an unqualified name is used to declare the entity,
11892 this value will be NULL_TREE, even if the entity is located at
11893 namespace scope. */
11894 tree in_namespace = NULL_TREE;
11895 cp_storage_class storage_class;
11896 bool unsigned_p, signed_p, short_p, long_p, thread_p;
11897 bool type_was_error_mark_node = false;
11898 bool parameter_pack_p = declarator ? declarator->parameter_pack_p : false;
11899 bool template_type_arg = false;
11900 bool template_parm_flag = false;
11901 bool typedef_p = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
11902 bool constexpr_p = decl_spec_seq_has_spec_p (declspecs, ds_constexpr);
11903 bool constinit_p = decl_spec_seq_has_spec_p (declspecs, ds_constinit);
11904 bool consteval_p = decl_spec_seq_has_spec_p (declspecs, ds_consteval);
11905 bool late_return_type_p = false;
11906 bool array_parameter_p = false;
11907 tree reqs = NULL_TREE;
11909 signed_p = decl_spec_seq_has_spec_p (declspecs, ds_signed);
11910 unsigned_p = decl_spec_seq_has_spec_p (declspecs, ds_unsigned);
11911 short_p = decl_spec_seq_has_spec_p (declspecs, ds_short);
11912 long_p = decl_spec_seq_has_spec_p (declspecs, ds_long);
11913 longlong = decl_spec_seq_has_spec_p (declspecs, ds_long_long);
11914 explicit_intN = declspecs->explicit_intN_p;
11915 int_n_alt = declspecs->int_n_alt;
11916 thread_p = decl_spec_seq_has_spec_p (declspecs, ds_thread);
11918 // Was concept_p specified? Note that ds_concept
11919 // implies ds_constexpr!
11920 bool concept_p = decl_spec_seq_has_spec_p (declspecs, ds_concept);
11921 if (concept_p)
11922 constexpr_p = true;
11924 if (decl_context == FUNCDEF)
11925 funcdef_flag = true, decl_context = NORMAL;
11926 else if (decl_context == MEMFUNCDEF)
11927 funcdef_flag = true, decl_context = FIELD;
11928 else if (decl_context == BITFIELD)
11929 bitfield = 1, decl_context = FIELD;
11930 else if (decl_context == TEMPLATE_TYPE_ARG)
11931 template_type_arg = true, decl_context = TYPENAME;
11932 else if (decl_context == TPARM)
11933 template_parm_flag = true, decl_context = PARM;
11935 if (initialized == SD_DEFAULTED || initialized == SD_DELETED)
11936 funcdef_flag = true;
11938 location_t typespec_loc = loc_or_input_loc (smallest_type_location
11939 (type_quals,
11940 declspecs->locations));
11941 location_t id_loc;
11942 location_t init_loc;
11943 if (declarator)
11945 id_loc = loc_or_input_loc (declarator->id_loc);
11946 init_loc = loc_or_input_loc (declarator->init_loc);
11948 else
11949 init_loc = id_loc = input_location;
11951 /* Look inside a declarator for the name being declared
11952 and get it as a string, for an error message. */
11953 for (id_declarator = declarator;
11954 id_declarator;
11955 id_declarator = id_declarator->declarator)
11957 if (id_declarator->kind != cdk_id)
11958 innermost_code = id_declarator->kind;
11960 switch (id_declarator->kind)
11962 case cdk_function:
11963 if (id_declarator->declarator
11964 && id_declarator->declarator->kind == cdk_id)
11966 sfk = id_declarator->declarator->u.id.sfk;
11967 if (sfk == sfk_destructor)
11968 flags = DTOR_FLAG;
11970 break;
11972 case cdk_id:
11974 tree qualifying_scope = id_declarator->u.id.qualifying_scope;
11975 tree decl = id_declarator->u.id.unqualified_name;
11976 if (!decl)
11977 break;
11978 if (qualifying_scope)
11980 if (check_for_bare_parameter_packs (qualifying_scope,
11981 id_declarator->id_loc))
11982 return error_mark_node;
11983 if (at_function_scope_p ())
11985 /* [dcl.meaning]
11987 A declarator-id shall not be qualified except
11988 for ...
11990 None of the cases are permitted in block
11991 scope. */
11992 if (qualifying_scope == global_namespace)
11993 error ("invalid use of qualified-name %<::%D%>",
11994 decl);
11995 else if (TYPE_P (qualifying_scope))
11996 error ("invalid use of qualified-name %<%T::%D%>",
11997 qualifying_scope, decl);
11998 else
11999 error ("invalid use of qualified-name %<%D::%D%>",
12000 qualifying_scope, decl);
12001 return error_mark_node;
12003 else if (TYPE_P (qualifying_scope))
12005 ctype = qualifying_scope;
12006 if (!MAYBE_CLASS_TYPE_P (ctype))
12008 error_at (id_declarator->id_loc,
12009 "%q#T is not a class or namespace", ctype);
12010 ctype = NULL_TREE;
12012 else if (innermost_code != cdk_function
12013 && current_class_type
12014 && !uniquely_derived_from_p (ctype,
12015 current_class_type))
12017 error_at (id_declarator->id_loc,
12018 "invalid use of qualified-name %<%T::%D%>",
12019 qualifying_scope, decl);
12020 return error_mark_node;
12023 else if (TREE_CODE (qualifying_scope) == NAMESPACE_DECL)
12024 in_namespace = qualifying_scope;
12026 switch (TREE_CODE (decl))
12028 case BIT_NOT_EXPR:
12030 if (innermost_code != cdk_function)
12032 error_at (EXPR_LOCATION (decl),
12033 "declaration of %qE as non-function", decl);
12034 return error_mark_node;
12036 else if (!qualifying_scope
12037 && !(current_class_type && at_class_scope_p ()))
12039 error_at (EXPR_LOCATION (decl),
12040 "declaration of %qE as non-member", decl);
12041 return error_mark_node;
12044 tree type = TREE_OPERAND (decl, 0);
12045 if (TYPE_P (type))
12046 type = constructor_name (type);
12047 name = identifier_to_locale (IDENTIFIER_POINTER (type));
12048 dname = decl;
12050 break;
12052 case TEMPLATE_ID_EXPR:
12054 tree fns = TREE_OPERAND (decl, 0);
12056 dname = fns;
12057 if (!identifier_p (dname))
12058 dname = OVL_NAME (dname);
12060 /* Fall through. */
12062 case IDENTIFIER_NODE:
12063 if (identifier_p (decl))
12064 dname = decl;
12066 if (IDENTIFIER_KEYWORD_P (dname))
12068 error ("declarator-id missing; using reserved word %qD",
12069 dname);
12070 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
12072 else if (!IDENTIFIER_CONV_OP_P (dname))
12073 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
12074 else
12076 gcc_assert (flags == NO_SPECIAL);
12077 flags = TYPENAME_FLAG;
12078 sfk = sfk_conversion;
12079 tree glob = get_global_binding (dname);
12080 if (glob && TREE_CODE (glob) == TYPE_DECL)
12081 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
12082 else
12083 name = "<invalid operator>";
12085 break;
12087 default:
12088 gcc_unreachable ();
12090 break;
12093 case cdk_array:
12094 case cdk_pointer:
12095 case cdk_reference:
12096 case cdk_ptrmem:
12097 break;
12099 case cdk_decomp:
12100 name = "structured binding";
12101 break;
12103 case cdk_error:
12104 return error_mark_node;
12106 default:
12107 gcc_unreachable ();
12109 if (id_declarator->kind == cdk_id)
12110 break;
12113 /* [dcl.fct.edf]
12115 The declarator in a function-definition shall have the form
12116 D1 ( parameter-declaration-clause) ... */
12117 if (funcdef_flag && innermost_code != cdk_function)
12119 error_at (id_loc, "function definition does not declare parameters");
12120 return error_mark_node;
12123 if (flags == TYPENAME_FLAG
12124 && innermost_code != cdk_function
12125 && ! (ctype && !declspecs->any_specifiers_p))
12127 error_at (id_loc, "declaration of %qD as non-function", dname);
12128 return error_mark_node;
12131 if (dname && identifier_p (dname))
12133 if (UDLIT_OPER_P (dname)
12134 && innermost_code != cdk_function)
12136 error_at (id_loc, "declaration of %qD as non-function", dname);
12137 return error_mark_node;
12140 if (IDENTIFIER_ANY_OP_P (dname))
12142 if (typedef_p)
12144 error_at (id_loc, "declaration of %qD as %<typedef%>", dname);
12145 return error_mark_node;
12147 else if (decl_context == PARM || decl_context == CATCHPARM)
12149 error_at (id_loc, "declaration of %qD as parameter", dname);
12150 return error_mark_node;
12155 /* Anything declared one level down from the top level
12156 must be one of the parameters of a function
12157 (because the body is at least two levels down). */
12159 /* This heuristic cannot be applied to C++ nodes! Fixed, however,
12160 by not allowing C++ class definitions to specify their parameters
12161 with xdecls (must be spec.d in the parmlist).
12163 Since we now wait to push a class scope until we are sure that
12164 we are in a legitimate method context, we must set oldcname
12165 explicitly (since current_class_name is not yet alive).
12167 We also want to avoid calling this a PARM if it is in a namespace. */
12169 if (decl_context == NORMAL && !toplevel_bindings_p ())
12171 cp_binding_level *b = current_binding_level;
12172 current_binding_level = b->level_chain;
12173 if (current_binding_level != 0 && toplevel_bindings_p ())
12174 decl_context = PARM;
12175 current_binding_level = b;
12178 if (name == NULL)
12179 name = decl_context == PARM ? "parameter" : "type name";
12181 if (consteval_p && constexpr_p)
12183 error_at (declspecs->locations[ds_consteval],
12184 "both %qs and %qs specified", "constexpr", "consteval");
12185 return error_mark_node;
12188 if (concept_p && typedef_p)
12190 error_at (declspecs->locations[ds_concept],
12191 "%qs cannot appear in a typedef declaration", "concept");
12192 return error_mark_node;
12195 if (constexpr_p && typedef_p)
12197 error_at (declspecs->locations[ds_constexpr],
12198 "%qs cannot appear in a typedef declaration", "constexpr");
12199 return error_mark_node;
12202 if (consteval_p && typedef_p)
12204 error_at (declspecs->locations[ds_consteval],
12205 "%qs cannot appear in a typedef declaration", "consteval");
12206 return error_mark_node;
12209 if (constinit_p && typedef_p)
12211 error_at (declspecs->locations[ds_constinit],
12212 "%qs cannot appear in a typedef declaration", "constinit");
12213 return error_mark_node;
12216 /* [dcl.spec]/2 "At most one of the constexpr, consteval, and constinit
12217 keywords shall appear in a decl-specifier-seq." */
12218 if (constinit_p && constexpr_p)
12220 gcc_rich_location richloc (declspecs->locations[ds_constinit]);
12221 richloc.add_range (declspecs->locations[ds_constexpr]);
12222 error_at (&richloc,
12223 "can use at most one of the %<constinit%> and %<constexpr%> "
12224 "specifiers");
12225 return error_mark_node;
12228 /* If there were multiple types specified in the decl-specifier-seq,
12229 issue an error message. */
12230 if (declspecs->multiple_types_p)
12232 error_at (typespec_loc,
12233 "two or more data types in declaration of %qs", name);
12234 return error_mark_node;
12237 if (declspecs->conflicting_specifiers_p)
12238 return error_mark_node;
12240 /* Extract the basic type from the decl-specifier-seq. */
12241 type = declspecs->type;
12242 if (type == error_mark_node)
12244 type = NULL_TREE;
12245 type_was_error_mark_node = true;
12248 /* Ignore erroneous attributes. */
12249 if (attrlist && *attrlist == error_mark_node)
12250 *attrlist = NULL_TREE;
12252 /* An object declared as __attribute__((unavailable)) suppresses
12253 any reports of being declared with unavailable or deprecated
12254 items. An object declared as __attribute__((deprecated))
12255 suppresses warnings of uses of other deprecated items. */
12256 auto ds = make_temp_override (deprecated_state);
12257 if (attrlist && lookup_attribute ("unavailable", *attrlist))
12258 deprecated_state = UNAVAILABLE_DEPRECATED_SUPPRESS;
12259 else if (attrlist && lookup_attribute ("deprecated", *attrlist))
12260 deprecated_state = DEPRECATED_SUPPRESS;
12262 cp_handle_deprecated_or_unavailable (type);
12263 if (type && TREE_CODE (type) == TYPE_DECL)
12265 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (type));
12266 typedef_decl = type;
12267 type = TREE_TYPE (typedef_decl);
12268 if (DECL_ARTIFICIAL (typedef_decl))
12269 cp_handle_deprecated_or_unavailable (type);
12271 /* No type at all: default to `int', and set DEFAULTED_INT
12272 because it was not a user-defined typedef. */
12273 if (type == NULL_TREE)
12275 if (signed_p || unsigned_p || long_p || short_p)
12277 /* These imply 'int'. */
12278 type = integer_type_node;
12279 defaulted_int = 1;
12281 /* If we just have "complex", it is equivalent to "complex double". */
12282 else if (!longlong && !explicit_intN
12283 && decl_spec_seq_has_spec_p (declspecs, ds_complex))
12285 type = double_type_node;
12286 pedwarn (declspecs->locations[ds_complex], OPT_Wpedantic,
12287 "ISO C++ does not support plain %<complex%> meaning "
12288 "%<double complex%>");
12291 /* Gather flags. */
12292 explicit_int = declspecs->explicit_int_p;
12293 explicit_char = declspecs->explicit_char_p;
12295 #if 0
12296 /* See the code below that used this. */
12297 if (typedef_decl)
12298 decl_attr = DECL_ATTRIBUTES (typedef_decl);
12299 #endif
12300 typedef_type = type;
12302 if (sfk == sfk_conversion || sfk == sfk_deduction_guide)
12303 ctor_return_type = TREE_TYPE (dname);
12304 else
12305 ctor_return_type = ctype;
12307 if (sfk != sfk_none)
12309 type = check_special_function_return_type (sfk, type,
12310 ctor_return_type,
12311 type_quals,
12312 declspecs->locations);
12313 type_quals = TYPE_UNQUALIFIED;
12315 else if (type == NULL_TREE)
12317 int is_main;
12319 explicit_int = -1;
12321 /* We handle `main' specially here, because 'main () { }' is so
12322 common. With no options, it is allowed. With -Wreturn-type,
12323 it is a warning. It is only an error with -pedantic-errors. */
12324 is_main = (funcdef_flag
12325 && dname && identifier_p (dname)
12326 && MAIN_NAME_P (dname)
12327 && ctype == NULL_TREE
12328 && in_namespace == NULL_TREE
12329 && current_namespace == global_namespace);
12331 if (type_was_error_mark_node)
12332 /* We've already issued an error, don't complain more. */;
12333 else if (in_system_header_at (id_loc) || flag_ms_extensions)
12334 /* Allow it, sigh. */;
12335 else if (! is_main)
12336 permerror (id_loc, "ISO C++ forbids declaration of %qs with no type",
12337 name);
12338 else if (pedantic)
12339 pedwarn (id_loc, OPT_Wpedantic,
12340 "ISO C++ forbids declaration of %qs with no type", name);
12341 else
12342 warning_at (id_loc, OPT_Wreturn_type,
12343 "ISO C++ forbids declaration of %qs with no type", name);
12345 if (type_was_error_mark_node && template_parm_flag)
12346 /* FIXME we should be able to propagate the error_mark_node as is
12347 for other contexts too. */
12348 type = error_mark_node;
12349 else
12350 type = integer_type_node;
12353 ctype = NULL_TREE;
12355 if (explicit_intN)
12357 if (! int_n_enabled_p[declspecs->int_n_idx])
12359 error_at (declspecs->locations[ds_type_spec],
12360 "%<__int%d%> is not supported by this target",
12361 int_n_data[declspecs->int_n_idx].bitsize);
12362 explicit_intN = false;
12364 /* Don't pedwarn if the alternate "__intN__" form has been used instead
12365 of "__intN". */
12366 else if (!int_n_alt && pedantic)
12367 pedwarn (declspecs->locations[ds_type_spec], OPT_Wpedantic,
12368 "ISO C++ does not support %<__int%d%> for %qs",
12369 int_n_data[declspecs->int_n_idx].bitsize, name);
12372 /* Now process the modifiers that were specified
12373 and check for invalid combinations. */
12375 /* Long double is a special combination. */
12376 if (long_p && !longlong && TYPE_MAIN_VARIANT (type) == double_type_node)
12378 long_p = false;
12379 type = cp_build_qualified_type (long_double_type_node,
12380 cp_type_quals (type));
12383 /* Check all other uses of type modifiers. */
12385 if (unsigned_p || signed_p || long_p || short_p)
12387 location_t loc;
12388 const char *key;
12389 if (unsigned_p)
12391 key = "unsigned";
12392 loc = declspecs->locations[ds_unsigned];
12394 else if (signed_p)
12396 key = "signed";
12397 loc = declspecs->locations[ds_signed];
12399 else if (longlong)
12401 key = "long long";
12402 loc = declspecs->locations[ds_long_long];
12404 else if (long_p)
12406 key = "long";
12407 loc = declspecs->locations[ds_long];
12409 else /* if (short_p) */
12411 key = "short";
12412 loc = declspecs->locations[ds_short];
12415 int ok = 0;
12417 if (signed_p && unsigned_p)
12419 gcc_rich_location richloc (declspecs->locations[ds_signed]);
12420 richloc.add_range (declspecs->locations[ds_unsigned]);
12421 error_at (&richloc,
12422 "%<signed%> and %<unsigned%> specified together");
12424 else if (long_p && short_p)
12426 gcc_rich_location richloc (declspecs->locations[ds_long]);
12427 richloc.add_range (declspecs->locations[ds_short]);
12428 error_at (&richloc, "%<long%> and %<short%> specified together");
12430 else if (TREE_CODE (type) != INTEGER_TYPE
12431 || type == char8_type_node
12432 || type == char16_type_node
12433 || type == char32_type_node
12434 || ((long_p || short_p)
12435 && (explicit_char || explicit_intN)))
12436 error_at (loc, "%qs specified with %qT", key, type);
12437 else if (!explicit_int && !defaulted_int
12438 && !explicit_char && !explicit_intN)
12440 if (typedef_decl)
12442 pedwarn (loc, OPT_Wpedantic, "%qs specified with %qT",
12443 key, type);
12444 ok = !flag_pedantic_errors;
12445 type = DECL_ORIGINAL_TYPE (typedef_decl);
12446 typedef_decl = NULL_TREE;
12448 else if (declspecs->decltype_p)
12449 error_at (loc, "%qs specified with %<decltype%>", key);
12450 else
12451 error_at (loc, "%qs specified with %<typeof%>", key);
12453 else
12454 ok = 1;
12456 /* Discard the type modifiers if they are invalid. */
12457 if (! ok)
12459 unsigned_p = false;
12460 signed_p = false;
12461 long_p = false;
12462 short_p = false;
12463 longlong = 0;
12467 /* Decide whether an integer type is signed or not.
12468 Optionally treat bitfields as signed by default. */
12469 if (unsigned_p
12470 /* [class.bit]
12472 It is implementation-defined whether a plain (neither
12473 explicitly signed or unsigned) char, short, int, or long
12474 bit-field is signed or unsigned.
12476 Naturally, we extend this to long long as well. Note that
12477 this does not include wchar_t. */
12478 || (bitfield && !flag_signed_bitfields
12479 && !signed_p
12480 /* A typedef for plain `int' without `signed' can be
12481 controlled just like plain `int', but a typedef for
12482 `signed int' cannot be so controlled. */
12483 && !(typedef_decl
12484 && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl))
12485 && TREE_CODE (type) == INTEGER_TYPE
12486 && !same_type_p (TYPE_MAIN_VARIANT (type), wchar_type_node)))
12488 if (explicit_intN)
12489 type = int_n_trees[declspecs->int_n_idx].unsigned_type;
12490 else if (longlong)
12491 type = long_long_unsigned_type_node;
12492 else if (long_p)
12493 type = long_unsigned_type_node;
12494 else if (short_p)
12495 type = short_unsigned_type_node;
12496 else if (type == char_type_node)
12497 type = unsigned_char_type_node;
12498 else if (typedef_decl)
12499 type = unsigned_type_for (type);
12500 else
12501 type = unsigned_type_node;
12503 else if (signed_p && type == char_type_node)
12504 type = signed_char_type_node;
12505 else if (explicit_intN)
12506 type = int_n_trees[declspecs->int_n_idx].signed_type;
12507 else if (longlong)
12508 type = long_long_integer_type_node;
12509 else if (long_p)
12510 type = long_integer_type_node;
12511 else if (short_p)
12512 type = short_integer_type_node;
12514 if (decl_spec_seq_has_spec_p (declspecs, ds_complex))
12516 if (TREE_CODE (type) != INTEGER_TYPE && TREE_CODE (type) != REAL_TYPE)
12517 error_at (declspecs->locations[ds_complex],
12518 "complex invalid for %qs", name);
12519 /* If a modifier is specified, the resulting complex is the complex
12520 form of TYPE. E.g, "complex short" is "complex short int". */
12521 else if (type == integer_type_node)
12522 type = complex_integer_type_node;
12523 else if (type == float_type_node)
12524 type = complex_float_type_node;
12525 else if (type == double_type_node)
12526 type = complex_double_type_node;
12527 else if (type == long_double_type_node)
12528 type = complex_long_double_type_node;
12529 else
12530 type = build_complex_type (type);
12533 /* If we're using the injected-class-name to form a compound type or a
12534 declaration, replace it with the underlying class so we don't get
12535 redundant typedefs in the debug output. But if we are returning the
12536 type unchanged, leave it alone so that it's available to
12537 maybe_get_template_decl_from_type_decl. */
12538 if (CLASS_TYPE_P (type)
12539 && DECL_SELF_REFERENCE_P (TYPE_NAME (type))
12540 && type == TREE_TYPE (TYPE_NAME (type))
12541 && (declarator || type_quals))
12542 type = DECL_ORIGINAL_TYPE (TYPE_NAME (type));
12544 type_quals |= cp_type_quals (type);
12545 type = cp_build_qualified_type
12546 (type, type_quals, ((((typedef_decl && !DECL_ARTIFICIAL (typedef_decl))
12547 || declspecs->decltype_p)
12548 ? tf_ignore_bad_quals : 0) | tf_warning_or_error));
12549 /* We might have ignored or rejected some of the qualifiers. */
12550 type_quals = cp_type_quals (type);
12552 if (cxx_dialect >= cxx17 && type && is_auto (type)
12553 && innermost_code != cdk_function
12554 /* Placeholder in parm gets a better error below. */
12555 && !(decl_context == PARM || decl_context == CATCHPARM)
12556 && id_declarator && declarator != id_declarator)
12557 if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (type))
12559 auto_diagnostic_group g;
12560 gcc_rich_location richloc (typespec_loc);
12561 richloc.add_fixit_insert_after ("<>");
12562 error_at (&richloc, "missing template argument list after %qE; "
12563 "for deduction, template placeholder must be followed "
12564 "by a simple declarator-id", tmpl);
12565 inform (DECL_SOURCE_LOCATION (tmpl), "%qD declared here", tmpl);
12566 type = error_mark_node;
12569 staticp = 0;
12570 inlinep = decl_spec_seq_has_spec_p (declspecs, ds_inline);
12571 virtualp = decl_spec_seq_has_spec_p (declspecs, ds_virtual);
12572 explicitp = decl_spec_seq_has_spec_p (declspecs, ds_explicit);
12574 storage_class = declspecs->storage_class;
12575 if (storage_class == sc_static)
12576 staticp = 1 + (decl_context == FIELD);
12577 else if (decl_context == FIELD && sfk == sfk_deduction_guide)
12578 /* Treat class-scope deduction guides as static member functions
12579 so that they get a FUNCTION_TYPE instead of a METHOD_TYPE. */
12580 staticp = 2;
12582 if (virtualp)
12584 if (staticp == 2)
12586 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
12587 richloc.add_range (declspecs->locations[ds_storage_class]);
12588 error_at (&richloc, "member %qD cannot be declared both %<virtual%> "
12589 "and %<static%>", dname);
12590 storage_class = sc_none;
12591 staticp = 0;
12593 if (constexpr_p && pedantic && cxx_dialect < cxx20)
12595 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
12596 richloc.add_range (declspecs->locations[ds_constexpr]);
12597 pedwarn (&richloc, OPT_Wc__20_extensions, "member %qD can be "
12598 "declared both %<virtual%> and %<constexpr%> only in "
12599 "%<-std=c++20%> or %<-std=gnu++20%>", dname);
12602 friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
12604 /* Issue errors about use of storage classes for parameters. */
12605 if (decl_context == PARM)
12607 if (typedef_p)
12609 error_at (declspecs->locations[ds_typedef],
12610 "typedef declaration invalid in parameter declaration");
12611 return error_mark_node;
12613 else if (template_parm_flag && storage_class != sc_none)
12615 error_at (min_location (declspecs->locations[ds_thread],
12616 declspecs->locations[ds_storage_class]),
12617 "storage class specified for template parameter %qs",
12618 name);
12619 return error_mark_node;
12621 else if (storage_class == sc_static
12622 || storage_class == sc_extern
12623 || thread_p)
12625 error_at (min_location (declspecs->locations[ds_thread],
12626 declspecs->locations[ds_storage_class]),
12627 "storage class specified for parameter %qs", name);
12628 return error_mark_node;
12631 /* Function parameters cannot be concept. */
12632 if (concept_p)
12634 error_at (declspecs->locations[ds_concept],
12635 "a parameter cannot be declared %qs", "concept");
12636 concept_p = 0;
12637 constexpr_p = 0;
12639 /* Function parameters cannot be constexpr. If we saw one, moan
12640 and pretend it wasn't there. */
12641 else if (constexpr_p)
12643 error_at (declspecs->locations[ds_constexpr],
12644 "a parameter cannot be declared %qs", "constexpr");
12645 constexpr_p = 0;
12647 if (constinit_p)
12649 error_at (declspecs->locations[ds_constinit],
12650 "a parameter cannot be declared %qs", "constinit");
12651 constinit_p = 0;
12653 if (consteval_p)
12655 error_at (declspecs->locations[ds_consteval],
12656 "a parameter cannot be declared %qs", "consteval");
12657 consteval_p = 0;
12661 /* Give error if `virtual' is used outside of class declaration. */
12662 if (virtualp
12663 && (current_class_name == NULL_TREE || decl_context != FIELD))
12665 error_at (declspecs->locations[ds_virtual],
12666 "%<virtual%> outside class declaration");
12667 virtualp = 0;
12670 if (innermost_code == cdk_decomp)
12672 location_t loc = (declarator->kind == cdk_reference
12673 ? declarator->declarator->id_loc : declarator->id_loc);
12674 if (inlinep)
12675 error_at (declspecs->locations[ds_inline],
12676 "structured binding declaration cannot be %qs", "inline");
12677 if (typedef_p)
12678 error_at (declspecs->locations[ds_typedef],
12679 "structured binding declaration cannot be %qs", "typedef");
12680 if (constexpr_p && !concept_p)
12681 error_at (declspecs->locations[ds_constexpr], "structured "
12682 "binding declaration cannot be %qs", "constexpr");
12683 if (consteval_p)
12684 error_at (declspecs->locations[ds_consteval], "structured "
12685 "binding declaration cannot be %qs", "consteval");
12686 if (thread_p && cxx_dialect < cxx20)
12687 pedwarn (declspecs->locations[ds_thread], OPT_Wc__20_extensions,
12688 "structured binding declaration can be %qs only in "
12689 "%<-std=c++20%> or %<-std=gnu++20%>",
12690 declspecs->gnu_thread_keyword_p
12691 ? "__thread" : "thread_local");
12692 if (concept_p)
12693 error_at (declspecs->locations[ds_concept],
12694 "structured binding declaration cannot be %qs", "concept");
12695 /* [dcl.struct.bind] "A cv that includes volatile is deprecated." */
12696 if (type_quals & TYPE_QUAL_VOLATILE)
12697 warning_at (declspecs->locations[ds_volatile], OPT_Wvolatile,
12698 "%<volatile%>-qualified structured binding is deprecated");
12699 switch (storage_class)
12701 case sc_none:
12702 break;
12703 case sc_register:
12704 error_at (loc, "structured binding declaration cannot be %qs",
12705 "register");
12706 break;
12707 case sc_static:
12708 if (cxx_dialect < cxx20)
12709 pedwarn (loc, OPT_Wc__20_extensions,
12710 "structured binding declaration can be %qs only in "
12711 "%<-std=c++20%> or %<-std=gnu++20%>", "static");
12712 break;
12713 case sc_extern:
12714 error_at (loc, "structured binding declaration cannot be %qs",
12715 "extern");
12716 break;
12717 case sc_mutable:
12718 error_at (loc, "structured binding declaration cannot be %qs",
12719 "mutable");
12720 break;
12721 case sc_auto:
12722 error_at (loc, "structured binding declaration cannot be "
12723 "C++98 %<auto%>");
12724 break;
12725 default:
12726 gcc_unreachable ();
12728 if (TREE_CODE (type) != TEMPLATE_TYPE_PARM
12729 || TYPE_IDENTIFIER (type) != auto_identifier)
12731 if (type != error_mark_node)
12733 auto_diagnostic_group d;
12734 error_at (loc, "structured binding declaration cannot have "
12735 "type %qT", type);
12736 inform (loc,
12737 "type must be cv-qualified %<auto%> or reference to "
12738 "cv-qualified %<auto%>");
12740 type = build_qualified_type (make_auto (), type_quals);
12741 declspecs->type = type;
12743 else if (PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type))
12744 pedwarn (loc, OPT_Wpedantic,
12745 "structured binding declaration cannot have constrained "
12746 "%<auto%> type %qT", type);
12747 inlinep = 0;
12748 typedef_p = 0;
12749 constexpr_p = 0;
12750 consteval_p = 0;
12751 concept_p = 0;
12752 if (storage_class != sc_static)
12754 storage_class = sc_none;
12755 declspecs->storage_class = sc_none;
12759 /* Static anonymous unions are dealt with here. */
12760 if (staticp && decl_context == TYPENAME
12761 && declspecs->type
12762 && ANON_AGGR_TYPE_P (declspecs->type))
12763 decl_context = FIELD;
12765 /* Warn about storage classes that are invalid for certain
12766 kinds of declarations (parameters, typenames, etc.). */
12767 if (thread_p
12768 && ((storage_class
12769 && storage_class != sc_extern
12770 && storage_class != sc_static)
12771 || typedef_p))
12773 location_t loc
12774 = min_location (declspecs->locations[ds_thread],
12775 declspecs->locations[ds_storage_class]);
12776 error_at (loc, "multiple storage classes in declaration of %qs", name);
12777 thread_p = false;
12779 if (decl_context != NORMAL
12780 && ((storage_class != sc_none
12781 && storage_class != sc_mutable)
12782 || thread_p))
12784 if ((decl_context == PARM || decl_context == CATCHPARM)
12785 && (storage_class == sc_register
12786 || storage_class == sc_auto))
12788 else if (typedef_p)
12790 else if (decl_context == FIELD
12791 /* C++ allows static class elements. */
12792 && storage_class == sc_static)
12793 /* C++ also allows inlines and signed and unsigned elements,
12794 but in those cases we don't come in here. */
12796 else
12798 location_t loc
12799 = min_location (declspecs->locations[ds_thread],
12800 declspecs->locations[ds_storage_class]);
12801 if (decl_context == FIELD)
12802 error_at (loc, "storage class specified for %qs", name);
12803 else if (decl_context == PARM || decl_context == CATCHPARM)
12804 error_at (loc, "storage class specified for parameter %qs", name);
12805 else
12806 error_at (loc, "storage class specified for typename");
12807 if (storage_class == sc_register
12808 || storage_class == sc_auto
12809 || storage_class == sc_extern
12810 || thread_p)
12811 storage_class = sc_none;
12814 else if (storage_class == sc_extern && funcdef_flag
12815 && ! toplevel_bindings_p ())
12816 error ("nested function %qs declared %<extern%>", name);
12817 else if (toplevel_bindings_p ())
12819 if (storage_class == sc_auto)
12820 error_at (declspecs->locations[ds_storage_class],
12821 "top-level declaration of %qs specifies %<auto%>", name);
12823 else if (thread_p
12824 && storage_class != sc_extern
12825 && storage_class != sc_static)
12827 if (declspecs->gnu_thread_keyword_p)
12828 pedwarn (declspecs->locations[ds_thread],
12829 0, "function-scope %qs implicitly auto and "
12830 "declared %<__thread%>", name);
12832 /* When thread_local is applied to a variable of block scope the
12833 storage-class-specifier static is implied if it does not appear
12834 explicitly. */
12835 storage_class = declspecs->storage_class = sc_static;
12836 staticp = 1;
12839 if (storage_class && friendp)
12841 error_at (min_location (declspecs->locations[ds_thread],
12842 declspecs->locations[ds_storage_class]),
12843 "storage class specifiers invalid in friend function "
12844 "declarations");
12845 storage_class = sc_none;
12846 staticp = 0;
12849 if (!id_declarator)
12850 unqualified_id = NULL_TREE;
12851 else
12853 unqualified_id = id_declarator->u.id.unqualified_name;
12854 switch (TREE_CODE (unqualified_id))
12856 case BIT_NOT_EXPR:
12857 unqualified_id = TREE_OPERAND (unqualified_id, 0);
12858 if (TYPE_P (unqualified_id))
12859 unqualified_id = constructor_name (unqualified_id);
12860 break;
12862 case IDENTIFIER_NODE:
12863 case TEMPLATE_ID_EXPR:
12864 break;
12866 default:
12867 gcc_unreachable ();
12871 if (declspecs->std_attributes
12872 && !diagnose_misapplied_contracts (declspecs->std_attributes))
12874 location_t attr_loc = declspecs->locations[ds_std_attribute];
12875 if (warning_at (attr_loc, OPT_Wattributes, "attribute ignored"))
12876 inform (attr_loc, "an attribute that appertains to a type-specifier "
12877 "is ignored");
12880 if (attrlist)
12881 diagnose_misapplied_contracts (*attrlist);
12883 /* Determine the type of the entity declared by recurring on the
12884 declarator. */
12885 for (; declarator; declarator = declarator->declarator)
12887 const cp_declarator *inner_declarator;
12888 tree attrs;
12890 if (type == error_mark_node)
12891 return error_mark_node;
12893 attrs = declarator->attributes;
12894 if (attrs)
12896 int attr_flags;
12898 attr_flags = 0;
12899 if (declarator->kind == cdk_id)
12900 attr_flags |= (int) ATTR_FLAG_DECL_NEXT;
12901 if (declarator->kind == cdk_function)
12902 attr_flags |= (int) ATTR_FLAG_FUNCTION_NEXT;
12903 if (declarator->kind == cdk_array)
12904 attr_flags |= (int) ATTR_FLAG_ARRAY_NEXT;
12905 tree late_attrs = NULL_TREE;
12906 if (decl_context != PARM && decl_context != TYPENAME)
12907 /* Assume that any attributes that get applied late to
12908 templates will DTRT when applied to the declaration
12909 as a whole. */
12910 late_attrs = splice_template_attributes (&attrs, type);
12911 returned_attrs = decl_attributes (&type,
12912 attr_chainon (returned_attrs,
12913 attrs),
12914 attr_flags);
12915 returned_attrs = attr_chainon (late_attrs, returned_attrs);
12918 inner_declarator = declarator->declarator;
12920 /* Check that contracts aren't misapplied. */
12921 if (tree contract_attr = find_contract (declarator->std_attributes))
12922 if (declarator->kind != cdk_function
12923 || innermost_code != cdk_function)
12924 diagnose_misapplied_contracts (contract_attr);
12926 /* We don't want to warn in parameter context because we don't
12927 yet know if the parse will succeed, and this might turn out
12928 to be a constructor call. */
12929 if (decl_context != PARM
12930 && decl_context != TYPENAME
12931 && !typedef_p
12932 && declarator->parenthesized != UNKNOWN_LOCATION
12933 /* If the type is class-like and the inner name used a
12934 global namespace qualifier, we need the parens.
12935 Unfortunately all we can tell is whether a qualified name
12936 was used or not. */
12937 && !(inner_declarator
12938 && inner_declarator->kind == cdk_id
12939 && inner_declarator->u.id.qualifying_scope
12940 && (MAYBE_CLASS_TYPE_P (type)
12941 || TREE_CODE (type) == ENUMERAL_TYPE)))
12943 if (warning_at (declarator->parenthesized, OPT_Wparentheses,
12944 "unnecessary parentheses in declaration of %qs",
12945 name))
12947 gcc_rich_location iloc (declarator->parenthesized);
12948 iloc.add_fixit_remove (get_start (declarator->parenthesized));
12949 iloc.add_fixit_remove (get_finish (declarator->parenthesized));
12950 inform (&iloc, "remove parentheses");
12953 if (declarator->kind == cdk_id || declarator->kind == cdk_decomp)
12954 break;
12956 switch (declarator->kind)
12958 case cdk_array:
12959 type = create_array_type_for_decl (dname, type,
12960 declarator->u.array.bounds,
12961 declarator->id_loc);
12962 if (!valid_array_size_p (dname
12963 ? declarator->id_loc : input_location,
12964 type, dname))
12965 type = error_mark_node;
12967 if (declarator->std_attributes)
12968 /* [dcl.array]/1:
12970 The optional attribute-specifier-seq appertains to the
12971 array. */
12972 returned_attrs = attr_chainon (returned_attrs,
12973 declarator->std_attributes);
12974 break;
12976 case cdk_function:
12978 tree arg_types;
12979 int funcdecl_p;
12981 /* Declaring a function type. */
12983 /* Pick up type qualifiers which should be applied to `this'. */
12984 memfn_quals = declarator->u.function.qualifiers;
12985 /* Pick up virt-specifiers. */
12986 virt_specifiers = declarator->u.function.virt_specifiers;
12987 /* And ref-qualifier, too */
12988 rqual = declarator->u.function.ref_qualifier;
12989 /* And tx-qualifier. */
12990 tree tx_qual = declarator->u.function.tx_qualifier;
12991 /* Pick up the exception specifications. */
12992 raises = declarator->u.function.exception_specification;
12993 /* If the exception-specification is ill-formed, let's pretend
12994 there wasn't one. */
12995 if (raises == error_mark_node)
12996 raises = NULL_TREE;
12998 if (reqs)
12999 error_at (location_of (reqs), "requires-clause on return type");
13000 reqs = declarator->u.function.requires_clause;
13002 /* Say it's a definition only for the CALL_EXPR
13003 closest to the identifier. */
13004 funcdecl_p = inner_declarator && inner_declarator->kind == cdk_id;
13006 /* Handle a late-specified return type. */
13007 tree late_return_type = declarator->u.function.late_return_type;
13008 if (tree auto_node = type_uses_auto (type))
13010 if (!late_return_type)
13012 if (!funcdecl_p)
13013 /* auto (*fp)() = f; is OK. */;
13014 else if (current_class_type
13015 && LAMBDA_TYPE_P (current_class_type))
13016 /* OK for C++11 lambdas. */;
13017 else if (cxx_dialect < cxx14)
13019 error_at (typespec_loc, "%qs function uses "
13020 "%<auto%> type specifier without "
13021 "trailing return type", name);
13022 inform (typespec_loc,
13023 "deduced return type only available "
13024 "with %<-std=c++14%> or %<-std=gnu++14%>");
13026 else if (virtualp)
13028 error_at (typespec_loc, "virtual function "
13029 "cannot have deduced return type");
13030 virtualp = false;
13033 else if (!is_auto (type) && sfk != sfk_conversion)
13035 error_at (typespec_loc, "%qs function with trailing "
13036 "return type has %qT as its type rather "
13037 "than plain %<auto%>", name, type);
13038 return error_mark_node;
13040 else if (is_auto (type) && AUTO_IS_DECLTYPE (type))
13042 if (funcdecl_p)
13043 error_at (typespec_loc,
13044 "%qs function with trailing return type "
13045 "has %<decltype(auto)%> as its type "
13046 "rather than plain %<auto%>", name);
13047 else
13048 error_at (typespec_loc,
13049 "invalid use of %<decltype(auto)%>");
13050 return error_mark_node;
13052 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node);
13053 if (!tmpl)
13054 if (tree late_auto = type_uses_auto (late_return_type))
13055 tmpl = CLASS_PLACEHOLDER_TEMPLATE (late_auto);
13056 if (tmpl)
13058 if (!funcdecl_p || !dguide_name_p (unqualified_id))
13060 auto_diagnostic_group g;
13061 error_at (typespec_loc, "deduced class "
13062 "type %qD in function return type",
13063 DECL_NAME (tmpl));
13064 inform (DECL_SOURCE_LOCATION (tmpl),
13065 "%qD declared here", tmpl);
13066 return error_mark_node;
13068 else if (!late_return_type)
13070 error_at (declarator->id_loc, "deduction guide "
13071 "for %qT must have trailing return "
13072 "type", TREE_TYPE (tmpl));
13073 inform (DECL_SOURCE_LOCATION (tmpl),
13074 "%qD declared here", tmpl);
13075 return error_mark_node;
13077 else if (CLASS_TYPE_P (late_return_type)
13078 && CLASSTYPE_TEMPLATE_INFO (late_return_type)
13079 && (CLASSTYPE_TI_TEMPLATE (late_return_type)
13080 == tmpl))
13081 /* OK */;
13082 else
13083 error ("trailing return type %qT of deduction guide "
13084 "is not a specialization of %qT",
13085 late_return_type, TREE_TYPE (tmpl));
13088 else if (late_return_type
13089 && sfk != sfk_conversion)
13091 if (late_return_type == error_mark_node)
13092 return error_mark_node;
13093 if (cxx_dialect < cxx11)
13094 /* Not using maybe_warn_cpp0x because this should
13095 always be an error. */
13096 error_at (typespec_loc,
13097 "trailing return type only available "
13098 "with %<-std=c++11%> or %<-std=gnu++11%>");
13099 else
13100 error_at (typespec_loc, "%qs function with trailing "
13101 "return type not declared with %<auto%> "
13102 "type specifier", name);
13103 return error_mark_node;
13105 if (late_return_type && sfk == sfk_conversion)
13107 error ("a conversion function cannot have a trailing return type");
13108 return error_mark_node;
13110 type = splice_late_return_type (type, late_return_type);
13111 if (type == error_mark_node)
13112 return error_mark_node;
13114 if (late_return_type)
13116 late_return_type_p = true;
13117 type_quals = cp_type_quals (type);
13120 if (type_quals != TYPE_UNQUALIFIED)
13122 /* It's wrong, for instance, to issue a -Wignored-qualifiers
13123 warning for
13124 static_assert(!is_same_v<void(*)(), const void(*)()>);
13125 because there the qualifier matters. */
13126 if (funcdecl_p && (SCALAR_TYPE_P (type) || VOID_TYPE_P (type)))
13127 warning_at (typespec_loc, OPT_Wignored_qualifiers, "type "
13128 "qualifiers ignored on function return type");
13129 /* [dcl.fct] "A volatile-qualified return type is
13130 deprecated." */
13131 if (type_quals & TYPE_QUAL_VOLATILE)
13132 warning_at (typespec_loc, OPT_Wvolatile,
13133 "%<volatile%>-qualified return type is "
13134 "deprecated");
13136 /* We now know that the TYPE_QUALS don't apply to the
13137 decl, but to its return type. */
13138 type_quals = TYPE_UNQUALIFIED;
13141 /* Error about some types functions can't return. */
13143 if (TREE_CODE (type) == FUNCTION_TYPE)
13145 error_at (typespec_loc, "%qs declared as function returning "
13146 "a function", name);
13147 return error_mark_node;
13149 if (TREE_CODE (type) == ARRAY_TYPE)
13151 error_at (typespec_loc, "%qs declared as function returning "
13152 "an array", name);
13153 return error_mark_node;
13155 if (constinit_p && funcdecl_p)
13157 error_at (declspecs->locations[ds_constinit],
13158 "%<constinit%> on function return type is not "
13159 "allowed");
13160 return error_mark_node;
13163 if (check_decltype_auto (typespec_loc, type))
13164 return error_mark_node;
13166 if (ctype == NULL_TREE
13167 && decl_context == FIELD
13168 && funcdecl_p
13169 && friendp == 0)
13170 ctype = current_class_type;
13172 if (ctype && (sfk == sfk_constructor
13173 || sfk == sfk_destructor))
13175 /* We are within a class's scope. If our declarator name
13176 is the same as the class name, and we are defining
13177 a function, then it is a constructor/destructor, and
13178 therefore returns a void type. */
13180 /* ISO C++ 12.4/2. A destructor may not be declared
13181 const or volatile. A destructor may not be static.
13182 A destructor may not be declared with ref-qualifier.
13184 ISO C++ 12.1. A constructor may not be declared
13185 const or volatile. A constructor may not be
13186 virtual. A constructor may not be static.
13187 A constructor may not be declared with ref-qualifier. */
13188 if (staticp == 2)
13189 error_at (declspecs->locations[ds_storage_class],
13190 (flags == DTOR_FLAG)
13191 ? G_("destructor cannot be static member "
13192 "function")
13193 : G_("constructor cannot be static member "
13194 "function"));
13195 if (memfn_quals)
13197 error ((flags == DTOR_FLAG)
13198 ? G_("destructors may not be cv-qualified")
13199 : G_("constructors may not be cv-qualified"));
13200 memfn_quals = TYPE_UNQUALIFIED;
13203 if (rqual)
13205 maybe_warn_cpp0x (CPP0X_REF_QUALIFIER);
13206 error ((flags == DTOR_FLAG)
13207 ? G_("destructors may not be ref-qualified")
13208 : G_("constructors may not be ref-qualified"));
13209 rqual = REF_QUAL_NONE;
13212 if (decl_context == FIELD
13213 && !member_function_or_else (ctype,
13214 current_class_type,
13215 flags))
13216 return error_mark_node;
13218 if (flags != DTOR_FLAG)
13220 /* It's a constructor. */
13221 if (explicitp == 1)
13222 explicitp = 2;
13223 if (virtualp)
13225 permerror (declspecs->locations[ds_virtual],
13226 "constructors cannot be declared %<virtual%>");
13227 virtualp = 0;
13229 if (decl_context == FIELD
13230 && sfk != sfk_constructor)
13231 return error_mark_node;
13233 if (decl_context == FIELD)
13234 staticp = 0;
13236 else if (friendp)
13238 if (virtualp)
13240 /* Cannot be both friend and virtual. */
13241 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
13242 richloc.add_range (declspecs->locations[ds_friend]);
13243 error_at (&richloc, "virtual functions cannot be friends");
13244 friendp = 0;
13246 if (decl_context == NORMAL)
13247 error_at (declarator->id_loc,
13248 "friend declaration not in class definition");
13249 if (current_function_decl && funcdef_flag)
13251 error_at (declarator->id_loc,
13252 "cannot define friend function %qs in a local "
13253 "class definition", name);
13254 friendp = 0;
13256 /* [class.friend]/6: A function can be defined in a friend
13257 declaration if the function name is unqualified. */
13258 if (funcdef_flag && in_namespace)
13260 if (in_namespace == global_namespace)
13261 error_at (declarator->id_loc,
13262 "friend function definition %qs cannot have "
13263 "a name qualified with %<::%>", name);
13264 else
13265 error_at (declarator->id_loc,
13266 "friend function definition %qs cannot have "
13267 "a name qualified with %<%D::%>", name,
13268 in_namespace);
13271 else if (ctype && sfk == sfk_conversion)
13273 if (explicitp == 1)
13275 maybe_warn_cpp0x (CPP0X_EXPLICIT_CONVERSION);
13276 explicitp = 2;
13279 else if (sfk == sfk_deduction_guide)
13281 if (explicitp == 1)
13282 explicitp = 2;
13285 tree pushed_scope = NULL_TREE;
13286 if (funcdecl_p
13287 && decl_context != FIELD
13288 && inner_declarator->u.id.qualifying_scope
13289 && CLASS_TYPE_P (inner_declarator->u.id.qualifying_scope))
13290 pushed_scope
13291 = push_scope (inner_declarator->u.id.qualifying_scope);
13293 arg_types = grokparms (declarator->u.function.parameters, &parms);
13295 if (pushed_scope)
13296 pop_scope (pushed_scope);
13298 if (inner_declarator
13299 && inner_declarator->kind == cdk_id
13300 && inner_declarator->u.id.sfk == sfk_destructor
13301 && arg_types != void_list_node)
13303 error_at (declarator->id_loc,
13304 "destructors may not have parameters");
13305 arg_types = void_list_node;
13306 parms = NULL_TREE;
13309 type = build_function_type (type, arg_types);
13311 tree attrs = declarator->std_attributes;
13312 if (tx_qual)
13314 tree att = build_tree_list (tx_qual, NULL_TREE);
13315 /* transaction_safe applies to the type, but
13316 transaction_safe_dynamic applies to the function. */
13317 if (is_attribute_p ("transaction_safe", tx_qual))
13318 attrs = attr_chainon (attrs, att);
13319 else
13320 returned_attrs = attr_chainon (returned_attrs, att);
13323 /* Actually apply the contract attributes to the declaration. */
13324 for (tree *p = &attrs; *p;)
13326 tree l = *p;
13327 if (cxx_contract_attribute_p (l))
13329 *p = TREE_CHAIN (l);
13330 /* Intentionally reverse order of contracts so they're
13331 reversed back into their lexical order. */
13332 TREE_CHAIN (l) = NULL_TREE;
13333 returned_attrs = chainon (l, returned_attrs);
13335 else
13336 p = &TREE_CHAIN (l);
13339 if (attrs)
13340 /* [dcl.fct]/2:
13342 The optional attribute-specifier-seq appertains to
13343 the function type. */
13344 cplus_decl_attributes (&type, attrs, 0);
13346 if (raises)
13347 type = build_exception_variant (type, raises);
13349 break;
13351 case cdk_pointer:
13352 case cdk_reference:
13353 case cdk_ptrmem:
13354 /* Filter out pointers-to-references and references-to-references.
13355 We can get these if a TYPE_DECL is used. */
13357 if (TYPE_REF_P (type))
13359 if (declarator->kind != cdk_reference)
13361 error ("cannot declare pointer to %q#T", type);
13362 type = TREE_TYPE (type);
13365 /* In C++0x, we allow reference to reference declarations
13366 that occur indirectly through typedefs [7.1.3/8 dcl.typedef]
13367 and template type arguments [14.3.1/4 temp.arg.type]. The
13368 check for direct reference to reference declarations, which
13369 are still forbidden, occurs below. Reasoning behind the change
13370 can be found in DR106, DR540, and the rvalue reference
13371 proposals. */
13372 else if (cxx_dialect == cxx98)
13374 error ("cannot declare reference to %q#T", type);
13375 type = TREE_TYPE (type);
13378 else if (VOID_TYPE_P (type))
13380 if (declarator->kind == cdk_reference)
13381 error ("cannot declare reference to %q#T", type);
13382 else if (declarator->kind == cdk_ptrmem)
13383 error ("cannot declare pointer to %q#T member", type);
13386 /* We now know that the TYPE_QUALS don't apply to the decl,
13387 but to the target of the pointer. */
13388 type_quals = TYPE_UNQUALIFIED;
13390 /* This code used to handle METHOD_TYPE, but I don't think it's
13391 possible to get it here anymore. */
13392 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
13393 if (declarator->kind == cdk_ptrmem
13394 && TREE_CODE (type) == FUNCTION_TYPE)
13396 memfn_quals |= type_memfn_quals (type);
13397 type = build_memfn_type (type,
13398 declarator->u.pointer.class_type,
13399 memfn_quals,
13400 rqual);
13401 if (type == error_mark_node)
13402 return error_mark_node;
13404 rqual = REF_QUAL_NONE;
13405 memfn_quals = TYPE_UNQUALIFIED;
13408 if (TREE_CODE (type) == FUNCTION_TYPE
13409 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
13410 || type_memfn_rqual (type) != REF_QUAL_NONE))
13411 error (declarator->kind == cdk_reference
13412 ? G_("cannot declare reference to qualified function type %qT")
13413 : G_("cannot declare pointer to qualified function type %qT"),
13414 type);
13416 /* When the pointed-to type involves components of variable size,
13417 care must be taken to ensure that the size evaluation code is
13418 emitted early enough to dominate all the possible later uses
13419 and late enough for the variables on which it depends to have
13420 been assigned.
13422 This is expected to happen automatically when the pointed-to
13423 type has a name/declaration of it's own, but special attention
13424 is required if the type is anonymous.
13426 We handle the NORMAL and FIELD contexts here by inserting a
13427 dummy statement that just evaluates the size at a safe point
13428 and ensures it is not deferred until e.g. within a deeper
13429 conditional context (c++/43555).
13431 We expect nothing to be needed here for PARM or TYPENAME.
13432 Evaluating the size at this point for TYPENAME would
13433 actually be incorrect, as we might be in the middle of an
13434 expression with side effects on the pointed-to type size
13435 "arguments" prior to the pointer declaration point and the
13436 size evaluation could end up prior to the side effects. */
13438 if (!TYPE_NAME (type)
13439 && (decl_context == NORMAL || decl_context == FIELD)
13440 && at_function_scope_p ()
13441 && variably_modified_type_p (type, NULL_TREE))
13443 TYPE_NAME (type) = build_decl (UNKNOWN_LOCATION, TYPE_DECL,
13444 NULL_TREE, type);
13445 add_decl_expr (TYPE_NAME (type));
13448 if (declarator->kind == cdk_reference)
13450 /* In C++0x, the type we are creating a reference to might be
13451 a typedef which is itself a reference type. In that case,
13452 we follow the reference collapsing rules in
13453 [7.1.3/8 dcl.typedef] to create the final reference type:
13455 "If a typedef TD names a type that is a reference to a type
13456 T, an attempt to create the type 'lvalue reference to cv TD'
13457 creates the type 'lvalue reference to T,' while an attempt
13458 to create the type "rvalue reference to cv TD' creates the
13459 type TD."
13461 if (VOID_TYPE_P (type))
13462 /* We already gave an error. */;
13463 else if (TYPE_REF_P (type))
13465 if (declarator->u.reference.rvalue_ref)
13466 /* Leave type alone. */;
13467 else
13468 type = cp_build_reference_type (TREE_TYPE (type), false);
13470 else
13471 type = cp_build_reference_type
13472 (type, declarator->u.reference.rvalue_ref);
13474 /* In C++0x, we need this check for direct reference to
13475 reference declarations, which are forbidden by
13476 [8.3.2/5 dcl.ref]. Reference to reference declarations
13477 are only allowed indirectly through typedefs and template
13478 type arguments. Example:
13480 void foo(int & &); // invalid ref-to-ref decl
13482 typedef int & int_ref;
13483 void foo(int_ref &); // valid ref-to-ref decl
13485 if (inner_declarator && inner_declarator->kind == cdk_reference)
13486 error ("cannot declare reference to %q#T, which is not "
13487 "a typedef or a template type argument", type);
13489 else if (TREE_CODE (type) == METHOD_TYPE)
13490 type = build_ptrmemfunc_type (build_pointer_type (type));
13491 else if (declarator->kind == cdk_ptrmem)
13493 gcc_assert (TREE_CODE (declarator->u.pointer.class_type)
13494 != NAMESPACE_DECL);
13495 if (declarator->u.pointer.class_type == error_mark_node)
13496 /* We will already have complained. */
13497 type = error_mark_node;
13498 else
13499 type = build_ptrmem_type (declarator->u.pointer.class_type,
13500 type);
13502 else
13503 type = build_pointer_type (type);
13505 /* Process a list of type modifier keywords (such as
13506 const or volatile) that were given inside the `*' or `&'. */
13508 if (declarator->u.pointer.qualifiers)
13510 type
13511 = cp_build_qualified_type (type,
13512 declarator->u.pointer.qualifiers);
13513 type_quals = cp_type_quals (type);
13516 /* Apply C++11 attributes to the pointer, and not to the
13517 type pointed to. This is unlike what is done for GNU
13518 attributes above. It is to comply with [dcl.ptr]/1:
13520 [the optional attribute-specifier-seq (7.6.1) appertains
13521 to the pointer and not to the object pointed to]. */
13522 if (declarator->std_attributes)
13523 decl_attributes (&type, declarator->std_attributes,
13526 ctype = NULL_TREE;
13527 break;
13529 case cdk_error:
13530 break;
13532 default:
13533 gcc_unreachable ();
13537 id_loc = declarator ? declarator->id_loc : input_location;
13539 if (innermost_code != cdk_function
13540 /* Don't check this if it can be the artifical decltype(auto)
13541 we created when building a constraint in a compound-requirement:
13542 that the type-constraint is plain is going to be checked in
13543 cp_parser_compound_requirement. */
13544 && decl_context != TYPENAME
13545 && check_decltype_auto (id_loc, type))
13546 return error_mark_node;
13548 /* A `constexpr' specifier used in an object declaration declares
13549 the object as `const'. */
13550 if (constexpr_p && innermost_code != cdk_function)
13552 /* DR1688 says that a `constexpr' specifier in combination with
13553 `volatile' is valid. */
13555 if (!TYPE_REF_P (type))
13557 type_quals |= TYPE_QUAL_CONST;
13558 type = cp_build_qualified_type (type, type_quals);
13562 if (unqualified_id && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR
13563 && !FUNC_OR_METHOD_TYPE_P (type)
13564 && !variable_template_p (TREE_OPERAND (unqualified_id, 0)))
13566 error ("template-id %qD used as a declarator",
13567 unqualified_id);
13568 unqualified_id = dname;
13571 /* If TYPE is a FUNCTION_TYPE, but the function name was explicitly
13572 qualified with a class-name, turn it into a METHOD_TYPE, unless
13573 we know that the function is static. We take advantage of this
13574 opportunity to do other processing that pertains to entities
13575 explicitly declared to be class members. Note that if DECLARATOR
13576 is non-NULL, we know it is a cdk_id declarator; otherwise, we
13577 would not have exited the loop above. */
13578 if (declarator
13579 && declarator->kind == cdk_id
13580 && declarator->u.id.qualifying_scope
13581 && MAYBE_CLASS_TYPE_P (declarator->u.id.qualifying_scope))
13583 ctype = declarator->u.id.qualifying_scope;
13584 ctype = TYPE_MAIN_VARIANT (ctype);
13585 template_count = num_template_headers_for_class (ctype);
13587 if (ctype == current_class_type)
13589 if (friendp)
13591 permerror (declspecs->locations[ds_friend],
13592 "member functions are implicitly "
13593 "friends of their class");
13594 friendp = 0;
13596 else
13597 permerror (id_loc, "extra qualification %<%T::%> on member %qs",
13598 ctype, name);
13600 else if (/* If the qualifying type is already complete, then we
13601 can skip the following checks. */
13602 !COMPLETE_TYPE_P (ctype)
13603 && (/* If the function is being defined, then
13604 qualifying type must certainly be complete. */
13605 funcdef_flag
13606 /* A friend declaration of "T::f" is OK, even if
13607 "T" is a template parameter. But, if this
13608 function is not a friend, the qualifying type
13609 must be a class. */
13610 || (!friendp && !CLASS_TYPE_P (ctype))
13611 /* For a declaration, the type need not be
13612 complete, if either it is dependent (since there
13613 is no meaningful definition of complete in that
13614 case) or the qualifying class is currently being
13615 defined. */
13616 || !(dependent_type_p (ctype)
13617 || currently_open_class (ctype)))
13618 /* Check that the qualifying type is complete. */
13619 && !complete_type_or_else (ctype, NULL_TREE))
13620 return error_mark_node;
13621 else if (TREE_CODE (type) == FUNCTION_TYPE)
13623 if (current_class_type
13624 && (!friendp || funcdef_flag || initialized))
13626 error_at (id_loc, funcdef_flag || initialized
13627 ? G_("cannot define member function %<%T::%s%> "
13628 "within %qT")
13629 : G_("cannot declare member function %<%T::%s%> "
13630 "within %qT"),
13631 ctype, name, current_class_type);
13632 return error_mark_node;
13635 else if (typedef_p && current_class_type)
13637 error_at (id_loc, "cannot declare member %<%T::%s%> within %qT",
13638 ctype, name, current_class_type);
13639 return error_mark_node;
13643 if (ctype == NULL_TREE && decl_context == FIELD && friendp == 0)
13644 ctype = current_class_type;
13646 /* Now TYPE has the actual type. */
13648 if (returned_attrs)
13650 if (attrlist)
13651 *attrlist = attr_chainon (returned_attrs, *attrlist);
13652 else
13653 attrlist = &returned_attrs;
13656 if (declarator
13657 && declarator->kind == cdk_id
13658 && declarator->std_attributes
13659 && attrlist != NULL)
13661 /* [dcl.meaning]/1: The optional attribute-specifier-seq following
13662 a declarator-id appertains to the entity that is declared. */
13663 if (declarator->std_attributes != error_mark_node)
13664 *attrlist = attr_chainon (declarator->std_attributes, *attrlist);
13665 else
13666 /* We should have already diagnosed the issue (c++/78344). */
13667 gcc_assert (seen_error ());
13670 /* Handle parameter packs. */
13671 if (parameter_pack_p)
13673 if (decl_context == PARM)
13674 /* Turn the type into a pack expansion.*/
13675 type = make_pack_expansion (type);
13676 else
13677 error ("non-parameter %qs cannot be a parameter pack", name);
13680 if ((decl_context == FIELD || decl_context == PARM)
13681 && !processing_template_decl
13682 && variably_modified_type_p (type, NULL_TREE))
13684 if (decl_context == FIELD)
13685 error_at (id_loc,
13686 "data member may not have variably modified type %qT", type);
13687 else
13688 error_at (id_loc,
13689 "parameter may not have variably modified type %qT", type);
13690 type = error_mark_node;
13693 if (explicitp == 1 || (explicitp && friendp))
13695 /* [dcl.fct.spec] (C++11) The explicit specifier shall be used only
13696 in the declaration of a constructor or conversion function within
13697 a class definition. */
13698 if (!current_class_type)
13699 error_at (declspecs->locations[ds_explicit],
13700 "%<explicit%> outside class declaration");
13701 else if (friendp)
13702 error_at (declspecs->locations[ds_explicit],
13703 "%<explicit%> in friend declaration");
13704 else
13705 error_at (declspecs->locations[ds_explicit],
13706 "only declarations of constructors and conversion operators "
13707 "can be %<explicit%>");
13708 explicitp = 0;
13711 if (storage_class == sc_mutable)
13713 location_t sloc = declspecs->locations[ds_storage_class];
13714 if (decl_context != FIELD || friendp)
13716 error_at (sloc, "non-member %qs cannot be declared %<mutable%>",
13717 name);
13718 storage_class = sc_none;
13720 else if (decl_context == TYPENAME || typedef_p)
13722 error_at (sloc,
13723 "non-object member %qs cannot be declared %<mutable%>",
13724 name);
13725 storage_class = sc_none;
13727 else if (FUNC_OR_METHOD_TYPE_P (type))
13729 error_at (sloc, "function %qs cannot be declared %<mutable%>",
13730 name);
13731 storage_class = sc_none;
13733 else if (staticp)
13735 error_at (sloc, "%<static%> %qs cannot be declared %<mutable%>",
13736 name);
13737 storage_class = sc_none;
13739 else if (type_quals & TYPE_QUAL_CONST)
13741 error_at (sloc, "%<const%> %qs cannot be declared %<mutable%>",
13742 name);
13743 storage_class = sc_none;
13745 else if (TYPE_REF_P (type))
13747 permerror (sloc, "reference %qs cannot be declared %<mutable%>",
13748 name);
13749 storage_class = sc_none;
13753 /* If this is declaring a typedef name, return a TYPE_DECL. */
13754 if (typedef_p && decl_context != TYPENAME)
13756 bool alias_p = decl_spec_seq_has_spec_p (declspecs, ds_alias);
13757 tree decl;
13759 if (funcdef_flag)
13761 if (decl_context == NORMAL)
13762 error_at (id_loc,
13763 "typedef may not be a function definition");
13764 else
13765 error_at (id_loc,
13766 "typedef may not be a member function definition");
13767 return error_mark_node;
13770 /* This declaration:
13772 typedef void f(int) const;
13774 declares a function type which is not a member of any
13775 particular class, but which is cv-qualified; for
13776 example "f S::*" declares a pointer to a const-qualified
13777 member function of S. We record the cv-qualification in the
13778 function type. */
13779 if ((rqual || memfn_quals) && TREE_CODE (type) == FUNCTION_TYPE)
13781 type = apply_memfn_quals (type, memfn_quals, rqual);
13783 /* We have now dealt with these qualifiers. */
13784 memfn_quals = TYPE_UNQUALIFIED;
13785 rqual = REF_QUAL_NONE;
13788 if (type_uses_auto (type))
13790 if (alias_p)
13791 error_at (declspecs->locations[ds_type_spec],
13792 "%<auto%> not allowed in alias declaration");
13793 else
13794 error_at (declspecs->locations[ds_type_spec],
13795 "typedef declared %<auto%>");
13796 type = error_mark_node;
13799 if (reqs)
13800 error_at (location_of (reqs), "requires-clause on typedef");
13802 if (id_declarator && declarator->u.id.qualifying_scope)
13804 error_at (id_loc, "typedef name may not be a nested-name-specifier");
13805 type = error_mark_node;
13808 if (decl_context == FIELD)
13809 decl = build_lang_decl_loc (id_loc, TYPE_DECL, unqualified_id, type);
13810 else
13811 decl = build_decl (id_loc, TYPE_DECL, unqualified_id, type);
13813 if (decl_context != FIELD)
13815 if (!current_function_decl)
13816 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
13817 else if (DECL_MAYBE_IN_CHARGE_CDTOR_P (current_function_decl))
13818 /* The TYPE_DECL is "abstract" because there will be
13819 clones of this constructor/destructor, and there will
13820 be copies of this TYPE_DECL generated in those
13821 clones. The decloning optimization (for space) may
13822 revert this subsequently if it determines that
13823 the clones should share a common implementation. */
13824 DECL_ABSTRACT_P (decl) = true;
13826 set_originating_module (decl);
13828 else if (current_class_type
13829 && constructor_name_p (unqualified_id, current_class_type))
13830 permerror (id_loc, "ISO C++ forbids nested type %qD with same name "
13831 "as enclosing class",
13832 unqualified_id);
13834 /* If the user declares "typedef struct {...} foo" then the
13835 struct will have an anonymous name. Fill that name in now.
13836 Nothing can refer to it, so nothing needs know about the name
13837 change. */
13838 if (type != error_mark_node
13839 && unqualified_id
13840 && TYPE_NAME (type)
13841 && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL
13842 && TYPE_UNNAMED_P (type)
13843 && declspecs->type_definition_p
13844 && attributes_naming_typedef_ok (*attrlist)
13845 && cp_type_quals (type) == TYPE_UNQUALIFIED)
13846 name_unnamed_type (type, decl);
13848 if (signed_p
13849 || (typedef_decl && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl)))
13850 C_TYPEDEF_EXPLICITLY_SIGNED (decl) = 1;
13852 bad_specifiers (decl, BSP_TYPE, virtualp,
13853 memfn_quals != TYPE_UNQUALIFIED,
13854 inlinep, friendp, raises != NULL_TREE,
13855 declspecs->locations);
13857 if (alias_p)
13858 /* Acknowledge that this was written:
13859 `using analias = atype;'. */
13860 TYPE_DECL_ALIAS_P (decl) = 1;
13862 return decl;
13865 /* Detect the case of an array type of unspecified size
13866 which came, as such, direct from a typedef name.
13867 We must copy the type, so that the array's domain can be
13868 individually set by the object's initializer. */
13870 if (type && typedef_type
13871 && TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type)
13872 && TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (typedef_type))
13873 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
13875 /* Detect where we're using a typedef of function type to declare a
13876 function. PARMS will not be set, so we must create it now. */
13878 if (type == typedef_type && TREE_CODE (type) == FUNCTION_TYPE)
13880 tree decls = NULL_TREE;
13881 tree args;
13883 for (args = TYPE_ARG_TYPES (type);
13884 args && args != void_list_node;
13885 args = TREE_CHAIN (args))
13887 tree decl = cp_build_parm_decl (NULL_TREE, NULL_TREE,
13888 TREE_VALUE (args));
13890 DECL_CHAIN (decl) = decls;
13891 decls = decl;
13894 parms = nreverse (decls);
13896 if (decl_context != TYPENAME)
13898 /* The qualifiers on the function type become the qualifiers on
13899 the non-static member function. */
13900 memfn_quals |= type_memfn_quals (type);
13901 rqual = type_memfn_rqual (type);
13902 type_quals = TYPE_UNQUALIFIED;
13903 raises = TYPE_RAISES_EXCEPTIONS (type);
13907 /* If this is a type name (such as, in a cast or sizeof),
13908 compute the type and return it now. */
13910 if (decl_context == TYPENAME)
13912 /* Note that here we don't care about type_quals. */
13914 /* Special case: "friend class foo" looks like a TYPENAME context. */
13915 if (friendp)
13917 if (inlinep)
13919 error ("%<inline%> specified for friend class declaration");
13920 inlinep = 0;
13923 if (!current_aggr)
13925 /* Don't allow friend declaration without a class-key. */
13926 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
13927 permerror (input_location, "template parameters cannot be friends");
13928 else if (TREE_CODE (type) == TYPENAME_TYPE)
13929 permerror (input_location, "friend declaration requires class-key, "
13930 "i.e. %<friend class %T::%D%>",
13931 TYPE_CONTEXT (type), TYPENAME_TYPE_FULLNAME (type));
13932 else
13933 permerror (input_location, "friend declaration requires class-key, "
13934 "i.e. %<friend %#T%>",
13935 type);
13938 /* Only try to do this stuff if we didn't already give up. */
13939 if (type != integer_type_node)
13941 /* A friendly class? */
13942 if (current_class_type)
13943 make_friend_class (current_class_type, TYPE_MAIN_VARIANT (type),
13944 /*complain=*/true);
13945 else
13946 error ("trying to make class %qT a friend of global scope",
13947 type);
13949 type = void_type_node;
13952 else if (memfn_quals || rqual)
13954 if (ctype == NULL_TREE
13955 && TREE_CODE (type) == METHOD_TYPE)
13956 ctype = TYPE_METHOD_BASETYPE (type);
13958 if (ctype)
13959 type = build_memfn_type (type, ctype, memfn_quals, rqual);
13960 /* Core issue #547: need to allow this in template type args.
13961 Allow it in general in C++11 for alias-declarations. */
13962 else if ((template_type_arg || cxx_dialect >= cxx11)
13963 && TREE_CODE (type) == FUNCTION_TYPE)
13964 type = apply_memfn_quals (type, memfn_quals, rqual);
13965 else
13966 error ("invalid qualifiers on non-member function type");
13969 if (reqs)
13970 error_at (location_of (reqs), "requires-clause on type-id");
13972 return type;
13974 else if (unqualified_id == NULL_TREE && decl_context != PARM
13975 && decl_context != CATCHPARM
13976 && TREE_CODE (type) != UNION_TYPE
13977 && ! bitfield
13978 && innermost_code != cdk_decomp)
13980 error ("abstract declarator %qT used as declaration", type);
13981 return error_mark_node;
13984 if (!FUNC_OR_METHOD_TYPE_P (type))
13986 /* Only functions may be declared using an operator-function-id. */
13987 if (dname && IDENTIFIER_ANY_OP_P (dname))
13989 error_at (id_loc, "declaration of %qD as non-function", dname);
13990 return error_mark_node;
13993 if (reqs)
13994 error_at (location_of (reqs),
13995 "requires-clause on declaration of non-function type %qT",
13996 type);
13999 /* We don't check parameter types here because we can emit a better
14000 error message later. */
14001 if (decl_context != PARM)
14003 type = check_var_type (unqualified_id, type, id_loc);
14004 if (type == error_mark_node)
14005 return error_mark_node;
14008 /* Now create the decl, which may be a VAR_DECL, a PARM_DECL
14009 or a FUNCTION_DECL, depending on DECL_CONTEXT and TYPE. */
14011 if (decl_context == PARM || decl_context == CATCHPARM)
14013 if (ctype || in_namespace)
14014 error ("cannot use %<::%> in parameter declaration");
14016 tree auto_node = type_uses_auto (type);
14017 if (auto_node && !(cxx_dialect >= cxx17 && template_parm_flag))
14019 if (cxx_dialect >= cxx14)
14021 if (decl_context == PARM && AUTO_IS_DECLTYPE (auto_node))
14022 error_at (typespec_loc,
14023 "cannot declare a parameter with %<decltype(auto)%>");
14024 else if (tree c = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14026 auto_diagnostic_group g;
14027 gcc_rich_location richloc (typespec_loc);
14028 richloc.add_fixit_insert_after ("<>");
14029 error_at (&richloc,
14030 "missing template argument list after %qE; template "
14031 "placeholder not permitted in parameter", c);
14032 if (decl_context == PARM && cxx_dialect >= cxx20)
14033 inform (typespec_loc, "or use %<auto%> for an "
14034 "abbreviated function template");
14035 inform (DECL_SOURCE_LOCATION (c), "%qD declared here", c);
14037 else
14038 error_at (typespec_loc,
14039 "%<auto%> parameter not permitted in this context");
14041 else
14042 error_at (typespec_loc, "parameter declared %<auto%>");
14043 type = error_mark_node;
14046 /* A parameter declared as an array of T is really a pointer to T.
14047 One declared as a function is really a pointer to a function.
14048 One declared as a member is really a pointer to member. */
14050 if (TREE_CODE (type) == ARRAY_TYPE)
14052 /* Transfer const-ness of array into that of type pointed to. */
14053 type = build_pointer_type (TREE_TYPE (type));
14054 type_quals = TYPE_UNQUALIFIED;
14055 array_parameter_p = true;
14057 else if (TREE_CODE (type) == FUNCTION_TYPE)
14058 type = build_pointer_type (type);
14061 if (ctype && TREE_CODE (type) == FUNCTION_TYPE && staticp < 2
14062 && !(unqualified_id
14063 && identifier_p (unqualified_id)
14064 && IDENTIFIER_NEWDEL_OP_P (unqualified_id)))
14066 cp_cv_quals real_quals = memfn_quals;
14067 if (cxx_dialect < cxx14 && constexpr_p
14068 && sfk != sfk_constructor && sfk != sfk_destructor)
14069 real_quals |= TYPE_QUAL_CONST;
14070 type = build_memfn_type (type, ctype, real_quals, rqual);
14074 tree decl = NULL_TREE;
14076 if (decl_context == PARM)
14078 decl = cp_build_parm_decl (NULL_TREE, unqualified_id, type);
14079 DECL_ARRAY_PARAMETER_P (decl) = array_parameter_p;
14081 bad_specifiers (decl, BSP_PARM, virtualp,
14082 memfn_quals != TYPE_UNQUALIFIED,
14083 inlinep, friendp, raises != NULL_TREE,
14084 declspecs->locations);
14086 else if (decl_context == FIELD)
14088 if (!staticp && !friendp && !FUNC_OR_METHOD_TYPE_P (type))
14089 if (tree auto_node = type_uses_auto (type))
14091 location_t tloc = declspecs->locations[ds_type_spec];
14092 if (CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14093 error_at (tloc, "invalid use of template-name %qE without an "
14094 "argument list",
14095 CLASS_PLACEHOLDER_TEMPLATE (auto_node));
14096 else
14097 error_at (tloc, "non-static data member declared with "
14098 "placeholder %qT", auto_node);
14099 type = error_mark_node;
14102 /* The C99 flexible array extension. */
14103 if (!staticp && TREE_CODE (type) == ARRAY_TYPE
14104 && TYPE_DOMAIN (type) == NULL_TREE)
14106 if (ctype
14107 && (TREE_CODE (ctype) == UNION_TYPE
14108 || TREE_CODE (ctype) == QUAL_UNION_TYPE))
14110 error_at (id_loc, "flexible array member in union");
14111 type = error_mark_node;
14113 else
14115 /* Array is a flexible member. */
14116 if (name)
14117 pedwarn (id_loc, OPT_Wpedantic,
14118 "ISO C++ forbids flexible array member %qs", name);
14119 else
14120 pedwarn (input_location, OPT_Wpedantic,
14121 "ISO C++ forbids flexible array members");
14123 /* Flexible array member has a null domain. */
14124 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
14128 if (type == error_mark_node)
14130 /* Happens when declaring arrays of sizes which
14131 are error_mark_node, for example. */
14132 decl = NULL_TREE;
14134 else if (in_namespace && !friendp)
14136 /* Something like struct S { int N::j; }; */
14137 error_at (id_loc, "invalid use of %<::%>");
14138 return error_mark_node;
14140 else if (FUNC_OR_METHOD_TYPE_P (type) && unqualified_id)
14142 int publicp = 0;
14143 tree function_context;
14145 if (friendp == 0)
14147 /* This should never happen in pure C++ (the check
14148 could be an assert). It could happen in
14149 Objective-C++ if someone writes invalid code that
14150 uses a function declaration for an instance
14151 variable or property (instance variables and
14152 properties are parsed as FIELD_DECLs, but they are
14153 part of an Objective-C class, not a C++ class).
14154 That code is invalid and is caught by this
14155 check. */
14156 if (!ctype)
14158 error ("declaration of function %qD in invalid context",
14159 unqualified_id);
14160 return error_mark_node;
14163 /* ``A union may [ ... ] not [ have ] virtual functions.''
14164 ARM 9.5 */
14165 if (virtualp && TREE_CODE (ctype) == UNION_TYPE)
14167 error_at (declspecs->locations[ds_virtual],
14168 "function %qD declared %<virtual%> inside a union",
14169 unqualified_id);
14170 return error_mark_node;
14173 if (virtualp
14174 && identifier_p (unqualified_id)
14175 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14177 error_at (declspecs->locations[ds_virtual],
14178 "%qD cannot be declared %<virtual%>, since it "
14179 "is always static", unqualified_id);
14180 virtualp = 0;
14184 /* Check that the name used for a destructor makes sense. */
14185 if (sfk == sfk_destructor)
14187 tree uqname = id_declarator->u.id.unqualified_name;
14189 if (!ctype)
14191 gcc_assert (friendp);
14192 error_at (id_loc, "expected qualified name in friend "
14193 "declaration for destructor %qD", uqname);
14194 return error_mark_node;
14197 if (!check_dtor_name (ctype, TREE_OPERAND (uqname, 0)))
14199 error_at (id_loc, "declaration of %qD as member of %qT",
14200 uqname, ctype);
14201 return error_mark_node;
14203 if (concept_p)
14205 error_at (declspecs->locations[ds_concept],
14206 "a destructor cannot be %qs", "concept");
14207 return error_mark_node;
14209 if (constexpr_p && cxx_dialect < cxx20)
14211 error_at (declspecs->locations[ds_constexpr],
14212 "%<constexpr%> destructors only available"
14213 " with %<-std=c++20%> or %<-std=gnu++20%>");
14214 return error_mark_node;
14216 if (consteval_p)
14218 error_at (declspecs->locations[ds_consteval],
14219 "a destructor cannot be %qs", "consteval");
14220 return error_mark_node;
14223 else if (sfk == sfk_constructor && friendp && !ctype)
14225 error ("expected qualified name in friend declaration "
14226 "for constructor %qD",
14227 id_declarator->u.id.unqualified_name);
14228 return error_mark_node;
14230 if (sfk == sfk_constructor)
14231 if (concept_p)
14233 error_at (declspecs->locations[ds_concept],
14234 "a constructor cannot be %<concept%>");
14235 return error_mark_node;
14237 if (concept_p)
14239 error_at (declspecs->locations[ds_concept],
14240 "a concept cannot be a member function");
14241 concept_p = false;
14243 else if (consteval_p
14244 && identifier_p (unqualified_id)
14245 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14247 error_at (declspecs->locations[ds_consteval],
14248 "%qD cannot be %qs", unqualified_id, "consteval");
14249 consteval_p = false;
14252 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14254 tree tmpl = TREE_OPERAND (unqualified_id, 0);
14255 if (variable_template_p (tmpl))
14257 error_at (id_loc, "specialization of variable template "
14258 "%qD declared as function", tmpl);
14259 inform (DECL_SOURCE_LOCATION (tmpl),
14260 "variable template declared here");
14261 return error_mark_node;
14265 /* Tell grokfndecl if it needs to set TREE_PUBLIC on the node. */
14266 function_context
14267 = (ctype != NULL_TREE
14268 ? decl_function_context (TYPE_MAIN_DECL (ctype)) : NULL_TREE);
14269 publicp = ((! friendp || ! staticp)
14270 && function_context == NULL_TREE);
14272 decl = grokfndecl (ctype, type,
14273 TREE_CODE (unqualified_id) != TEMPLATE_ID_EXPR
14274 ? unqualified_id : dname,
14275 parms,
14276 unqualified_id,
14277 declspecs,
14278 reqs,
14279 virtualp, flags, memfn_quals, rqual, raises,
14280 friendp ? -1 : 0, friendp, publicp,
14281 inlinep | (2 * constexpr_p) | (4 * concept_p)
14282 | (8 * consteval_p),
14283 initialized == SD_DELETED, sfk,
14284 funcdef_flag, late_return_type_p,
14285 template_count, in_namespace,
14286 attrlist, id_loc);
14287 decl = set_virt_specifiers (decl, virt_specifiers);
14288 if (decl == NULL_TREE)
14289 return error_mark_node;
14290 #if 0
14291 /* This clobbers the attrs stored in `decl' from `attrlist'. */
14292 /* The decl and setting of decl_attr is also turned off. */
14293 decl = build_decl_attribute_variant (decl, decl_attr);
14294 #endif
14296 /* [class.conv.ctor]
14298 A constructor declared without the function-specifier
14299 explicit that can be called with a single parameter
14300 specifies a conversion from the type of its first
14301 parameter to the type of its class. Such a constructor
14302 is called a converting constructor. */
14303 if (explicitp == 2)
14304 DECL_NONCONVERTING_P (decl) = 1;
14306 if (declspecs->explicit_specifier)
14307 store_explicit_specifier (decl, declspecs->explicit_specifier);
14309 else if (!staticp
14310 && ((current_class_type
14311 && same_type_p (type, current_class_type))
14312 || (!dependent_type_p (type)
14313 && !COMPLETE_TYPE_P (complete_type (type))
14314 && (!complete_or_array_type_p (type)
14315 || initialized == SD_UNINITIALIZED))))
14317 if (TREE_CODE (type) != ARRAY_TYPE
14318 || !COMPLETE_TYPE_P (TREE_TYPE (type)))
14320 if (unqualified_id)
14322 error_at (id_loc, "field %qD has incomplete type %qT",
14323 unqualified_id, type);
14324 cxx_incomplete_type_inform (strip_array_types (type));
14326 else
14327 error ("name %qT has incomplete type", type);
14329 type = error_mark_node;
14330 decl = NULL_TREE;
14333 else if (!verify_type_context (input_location,
14334 staticp
14335 ? TCTX_STATIC_STORAGE
14336 : TCTX_FIELD, type))
14338 type = error_mark_node;
14339 decl = NULL_TREE;
14341 else
14343 if (friendp)
14345 if (unqualified_id)
14346 error_at (id_loc,
14347 "%qE is neither function nor member function; "
14348 "cannot be declared friend", unqualified_id);
14349 else
14350 error ("unnamed field is neither function nor member "
14351 "function; cannot be declared friend");
14352 return error_mark_node;
14354 decl = NULL_TREE;
14357 if (friendp)
14359 /* Packages tend to use GNU attributes on friends, so we only
14360 warn for standard attributes. */
14361 if (attrlist
14362 && !funcdef_flag
14363 && cxx11_attribute_p (*attrlist)
14364 && !all_attributes_are_contracts_p (*attrlist))
14366 *attrlist = NULL_TREE;
14367 if (warning_at (id_loc, OPT_Wattributes, "attribute ignored"))
14368 inform (id_loc, "an attribute that appertains to a friend "
14369 "declaration that is not a definition is ignored");
14371 /* Friends are treated specially. */
14372 if (ctype == current_class_type)
14373 ; /* We already issued a permerror. */
14374 else if (decl && DECL_NAME (decl))
14376 set_originating_module (decl, true);
14378 if (initialized)
14379 /* Kludge: We need funcdef_flag to be true in do_friend for
14380 in-class defaulted functions, but that breaks grokfndecl.
14381 So set it here. */
14382 funcdef_flag = true;
14384 cplus_decl_attributes (&decl, *attrlist, 0);
14385 *attrlist = NULL_TREE;
14387 decl = do_friend (ctype, unqualified_id, decl,
14388 flags, funcdef_flag);
14389 return decl;
14391 else
14392 return error_mark_node;
14395 /* Structure field. It may not be a function, except for C++. */
14397 if (decl == NULL_TREE)
14399 if (staticp)
14401 /* C++ allows static class members. All other work
14402 for this is done by grokfield. */
14403 decl = build_lang_decl_loc (id_loc, VAR_DECL,
14404 unqualified_id, type);
14405 set_linkage_for_static_data_member (decl);
14406 if (concept_p)
14407 error_at (declspecs->locations[ds_concept],
14408 "static data member %qE declared %qs",
14409 unqualified_id, "concept");
14410 else if (constexpr_p && !initialized)
14412 error_at (DECL_SOURCE_LOCATION (decl),
14413 "%<constexpr%> static data member %qD must "
14414 "have an initializer", decl);
14415 constexpr_p = false;
14417 if (consteval_p)
14418 error_at (declspecs->locations[ds_consteval],
14419 "static data member %qE declared %qs",
14420 unqualified_id, "consteval");
14422 if (inlinep)
14423 mark_inline_variable (decl, declspecs->locations[ds_inline]);
14425 if (!DECL_VAR_DECLARED_INLINE_P (decl)
14426 && !(cxx_dialect >= cxx17 && constexpr_p))
14427 /* Even if there is an in-class initialization, DECL
14428 is considered undefined until an out-of-class
14429 definition is provided, unless this is an inline
14430 variable. */
14431 DECL_EXTERNAL (decl) = 1;
14433 if (thread_p)
14435 CP_DECL_THREAD_LOCAL_P (decl) = true;
14436 if (!processing_template_decl)
14437 set_decl_tls_model (decl, decl_default_tls_model (decl));
14438 if (declspecs->gnu_thread_keyword_p)
14439 SET_DECL_GNU_TLS_P (decl);
14442 /* Set the constraints on the declaration. */
14443 bool memtmpl = (current_template_depth
14444 > template_class_depth (current_class_type));
14445 if (memtmpl)
14447 tree ci = current_template_constraints ();
14448 set_constraints (decl, ci);
14451 else
14453 if (concept_p)
14455 error_at (declspecs->locations[ds_concept],
14456 "non-static data member %qE declared %qs",
14457 unqualified_id, "concept");
14458 concept_p = false;
14459 constexpr_p = false;
14461 else if (constexpr_p)
14463 error_at (declspecs->locations[ds_constexpr],
14464 "non-static data member %qE declared %qs",
14465 unqualified_id, "constexpr");
14466 constexpr_p = false;
14468 if (constinit_p)
14470 error_at (declspecs->locations[ds_constinit],
14471 "non-static data member %qE declared %qs",
14472 unqualified_id, "constinit");
14473 constinit_p = false;
14475 if (consteval_p)
14477 error_at (declspecs->locations[ds_consteval],
14478 "non-static data member %qE declared %qs",
14479 unqualified_id, "consteval");
14480 consteval_p = false;
14482 decl = build_decl (id_loc, FIELD_DECL, unqualified_id, type);
14483 DECL_NONADDRESSABLE_P (decl) = bitfield;
14484 if (bitfield && !unqualified_id)
14485 DECL_PADDING_P (decl) = 1;
14487 if (storage_class == sc_mutable)
14489 DECL_MUTABLE_P (decl) = 1;
14490 storage_class = sc_none;
14493 if (initialized)
14495 /* An attempt is being made to initialize a non-static
14496 member. This is new in C++11. */
14497 maybe_warn_cpp0x (CPP0X_NSDMI, init_loc);
14499 /* If this has been parsed with static storage class, but
14500 errors forced staticp to be cleared, ensure NSDMI is
14501 not present. */
14502 if (declspecs->storage_class == sc_static)
14503 DECL_INITIAL (decl) = error_mark_node;
14507 bad_specifiers (decl, BSP_FIELD, virtualp,
14508 memfn_quals != TYPE_UNQUALIFIED,
14509 staticp ? false : inlinep, friendp,
14510 raises != NULL_TREE,
14511 declspecs->locations);
14514 else if (FUNC_OR_METHOD_TYPE_P (type))
14516 tree original_name;
14517 int publicp = 0;
14519 if (!unqualified_id)
14520 return error_mark_node;
14522 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14523 original_name = dname;
14524 else
14525 original_name = unqualified_id;
14526 // FIXME:gcc_assert (original_name == dname);
14528 if (storage_class == sc_auto)
14529 error_at (declspecs->locations[ds_storage_class],
14530 "storage class %<auto%> invalid for function %qs", name);
14531 else if (storage_class == sc_register)
14532 error_at (declspecs->locations[ds_storage_class],
14533 "storage class %<register%> invalid for function %qs",
14534 name);
14535 else if (thread_p)
14537 if (declspecs->gnu_thread_keyword_p)
14538 error_at (declspecs->locations[ds_thread],
14539 "storage class %<__thread%> invalid for function %qs",
14540 name);
14541 else
14542 error_at (declspecs->locations[ds_thread],
14543 "storage class %<thread_local%> invalid for "
14544 "function %qs", name);
14547 if (virt_specifiers)
14548 error ("virt-specifiers in %qs not allowed outside a class "
14549 "definition", name);
14550 /* Function declaration not at top level.
14551 Storage classes other than `extern' are not allowed
14552 and `extern' makes no difference. */
14553 if (! toplevel_bindings_p ()
14554 && (storage_class == sc_static
14555 || decl_spec_seq_has_spec_p (declspecs, ds_inline))
14556 && pedantic)
14558 if (storage_class == sc_static)
14559 pedwarn (declspecs->locations[ds_storage_class], OPT_Wpedantic,
14560 "%<static%> specifier invalid for function %qs "
14561 "declared out of global scope", name);
14562 else
14563 pedwarn (declspecs->locations[ds_inline], OPT_Wpedantic,
14564 "%<inline%> specifier invalid for function %qs "
14565 "declared out of global scope", name);
14568 if (ctype == NULL_TREE)
14570 if (virtualp)
14572 error ("virtual non-class function %qs", name);
14573 virtualp = 0;
14575 else if (sfk == sfk_constructor
14576 || sfk == sfk_destructor)
14578 error (funcdef_flag
14579 ? G_("%qs defined in a non-class scope")
14580 : G_("%qs declared in a non-class scope"), name);
14581 sfk = sfk_none;
14584 if (consteval_p
14585 && identifier_p (unqualified_id)
14586 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14588 error_at (declspecs->locations[ds_consteval],
14589 "%qD cannot be %qs", unqualified_id, "consteval");
14590 consteval_p = false;
14593 /* Record whether the function is public. */
14594 publicp = (ctype != NULL_TREE
14595 || storage_class != sc_static);
14597 decl = grokfndecl (ctype, type, original_name, parms, unqualified_id,
14598 declspecs,
14599 reqs, virtualp, flags, memfn_quals, rqual, raises,
14600 1, friendp,
14601 publicp,
14602 inlinep | (2 * constexpr_p) | (4 * concept_p)
14603 | (8 * consteval_p),
14604 initialized == SD_DELETED,
14605 sfk,
14606 funcdef_flag,
14607 late_return_type_p,
14608 template_count, in_namespace, attrlist,
14609 id_loc);
14610 if (decl == NULL_TREE)
14611 return error_mark_node;
14613 if (explicitp == 2)
14614 DECL_NONCONVERTING_P (decl) = 1;
14615 if (staticp == 1)
14617 int invalid_static = 0;
14619 /* Don't allow a static member function in a class, and forbid
14620 declaring main to be static. */
14621 if (TREE_CODE (type) == METHOD_TYPE)
14623 permerror (input_location, "cannot declare member function %qD to have "
14624 "static linkage", decl);
14625 invalid_static = 1;
14627 else if (current_function_decl)
14629 /* 7.1.1: There can be no static function declarations within a
14630 block. */
14631 error_at (declspecs->locations[ds_storage_class],
14632 "cannot declare static function inside another function");
14633 invalid_static = 1;
14636 if (invalid_static)
14638 staticp = 0;
14639 storage_class = sc_none;
14642 if (declspecs->explicit_specifier)
14643 store_explicit_specifier (decl, declspecs->explicit_specifier);
14645 else
14647 /* It's a variable. */
14649 /* An uninitialized decl with `extern' is a reference. */
14650 decl = grokvardecl (type, dname, unqualified_id,
14651 declspecs,
14652 initialized,
14653 type_quals,
14654 inlinep,
14655 concept_p,
14656 template_count,
14657 ctype ? ctype : in_namespace,
14658 id_loc);
14659 if (decl == NULL_TREE)
14660 return error_mark_node;
14662 bad_specifiers (decl, BSP_VAR, virtualp,
14663 memfn_quals != TYPE_UNQUALIFIED,
14664 inlinep, friendp, raises != NULL_TREE,
14665 declspecs->locations);
14667 if (ctype)
14669 DECL_CONTEXT (decl) = ctype;
14670 if (staticp == 1)
14672 permerror (declspecs->locations[ds_storage_class],
14673 "%<static%> may not be used when defining "
14674 "(as opposed to declaring) a static data member");
14675 staticp = 0;
14676 storage_class = sc_none;
14678 if (storage_class == sc_register && TREE_STATIC (decl))
14680 error ("static member %qD declared %<register%>", decl);
14681 storage_class = sc_none;
14683 if (storage_class == sc_extern && pedantic)
14685 pedwarn (input_location, OPT_Wpedantic,
14686 "cannot explicitly declare member %q#D to have "
14687 "extern linkage", decl);
14688 storage_class = sc_none;
14691 else if (constexpr_p && DECL_EXTERNAL (decl))
14693 error_at (DECL_SOURCE_LOCATION (decl),
14694 "declaration of %<constexpr%> variable %qD "
14695 "is not a definition", decl);
14696 constexpr_p = false;
14698 if (consteval_p)
14700 error_at (DECL_SOURCE_LOCATION (decl),
14701 "a variable cannot be declared %<consteval%>");
14702 consteval_p = false;
14705 if (inlinep)
14706 mark_inline_variable (decl, declspecs->locations[ds_inline]);
14707 if (innermost_code == cdk_decomp)
14709 gcc_assert (declarator && declarator->kind == cdk_decomp);
14710 DECL_SOURCE_LOCATION (decl) = id_loc;
14711 DECL_ARTIFICIAL (decl) = 1;
14712 fit_decomposition_lang_decl (decl, NULL_TREE);
14716 if (VAR_P (decl) && !initialized)
14717 if (tree auto_node = type_uses_auto (type))
14718 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14720 location_t loc = declspecs->locations[ds_type_spec];
14721 error_at (loc, "declaration of %q#D has no initializer", decl);
14722 TREE_TYPE (decl) = error_mark_node;
14725 if (storage_class == sc_extern && initialized && !funcdef_flag)
14727 if (toplevel_bindings_p ())
14729 /* It's common practice (and completely valid) to have a const
14730 be initialized and declared extern. */
14731 if (!(type_quals & TYPE_QUAL_CONST))
14732 warning_at (DECL_SOURCE_LOCATION (decl), 0,
14733 "%qs initialized and declared %<extern%>", name);
14735 else
14737 error_at (DECL_SOURCE_LOCATION (decl),
14738 "%qs has both %<extern%> and initializer", name);
14739 return error_mark_node;
14743 /* Record `register' declaration for warnings on &
14744 and in case doing stupid register allocation. */
14746 if (storage_class == sc_register)
14748 DECL_REGISTER (decl) = 1;
14749 /* Warn about register storage specifiers on PARM_DECLs. */
14750 if (TREE_CODE (decl) == PARM_DECL)
14752 if (cxx_dialect >= cxx17)
14753 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
14754 "ISO C++17 does not allow %<register%> storage "
14755 "class specifier");
14756 else
14757 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
14758 "%<register%> storage class specifier used");
14761 else if (storage_class == sc_extern)
14762 DECL_THIS_EXTERN (decl) = 1;
14763 else if (storage_class == sc_static)
14764 DECL_THIS_STATIC (decl) = 1;
14766 if (VAR_P (decl))
14768 /* Set constexpr flag on vars (functions got it in grokfndecl). */
14769 if (constexpr_p)
14770 DECL_DECLARED_CONSTEXPR_P (decl) = true;
14771 /* And the constinit flag (which only applies to variables). */
14772 else if (constinit_p)
14773 DECL_DECLARED_CONSTINIT_P (decl) = true;
14775 else if (TREE_CODE (decl) == FUNCTION_DECL)
14777 /* If we saw a return type, record its location. */
14778 location_t loc = declspecs->locations[ds_type_spec];
14779 if (loc == UNKNOWN_LOCATION)
14780 /* Build DECL_RESULT in start_preparsed_function. */;
14781 else if (!DECL_RESULT (decl))
14783 tree restype = TREE_TYPE (TREE_TYPE (decl));
14784 tree resdecl = build_decl (loc, RESULT_DECL, 0, restype);
14785 DECL_ARTIFICIAL (resdecl) = 1;
14786 DECL_IGNORED_P (resdecl) = 1;
14787 DECL_RESULT (decl) = resdecl;
14789 else if (funcdef_flag)
14790 DECL_SOURCE_LOCATION (DECL_RESULT (decl)) = loc;
14793 /* Record constancy and volatility on the DECL itself . There's
14794 no need to do this when processing a template; we'll do this
14795 for the instantiated declaration based on the type of DECL. */
14796 if (!processing_template_decl)
14797 cp_apply_type_quals_to_decl (type_quals, decl);
14799 return decl;
14803 /* Subroutine of start_function. Ensure that each of the parameter
14804 types (as listed in PARMS) is complete, as is required for a
14805 function definition. */
14807 static void
14808 require_complete_types_for_parms (tree parms)
14810 for (; parms; parms = DECL_CHAIN (parms))
14812 if (dependent_type_p (TREE_TYPE (parms)))
14813 continue;
14814 if (!VOID_TYPE_P (TREE_TYPE (parms))
14815 && complete_type_or_else (TREE_TYPE (parms), parms))
14817 relayout_decl (parms);
14818 DECL_ARG_TYPE (parms) = type_passed_as (TREE_TYPE (parms));
14820 abstract_virtuals_error (parms, TREE_TYPE (parms));
14821 maybe_warn_parm_abi (TREE_TYPE (parms),
14822 DECL_SOURCE_LOCATION (parms));
14824 else
14825 /* grokparms or complete_type_or_else will have already issued
14826 an error. */
14827 TREE_TYPE (parms) = error_mark_node;
14831 /* Returns nonzero if T is a local variable. */
14834 local_variable_p (const_tree t)
14836 if ((VAR_P (t)
14837 && (DECL_LOCAL_DECL_P (t)
14838 || !DECL_CONTEXT (t)
14839 || TREE_CODE (DECL_CONTEXT (t)) == FUNCTION_DECL))
14840 || (TREE_CODE (t) == PARM_DECL))
14841 return 1;
14843 return 0;
14846 /* Like local_variable_p, but suitable for use as a tree-walking
14847 function. */
14849 static tree
14850 local_variable_p_walkfn (tree *tp, int *walk_subtrees,
14851 void * /*data*/)
14853 if (unevaluated_p (TREE_CODE (*tp)))
14855 /* DR 2082 permits local variables in unevaluated contexts
14856 within a default argument. */
14857 *walk_subtrees = 0;
14858 return NULL_TREE;
14861 if (local_variable_p (*tp)
14862 && (!DECL_ARTIFICIAL (*tp) || DECL_NAME (*tp) == this_identifier))
14863 return *tp;
14864 else if (TYPE_P (*tp))
14865 *walk_subtrees = 0;
14867 return NULL_TREE;
14870 /* Check that ARG, which is a default-argument expression for a
14871 parameter DECL, is valid. Returns ARG, or ERROR_MARK_NODE, if
14872 something goes wrong. DECL may also be a _TYPE node, rather than a
14873 DECL, if there is no DECL available. */
14875 tree
14876 check_default_argument (tree decl, tree arg, tsubst_flags_t complain)
14878 tree var;
14879 tree decl_type;
14881 if (TREE_CODE (arg) == DEFERRED_PARSE)
14882 /* We get a DEFERRED_PARSE when looking at an in-class declaration
14883 with a default argument. Ignore the argument for now; we'll
14884 deal with it after the class is complete. */
14885 return arg;
14887 if (TYPE_P (decl))
14889 decl_type = decl;
14890 decl = NULL_TREE;
14892 else
14893 decl_type = TREE_TYPE (decl);
14895 if (arg == error_mark_node
14896 || decl == error_mark_node
14897 || TREE_TYPE (arg) == error_mark_node
14898 || decl_type == error_mark_node)
14899 /* Something already went wrong. There's no need to check
14900 further. */
14901 return error_mark_node;
14903 /* [dcl.fct.default]
14905 A default argument expression is implicitly converted to the
14906 parameter type. */
14907 ++cp_unevaluated_operand;
14908 /* Avoid digest_init clobbering the initializer. */
14909 tree carg = BRACE_ENCLOSED_INITIALIZER_P (arg) ? unshare_expr (arg): arg;
14910 perform_implicit_conversion_flags (decl_type, carg, complain,
14911 LOOKUP_IMPLICIT);
14912 --cp_unevaluated_operand;
14914 /* Avoid redundant -Wzero-as-null-pointer-constant warnings at
14915 the call sites. */
14916 if (TYPE_PTR_OR_PTRMEM_P (decl_type)
14917 && null_ptr_cst_p (arg)
14918 /* Don't lose side-effects as in PR90473. */
14919 && !TREE_SIDE_EFFECTS (arg))
14920 return nullptr_node;
14922 /* [dcl.fct.default]
14924 Local variables shall not be used in default argument
14925 expressions.
14927 The keyword `this' shall not be used in a default argument of a
14928 member function. */
14929 var = cp_walk_tree_without_duplicates (&arg, local_variable_p_walkfn, NULL);
14930 if (var)
14932 if (complain & tf_warning_or_error)
14934 if (DECL_NAME (var) == this_identifier)
14935 permerror (input_location, "default argument %qE uses %qD",
14936 arg, var);
14937 else
14938 error ("default argument %qE uses local variable %qD", arg, var);
14940 return error_mark_node;
14943 /* All is well. */
14944 return arg;
14947 /* Returns a deprecated type used within TYPE, or NULL_TREE if none. */
14949 static tree
14950 type_is_deprecated (tree type)
14952 enum tree_code code;
14953 if (TREE_DEPRECATED (type))
14954 return type;
14955 if (TYPE_NAME (type))
14957 if (TREE_DEPRECATED (TYPE_NAME (type)))
14958 return type;
14959 else
14961 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
14962 return NULL_TREE;
14966 /* Do warn about using typedefs to a deprecated class. */
14967 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
14968 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
14970 code = TREE_CODE (type);
14972 if (code == POINTER_TYPE || code == REFERENCE_TYPE
14973 || code == OFFSET_TYPE || code == FUNCTION_TYPE
14974 || code == METHOD_TYPE || code == ARRAY_TYPE)
14975 return type_is_deprecated (TREE_TYPE (type));
14977 if (TYPE_PTRMEMFUNC_P (type))
14978 return type_is_deprecated
14979 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
14981 return NULL_TREE;
14984 /* Returns an unavailable type used within TYPE, or NULL_TREE if none. */
14986 static tree
14987 type_is_unavailable (tree type)
14989 enum tree_code code;
14990 if (TREE_UNAVAILABLE (type))
14991 return type;
14992 if (TYPE_NAME (type))
14994 if (TREE_UNAVAILABLE (TYPE_NAME (type)))
14995 return type;
14996 else
14998 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
14999 return NULL_TREE;
15003 /* Do warn about using typedefs to a deprecated class. */
15004 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
15005 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
15007 code = TREE_CODE (type);
15009 if (code == POINTER_TYPE || code == REFERENCE_TYPE
15010 || code == OFFSET_TYPE || code == FUNCTION_TYPE
15011 || code == METHOD_TYPE || code == ARRAY_TYPE)
15012 return type_is_unavailable (TREE_TYPE (type));
15014 if (TYPE_PTRMEMFUNC_P (type))
15015 return type_is_unavailable
15016 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
15018 return NULL_TREE;
15021 /* Decode the list of parameter types for a function type.
15022 Given the list of things declared inside the parens,
15023 return a list of types.
15025 If this parameter does not end with an ellipsis, we append
15026 void_list_node.
15028 *PARMS is set to the chain of PARM_DECLs created. */
15030 tree
15031 grokparms (tree parmlist, tree *parms)
15033 tree result = NULL_TREE;
15034 tree decls = NULL_TREE;
15035 tree parm;
15036 int any_error = 0;
15038 for (parm = parmlist; parm != NULL_TREE; parm = TREE_CHAIN (parm))
15040 tree type = NULL_TREE;
15041 tree init = TREE_PURPOSE (parm);
15042 tree decl = TREE_VALUE (parm);
15044 if (parm == void_list_node || parm == explicit_void_list_node)
15045 break;
15047 if (! decl || TREE_TYPE (decl) == error_mark_node)
15049 any_error = 1;
15050 continue;
15053 type = TREE_TYPE (decl);
15054 if (VOID_TYPE_P (type))
15056 if (same_type_p (type, void_type_node)
15057 && !init
15058 && !DECL_NAME (decl) && !result
15059 && TREE_CHAIN (parm) == void_list_node)
15060 /* DR 577: A parameter list consisting of a single
15061 unnamed parameter of non-dependent type 'void'. */
15062 break;
15063 else if (cv_qualified_p (type))
15064 error_at (DECL_SOURCE_LOCATION (decl),
15065 "invalid use of cv-qualified type %qT in "
15066 "parameter declaration", type);
15067 else
15068 error_at (DECL_SOURCE_LOCATION (decl),
15069 "invalid use of type %<void%> in parameter "
15070 "declaration");
15071 /* It's not a good idea to actually create parameters of
15072 type `void'; other parts of the compiler assume that a
15073 void type terminates the parameter list. */
15074 type = error_mark_node;
15075 TREE_TYPE (decl) = error_mark_node;
15078 if (type != error_mark_node)
15080 if (deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
15082 tree unavailtype = type_is_unavailable (type);
15083 if (unavailtype)
15084 cp_handle_deprecated_or_unavailable (unavailtype);
15086 if (deprecated_state != DEPRECATED_SUPPRESS
15087 && deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
15089 tree deptype = type_is_deprecated (type);
15090 if (deptype)
15091 cp_handle_deprecated_or_unavailable (deptype);
15094 /* [dcl.fct] "A parameter with volatile-qualified type is
15095 deprecated." */
15096 if (CP_TYPE_VOLATILE_P (type))
15097 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wvolatile,
15098 "%<volatile%>-qualified parameter is "
15099 "deprecated");
15101 /* Top-level qualifiers on the parameters are
15102 ignored for function types. */
15103 type = cp_build_qualified_type (type, 0);
15104 if (TREE_CODE (type) == METHOD_TYPE)
15106 error ("parameter %qD invalidly declared method type", decl);
15107 type = build_pointer_type (type);
15108 TREE_TYPE (decl) = type;
15110 else if (cxx_dialect < cxx17 && INDIRECT_TYPE_P (type))
15112 /* Before C++17 DR 393:
15113 [dcl.fct]/6, parameter types cannot contain pointers
15114 (references) to arrays of unknown bound. */
15115 tree t = TREE_TYPE (type);
15116 int ptr = TYPE_PTR_P (type);
15118 while (1)
15120 if (TYPE_PTR_P (t))
15121 ptr = 1;
15122 else if (TREE_CODE (t) != ARRAY_TYPE)
15123 break;
15124 else if (!TYPE_DOMAIN (t))
15125 break;
15126 t = TREE_TYPE (t);
15128 if (TREE_CODE (t) == ARRAY_TYPE)
15129 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
15131 ? G_("parameter %qD includes pointer to array of "
15132 "unknown bound %qT")
15133 : G_("parameter %qD includes reference to array of "
15134 "unknown bound %qT"),
15135 decl, t);
15138 if (init && !processing_template_decl)
15139 init = check_default_argument (decl, init, tf_warning_or_error);
15142 DECL_CHAIN (decl) = decls;
15143 decls = decl;
15144 result = tree_cons (init, type, result);
15146 decls = nreverse (decls);
15147 result = nreverse (result);
15148 if (parm)
15149 result = chainon (result, void_list_node);
15150 *parms = decls;
15151 if (any_error)
15152 result = NULL_TREE;
15154 if (any_error)
15155 /* We had parm errors, recover by giving the function (...) type. */
15156 result = NULL_TREE;
15158 return result;
15162 /* D is a constructor or overloaded `operator='.
15164 Let T be the class in which D is declared. Then, this function
15165 returns:
15167 -1 if D's is an ill-formed constructor or copy assignment operator
15168 whose first parameter is of type `T'.
15169 0 if D is not a copy constructor or copy assignment
15170 operator.
15171 1 if D is a copy constructor or copy assignment operator whose
15172 first parameter is a reference to non-const qualified T.
15173 2 if D is a copy constructor or copy assignment operator whose
15174 first parameter is a reference to const qualified T.
15176 This function can be used as a predicate. Positive values indicate
15177 a copy constructor and nonzero values indicate a copy assignment
15178 operator. */
15181 copy_fn_p (const_tree d)
15183 tree args;
15184 tree arg_type;
15185 int result = 1;
15187 gcc_assert (DECL_FUNCTION_MEMBER_P (d));
15189 if (TREE_CODE (d) == TEMPLATE_DECL
15190 || (DECL_TEMPLATE_INFO (d)
15191 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
15192 /* Instantiations of template member functions are never copy
15193 functions. Note that member functions of templated classes are
15194 represented as template functions internally, and we must
15195 accept those as copy functions. */
15196 return 0;
15198 if (!DECL_CONSTRUCTOR_P (d)
15199 && DECL_NAME (d) != assign_op_identifier)
15200 return 0;
15202 args = FUNCTION_FIRST_USER_PARMTYPE (d);
15203 if (!args)
15204 return 0;
15206 arg_type = TREE_VALUE (args);
15207 if (arg_type == error_mark_node)
15208 return 0;
15210 if (TYPE_MAIN_VARIANT (arg_type) == DECL_CONTEXT (d))
15212 /* Pass by value copy assignment operator. */
15213 result = -1;
15215 else if (TYPE_REF_P (arg_type)
15216 && !TYPE_REF_IS_RVALUE (arg_type)
15217 && TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)) == DECL_CONTEXT (d))
15219 if (CP_TYPE_CONST_P (TREE_TYPE (arg_type)))
15220 result = 2;
15222 else
15223 return 0;
15225 args = TREE_CHAIN (args);
15227 if (args && args != void_list_node && !TREE_PURPOSE (args))
15228 /* There are more non-optional args. */
15229 return 0;
15231 return result;
15234 /* D is a constructor or overloaded `operator='.
15236 Let T be the class in which D is declared. Then, this function
15237 returns true when D is a move constructor or move assignment
15238 operator, false otherwise. */
15240 bool
15241 move_fn_p (const_tree d)
15243 if (cxx_dialect == cxx98)
15244 /* There are no move constructors if we are in C++98 mode. */
15245 return false;
15247 if (TREE_CODE (d) == TEMPLATE_DECL
15248 || (DECL_TEMPLATE_INFO (d)
15249 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
15250 /* Instantiations of template member functions are never move
15251 functions. Note that member functions of templated classes are
15252 represented as template functions internally, and we must
15253 accept those as move functions. */
15254 return 0;
15256 return move_signature_fn_p (d);
15259 /* D is a constructor or overloaded `operator='.
15261 Then, this function returns true when D has the same signature as a move
15262 constructor or move assignment operator (because either it is such a
15263 ctor/op= or it is a template specialization with the same signature),
15264 false otherwise. */
15266 bool
15267 move_signature_fn_p (const_tree d)
15269 tree args;
15270 tree arg_type;
15271 bool result = false;
15273 if (!DECL_CONSTRUCTOR_P (d)
15274 && DECL_NAME (d) != assign_op_identifier)
15275 return 0;
15277 args = FUNCTION_FIRST_USER_PARMTYPE (d);
15278 if (!args)
15279 return 0;
15281 arg_type = TREE_VALUE (args);
15282 if (arg_type == error_mark_node)
15283 return 0;
15285 if (TYPE_REF_P (arg_type)
15286 && TYPE_REF_IS_RVALUE (arg_type)
15287 && same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)),
15288 DECL_CONTEXT (d)))
15289 result = true;
15291 args = TREE_CHAIN (args);
15293 if (args && args != void_list_node && !TREE_PURPOSE (args))
15294 /* There are more non-optional args. */
15295 return false;
15297 return result;
15300 /* Remember any special properties of member function DECL. */
15302 void
15303 grok_special_member_properties (tree decl)
15305 tree class_type;
15307 if (TREE_CODE (decl) == USING_DECL
15308 || !DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
15309 return;
15311 class_type = DECL_CONTEXT (decl);
15312 if (IDENTIFIER_CTOR_P (DECL_NAME (decl)))
15314 int ctor = copy_fn_p (decl);
15316 if (!DECL_ARTIFICIAL (decl))
15317 TYPE_HAS_USER_CONSTRUCTOR (class_type) = 1;
15319 if (ctor > 0)
15321 /* [class.copy]
15323 A non-template constructor for class X is a copy
15324 constructor if its first parameter is of type X&, const
15325 X&, volatile X& or const volatile X&, and either there
15326 are no other parameters or else all other parameters have
15327 default arguments. */
15328 TYPE_HAS_COPY_CTOR (class_type) = 1;
15329 if (ctor > 1)
15330 TYPE_HAS_CONST_COPY_CTOR (class_type) = 1;
15333 if (sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (decl)))
15334 TYPE_HAS_DEFAULT_CONSTRUCTOR (class_type) = 1;
15336 if (is_list_ctor (decl))
15337 TYPE_HAS_LIST_CTOR (class_type) = 1;
15339 if (maybe_constexpr_fn (decl)
15340 && !ctor && !move_fn_p (decl))
15341 TYPE_HAS_CONSTEXPR_CTOR (class_type) = 1;
15343 else if (DECL_NAME (decl) == assign_op_identifier)
15345 /* [class.copy]
15347 A non-template assignment operator for class X is a copy
15348 assignment operator if its parameter is of type X, X&, const
15349 X&, volatile X& or const volatile X&. */
15351 int assop = copy_fn_p (decl);
15353 if (assop)
15355 TYPE_HAS_COPY_ASSIGN (class_type) = 1;
15356 if (assop != 1)
15357 TYPE_HAS_CONST_COPY_ASSIGN (class_type) = 1;
15360 else if (IDENTIFIER_CONV_OP_P (DECL_NAME (decl)))
15361 TYPE_HAS_CONVERSION (class_type) = true;
15363 /* Destructors are handled in check_methods. */
15366 /* Check a constructor DECL has the correct form. Complains
15367 if the class has a constructor of the form X(X). */
15369 bool
15370 grok_ctor_properties (const_tree ctype, const_tree decl)
15372 int ctor_parm = copy_fn_p (decl);
15374 if (ctor_parm < 0)
15376 /* [class.copy]
15378 A declaration of a constructor for a class X is ill-formed if
15379 its first parameter is of type (optionally cv-qualified) X
15380 and either there are no other parameters or else all other
15381 parameters have default arguments.
15383 We *don't* complain about member template instantiations that
15384 have this form, though; they can occur as we try to decide
15385 what constructor to use during overload resolution. Since
15386 overload resolution will never prefer such a constructor to
15387 the non-template copy constructor (which is either explicitly
15388 or implicitly defined), there's no need to worry about their
15389 existence. Theoretically, they should never even be
15390 instantiated, but that's hard to forestall. */
15391 error_at (DECL_SOURCE_LOCATION (decl),
15392 "invalid constructor; you probably meant %<%T (const %T&)%>",
15393 ctype, ctype);
15394 return false;
15397 return true;
15400 /* DECL is a declaration for an overloaded or conversion operator. If
15401 COMPLAIN is true, errors are issued for invalid declarations. */
15403 bool
15404 grok_op_properties (tree decl, bool complain)
15406 tree argtypes = TYPE_ARG_TYPES (TREE_TYPE (decl));
15407 bool methodp = TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE;
15408 tree name = DECL_NAME (decl);
15409 location_t loc = DECL_SOURCE_LOCATION (decl);
15411 tree class_type = DECL_CONTEXT (decl);
15412 if (class_type && !CLASS_TYPE_P (class_type))
15413 class_type = NULL_TREE;
15415 tree_code operator_code;
15416 unsigned op_flags;
15417 if (IDENTIFIER_CONV_OP_P (name))
15419 /* Conversion operators are TYPE_EXPR for the purposes of this
15420 function. */
15421 operator_code = TYPE_EXPR;
15422 op_flags = OVL_OP_FLAG_UNARY;
15424 else
15426 const ovl_op_info_t *ovl_op = IDENTIFIER_OVL_OP_INFO (name);
15428 operator_code = ovl_op->tree_code;
15429 op_flags = ovl_op->flags;
15430 gcc_checking_assert (operator_code != ERROR_MARK);
15431 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
15434 if (op_flags & OVL_OP_FLAG_ALLOC)
15436 /* operator new and operator delete are quite special. */
15437 if (class_type)
15438 switch (op_flags)
15440 case OVL_OP_FLAG_ALLOC:
15441 TYPE_HAS_NEW_OPERATOR (class_type) = 1;
15442 break;
15444 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE:
15445 TYPE_GETS_DELETE (class_type) |= 1;
15446 break;
15448 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_VEC:
15449 TYPE_HAS_ARRAY_NEW_OPERATOR (class_type) = 1;
15450 break;
15452 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE | OVL_OP_FLAG_VEC:
15453 TYPE_GETS_DELETE (class_type) |= 2;
15454 break;
15456 default:
15457 gcc_unreachable ();
15460 /* [basic.std.dynamic.allocation]/1:
15462 A program is ill-formed if an allocation function is declared
15463 in a namespace scope other than global scope or declared
15464 static in global scope.
15466 The same also holds true for deallocation functions. */
15467 if (DECL_NAMESPACE_SCOPE_P (decl))
15469 if (CP_DECL_CONTEXT (decl) != global_namespace)
15471 error_at (loc, "%qD may not be declared within a namespace",
15472 decl);
15473 return false;
15476 if (!TREE_PUBLIC (decl))
15478 error_at (loc, "%qD may not be declared as static", decl);
15479 return false;
15483 if (op_flags & OVL_OP_FLAG_DELETE)
15485 DECL_SET_IS_OPERATOR_DELETE (decl, true);
15486 coerce_delete_type (decl, loc);
15488 else
15490 DECL_SET_IS_OPERATOR_NEW (decl, true);
15491 TREE_TYPE (decl) = coerce_new_type (TREE_TYPE (decl), loc);
15494 return true;
15497 /* An operator function must either be a non-static member function
15498 or have at least one parameter of a class, a reference to a class,
15499 an enumeration, or a reference to an enumeration. 13.4.0.6 */
15500 if (! methodp || DECL_STATIC_FUNCTION_P (decl))
15502 if (operator_code == TYPE_EXPR
15503 || operator_code == COMPONENT_REF
15504 || operator_code == NOP_EXPR)
15506 error_at (loc, "%qD must be a non-static member function", decl);
15507 return false;
15510 if (operator_code == CALL_EXPR || operator_code == ARRAY_REF)
15512 if (! DECL_STATIC_FUNCTION_P (decl))
15514 error_at (loc, "%qD must be a member function", decl);
15515 return false;
15517 if (cxx_dialect < cxx23
15518 /* For lambdas we diagnose static lambda specifier elsewhere. */
15519 && (operator_code == ARRAY_REF || ! LAMBDA_FUNCTION_P (decl))
15520 /* For instantiations, we have diagnosed this already. */
15521 && ! DECL_USE_TEMPLATE (decl))
15522 pedwarn (loc, OPT_Wc__23_extensions, "%qD may be a static member "
15523 "function only with %<-std=c++23%> or %<-std=gnu++23%>",
15524 decl);
15525 if (operator_code == ARRAY_REF)
15526 /* static operator[] should have exactly one argument
15527 for C++20 and earlier, so that it isn't multidimensional. */
15528 op_flags = OVL_OP_FLAG_UNARY;
15530 else if (DECL_STATIC_FUNCTION_P (decl))
15532 error_at (loc, "%qD must be either a non-static member "
15533 "function or a non-member function", decl);
15534 return false;
15536 else
15537 for (tree arg = argtypes; ; arg = TREE_CHAIN (arg))
15539 if (!arg || arg == void_list_node)
15541 if (complain)
15542 error_at (loc, "%qD must have an argument of class or "
15543 "enumerated type", decl);
15544 return false;
15547 tree type = non_reference (TREE_VALUE (arg));
15548 if (type == error_mark_node)
15549 return false;
15551 /* MAYBE_CLASS_TYPE_P, rather than CLASS_TYPE_P, is used
15552 because these checks are performed even on template
15553 functions. */
15554 if (MAYBE_CLASS_TYPE_P (type)
15555 || TREE_CODE (type) == ENUMERAL_TYPE)
15556 break;
15560 if (operator_code == CALL_EXPR)
15561 /* There are no further restrictions on the arguments to an overloaded
15562 "operator ()". */
15563 return true;
15565 /* C++23 allows an arbitrary number of parameters and default arguments for
15566 operator[], and none of the other checks below apply. */
15567 if (operator_code == ARRAY_REF && cxx_dialect >= cxx23)
15568 return true;
15570 if (operator_code == COND_EXPR)
15572 /* 13.4.0.3 */
15573 error_at (loc, "ISO C++ prohibits overloading %<operator ?:%>");
15574 return false;
15577 /* Count the number of arguments and check for ellipsis. */
15578 int arity = 0;
15579 for (tree arg = argtypes; arg != void_list_node; arg = TREE_CHAIN (arg))
15581 if (!arg)
15583 error_at (loc, "%qD must not have variable number of arguments",
15584 decl);
15585 return false;
15587 ++arity;
15590 /* Verify correct number of arguments. */
15591 switch (op_flags)
15593 case OVL_OP_FLAG_AMBIARY:
15594 if (arity == 1)
15596 /* We have a unary instance of an ambi-ary op. Remap to the
15597 unary one. */
15598 unsigned alt = ovl_op_alternate[ovl_op_mapping [operator_code]];
15599 const ovl_op_info_t *ovl_op = &ovl_op_info[false][alt];
15600 gcc_checking_assert (ovl_op->flags == OVL_OP_FLAG_UNARY);
15601 operator_code = ovl_op->tree_code;
15602 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
15604 else if (arity != 2)
15606 /* This was an ambiguous operator but is invalid. */
15607 error_at (loc,
15608 methodp
15609 ? G_("%qD must have either zero or one argument")
15610 : G_("%qD must have either one or two arguments"), decl);
15611 return false;
15613 else if ((operator_code == POSTINCREMENT_EXPR
15614 || operator_code == POSTDECREMENT_EXPR)
15615 && ! processing_template_decl
15616 /* x++ and x--'s second argument must be an int. */
15617 && ! same_type_p (TREE_VALUE (TREE_CHAIN (argtypes)),
15618 integer_type_node))
15620 error_at (loc,
15621 methodp
15622 ? G_("postfix %qD must have %<int%> as its argument")
15623 : G_("postfix %qD must have %<int%> as its second argument"),
15624 decl);
15625 return false;
15627 break;
15629 case OVL_OP_FLAG_UNARY:
15630 if (arity != 1)
15632 error_at (loc,
15633 methodp
15634 ? G_("%qD must have no arguments")
15635 : G_("%qD must have exactly one argument"), decl);
15636 return false;
15638 break;
15640 case OVL_OP_FLAG_BINARY:
15641 if (arity != 2)
15643 error_at (loc,
15644 methodp
15645 ? G_("%qD must have exactly one argument")
15646 : G_("%qD must have exactly two arguments"), decl);
15647 return false;
15649 break;
15651 default:
15652 gcc_unreachable ();
15655 /* There can be no default arguments. */
15656 for (tree arg = argtypes; arg && arg != void_list_node;
15657 arg = TREE_CHAIN (arg))
15658 if (TREE_PURPOSE (arg))
15660 TREE_PURPOSE (arg) = NULL_TREE;
15661 error_at (loc, "%qD cannot have default arguments", decl);
15662 return false;
15665 /* At this point the declaration is well-formed. It may not be
15666 sensible though. */
15668 /* Check member function warnings only on the in-class declaration.
15669 There's no point warning on an out-of-class definition. */
15670 if (class_type && class_type != current_class_type)
15671 return true;
15673 /* Warn about conversion operators that will never be used. */
15674 if (IDENTIFIER_CONV_OP_P (name)
15675 && ! DECL_TEMPLATE_INFO (decl)
15676 && warn_class_conversion)
15678 tree t = TREE_TYPE (name);
15679 int ref = TYPE_REF_P (t);
15681 if (ref)
15682 t = TYPE_MAIN_VARIANT (TREE_TYPE (t));
15684 if (VOID_TYPE_P (t))
15685 warning_at (loc, OPT_Wclass_conversion, "converting %qT to %<void%> "
15686 "will never use a type conversion operator", class_type);
15687 else if (class_type)
15689 if (same_type_ignoring_top_level_qualifiers_p (t, class_type))
15690 warning_at (loc, OPT_Wclass_conversion,
15692 ? G_("converting %qT to a reference to the same type "
15693 "will never use a type conversion operator")
15694 : G_("converting %qT to the same type "
15695 "will never use a type conversion operator"),
15696 class_type);
15697 /* Don't force t to be complete here. */
15698 else if (MAYBE_CLASS_TYPE_P (t)
15699 && COMPLETE_TYPE_P (t)
15700 && DERIVED_FROM_P (t, class_type))
15701 warning_at (loc, OPT_Wclass_conversion,
15703 ? G_("converting %qT to a reference to a base class "
15704 "%qT will never use a type conversion operator")
15705 : G_("converting %qT to a base class %qT "
15706 "will never use a type conversion operator"),
15707 class_type, t);
15711 if (!warn_ecpp)
15712 return true;
15714 /* Effective C++ rules below. */
15716 /* More Effective C++ rule 7. */
15717 if (operator_code == TRUTH_ANDIF_EXPR
15718 || operator_code == TRUTH_ORIF_EXPR
15719 || operator_code == COMPOUND_EXPR)
15720 warning_at (loc, OPT_Weffc__,
15721 "user-defined %qD always evaluates both arguments", decl);
15723 /* More Effective C++ rule 6. */
15724 if (operator_code == POSTINCREMENT_EXPR
15725 || operator_code == POSTDECREMENT_EXPR
15726 || operator_code == PREINCREMENT_EXPR
15727 || operator_code == PREDECREMENT_EXPR)
15729 tree arg = TREE_VALUE (argtypes);
15730 tree ret = TREE_TYPE (TREE_TYPE (decl));
15731 if (methodp || TYPE_REF_P (arg))
15732 arg = TREE_TYPE (arg);
15733 arg = TYPE_MAIN_VARIANT (arg);
15735 if (operator_code == PREINCREMENT_EXPR
15736 || operator_code == PREDECREMENT_EXPR)
15738 if (!TYPE_REF_P (ret)
15739 || !same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (ret)), arg))
15740 warning_at (loc, OPT_Weffc__, "prefix %qD should return %qT", decl,
15741 build_reference_type (arg));
15743 else
15745 if (!same_type_p (TYPE_MAIN_VARIANT (ret), arg))
15746 warning_at (loc, OPT_Weffc__,
15747 "postfix %qD should return %qT", decl, arg);
15751 /* Effective C++ rule 23. */
15752 if (!DECL_ASSIGNMENT_OPERATOR_P (decl)
15753 && (operator_code == PLUS_EXPR
15754 || operator_code == MINUS_EXPR
15755 || operator_code == TRUNC_DIV_EXPR
15756 || operator_code == MULT_EXPR
15757 || operator_code == TRUNC_MOD_EXPR)
15758 && TYPE_REF_P (TREE_TYPE (TREE_TYPE (decl))))
15759 warning_at (loc, OPT_Weffc__, "%qD should return by value", decl);
15761 return true;
15764 /* Return a string giving the keyword associate with CODE. */
15766 static const char *
15767 tag_name (enum tag_types code)
15769 switch (code)
15771 case record_type:
15772 return "struct";
15773 case class_type:
15774 return "class";
15775 case union_type:
15776 return "union";
15777 case enum_type:
15778 return "enum";
15779 case typename_type:
15780 return "typename";
15781 default:
15782 gcc_unreachable ();
15786 /* Name lookup in an elaborated-type-specifier (after the keyword
15787 indicated by TAG_CODE) has found the TYPE_DECL DECL. If the
15788 elaborated-type-specifier is invalid, issue a diagnostic and return
15789 error_mark_node; otherwise, return the *_TYPE to which it referred.
15790 If ALLOW_TEMPLATE_P is true, TYPE may be a class template. */
15792 tree
15793 check_elaborated_type_specifier (enum tag_types tag_code,
15794 tree decl,
15795 bool allow_template_p)
15797 tree type;
15799 /* In the case of:
15801 struct S { struct S *p; };
15803 name lookup will find the TYPE_DECL for the implicit "S::S"
15804 typedef. Adjust for that here. */
15805 if (DECL_SELF_REFERENCE_P (decl))
15806 decl = TYPE_NAME (TREE_TYPE (decl));
15808 type = TREE_TYPE (decl);
15810 /* Check TEMPLATE_TYPE_PARM first because DECL_IMPLICIT_TYPEDEF_P
15811 is false for this case as well. */
15812 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
15814 error ("using template type parameter %qT after %qs",
15815 type, tag_name (tag_code));
15816 return error_mark_node;
15818 /* Accept template template parameters. */
15819 else if (allow_template_p
15820 && (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
15821 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM))
15823 /* [dcl.type.elab]
15825 If the identifier resolves to a typedef-name or the
15826 simple-template-id resolves to an alias template
15827 specialization, the elaborated-type-specifier is ill-formed.
15829 In other words, the only legitimate declaration to use in the
15830 elaborated type specifier is the implicit typedef created when
15831 the type is declared. */
15832 else if (!DECL_IMPLICIT_TYPEDEF_P (decl)
15833 && !DECL_SELF_REFERENCE_P (decl)
15834 && tag_code != typename_type)
15836 if (alias_template_specialization_p (type, nt_opaque))
15837 error ("using alias template specialization %qT after %qs",
15838 type, tag_name (tag_code));
15839 else
15840 error ("using typedef-name %qD after %qs", decl, tag_name (tag_code));
15841 inform (DECL_SOURCE_LOCATION (decl),
15842 "%qD has a previous declaration here", decl);
15843 return error_mark_node;
15845 else if (TREE_CODE (type) != RECORD_TYPE
15846 && TREE_CODE (type) != UNION_TYPE
15847 && tag_code != enum_type
15848 && tag_code != typename_type)
15850 error ("%qT referred to as %qs", type, tag_name (tag_code));
15851 inform (location_of (type), "%qT has a previous declaration here", type);
15852 return error_mark_node;
15854 else if (TREE_CODE (type) != ENUMERAL_TYPE
15855 && tag_code == enum_type)
15857 error ("%qT referred to as enum", type);
15858 inform (location_of (type), "%qT has a previous declaration here", type);
15859 return error_mark_node;
15861 else if (!allow_template_p
15862 && TREE_CODE (type) == RECORD_TYPE
15863 && CLASSTYPE_IS_TEMPLATE (type))
15865 /* If a class template appears as elaborated type specifier
15866 without a template header such as:
15868 template <class T> class C {};
15869 void f(class C); // No template header here
15871 then the required template argument is missing. */
15872 error ("template argument required for %<%s %T%>",
15873 tag_name (tag_code),
15874 DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)));
15875 return error_mark_node;
15878 return type;
15881 /* Lookup NAME of an elaborated type specifier according to SCOPE and
15882 issue diagnostics if necessary. Return *_TYPE node upon success,
15883 NULL_TREE when the NAME is not found, and ERROR_MARK_NODE for type
15884 error. */
15886 static tree
15887 lookup_and_check_tag (enum tag_types tag_code, tree name,
15888 TAG_how how, bool template_header_p)
15890 tree decl;
15891 if (how == TAG_how::GLOBAL)
15893 /* First try ordinary name lookup, ignoring hidden class name
15894 injected via friend declaration. */
15895 decl = lookup_name (name, LOOK_want::TYPE);
15896 decl = strip_using_decl (decl);
15897 /* If that fails, the name will be placed in the smallest
15898 non-class, non-function-prototype scope according to 3.3.1/5.
15899 We may already have a hidden name declared as friend in this
15900 scope. So lookup again but not ignoring hidden names.
15901 If we find one, that name will be made visible rather than
15902 creating a new tag. */
15903 if (!decl)
15904 decl = lookup_elaborated_type (name, TAG_how::INNERMOST_NON_CLASS);
15906 else
15907 decl = lookup_elaborated_type (name, how);
15909 if (!decl)
15910 /* We found nothing. */
15911 return NULL_TREE;
15913 if (TREE_CODE (decl) == TREE_LIST)
15915 error ("reference to %qD is ambiguous", name);
15916 print_candidates (decl);
15917 return error_mark_node;
15920 if (DECL_CLASS_TEMPLATE_P (decl)
15921 && !template_header_p
15922 && how == TAG_how::CURRENT_ONLY)
15924 error ("class template %qD redeclared as non-template", name);
15925 inform (location_of (decl), "previous declaration here");
15926 CLASSTYPE_ERRONEOUS (TREE_TYPE (decl)) = true;
15927 return error_mark_node;
15930 if (DECL_CLASS_TEMPLATE_P (decl)
15931 /* If scope is TAG_how::CURRENT_ONLY we're defining a class,
15932 so ignore a template template parameter. */
15933 || (how != TAG_how::CURRENT_ONLY && DECL_TEMPLATE_TEMPLATE_PARM_P (decl)))
15934 decl = DECL_TEMPLATE_RESULT (decl);
15936 if (TREE_CODE (decl) != TYPE_DECL)
15937 /* Found not-a-type. */
15938 return NULL_TREE;
15940 /* Look for invalid nested type:
15941 class C {
15942 class C {};
15943 }; */
15944 if (how == TAG_how::CURRENT_ONLY && DECL_SELF_REFERENCE_P (decl))
15946 error ("%qD has the same name as the class in which it is "
15947 "declared", decl);
15948 return error_mark_node;
15951 /* Two cases we need to consider when deciding if a class
15952 template is allowed as an elaborated type specifier:
15953 1. It is a self reference to its own class.
15954 2. It comes with a template header.
15956 For example:
15958 template <class T> class C {
15959 class C *c1; // DECL_SELF_REFERENCE_P is true
15960 class D;
15962 template <class U> class C; // template_header_p is true
15963 template <class T> class C<T>::D {
15964 class C *c2; // DECL_SELF_REFERENCE_P is true
15965 }; */
15967 tree t = check_elaborated_type_specifier (tag_code, decl,
15968 template_header_p
15969 | DECL_SELF_REFERENCE_P (decl));
15970 if (template_header_p && t && CLASS_TYPE_P (t)
15971 && (!CLASSTYPE_TEMPLATE_INFO (t)
15972 || (!PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))))
15974 error ("%qT is not a template", t);
15975 inform (location_of (t), "previous declaration here");
15976 if (TYPE_CLASS_SCOPE_P (t)
15977 && CLASSTYPE_TEMPLATE_INFO (TYPE_CONTEXT (t)))
15978 inform (input_location,
15979 "perhaps you want to explicitly add %<%T::%>",
15980 TYPE_CONTEXT (t));
15981 return error_mark_node;
15984 return t;
15987 /* Get the struct, enum or union (TAG_CODE says which) with tag NAME.
15988 Define the tag as a forward-reference if it is not defined.
15990 If a declaration is given, process it here, and report an error if
15991 multiple declarations are not identical.
15993 SCOPE is TS_CURRENT when this is also a definition. Only look in
15994 the current frame for the name (since C++ allows new names in any
15995 scope.) It is TS_WITHIN_ENCLOSING_NON_CLASS if this is a friend
15996 declaration. Only look beginning from the current scope outward up
15997 till the nearest non-class scope. Otherwise it is TS_GLOBAL.
15999 TEMPLATE_HEADER_P is true when this declaration is preceded by
16000 a set of template parameters. */
16002 tree
16003 xref_tag (enum tag_types tag_code, tree name,
16004 TAG_how how, bool template_header_p)
16006 enum tree_code code;
16007 tree context = NULL_TREE;
16009 auto_cond_timevar tv (TV_NAME_LOOKUP);
16011 gcc_assert (identifier_p (name));
16013 switch (tag_code)
16015 case record_type:
16016 case class_type:
16017 code = RECORD_TYPE;
16018 break;
16019 case union_type:
16020 code = UNION_TYPE;
16021 break;
16022 case enum_type:
16023 code = ENUMERAL_TYPE;
16024 break;
16025 default:
16026 gcc_unreachable ();
16029 /* In case of anonymous name, xref_tag is only called to
16030 make type node and push name. Name lookup is not required. */
16031 tree t = NULL_TREE;
16032 if (!IDENTIFIER_ANON_P (name))
16033 t = lookup_and_check_tag (tag_code, name, how, template_header_p);
16035 if (t == error_mark_node)
16036 return error_mark_node;
16038 if (how != TAG_how::CURRENT_ONLY && t && current_class_type
16039 && template_class_depth (current_class_type)
16040 && template_header_p)
16042 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
16043 return t;
16045 /* Since HOW is not TAG_how::CURRENT_ONLY, we are not looking at
16046 a definition of this tag. Since, in addition, we are
16047 currently processing a (member) template declaration of a
16048 template class, we must be very careful; consider:
16050 template <class X> struct S1
16052 template <class U> struct S2
16054 template <class V> friend struct S1;
16057 Here, the S2::S1 declaration should not be confused with the
16058 outer declaration. In particular, the inner version should
16059 have a template parameter of level 2, not level 1.
16061 On the other hand, when presented with:
16063 template <class T> struct S1
16065 template <class U> struct S2 {};
16066 template <class U> friend struct S2;
16069 the friend must find S1::S2 eventually. We accomplish this
16070 by making sure that the new type we create to represent this
16071 declaration has the right TYPE_CONTEXT. */
16072 context = TYPE_CONTEXT (t);
16073 t = NULL_TREE;
16076 if (! t)
16078 /* If no such tag is yet defined, create a forward-reference node
16079 and record it as the "definition".
16080 When a real declaration of this type is found,
16081 the forward-reference will be altered into a real type. */
16082 if (code == ENUMERAL_TYPE)
16084 error ("use of enum %q#D without previous declaration", name);
16085 return error_mark_node;
16088 t = make_class_type (code);
16089 TYPE_CONTEXT (t) = context;
16090 if (IDENTIFIER_LAMBDA_P (name))
16091 /* Mark it as a lambda type right now. Our caller will
16092 correct the value. */
16093 CLASSTYPE_LAMBDA_EXPR (t) = error_mark_node;
16094 t = pushtag (name, t, how);
16096 else
16098 if (template_header_p && MAYBE_CLASS_TYPE_P (t))
16100 /* Check that we aren't trying to overload a class with different
16101 constraints. */
16102 if (!redeclare_class_template (t, current_template_parms,
16103 current_template_constraints ()))
16104 return error_mark_node;
16106 else if (!processing_template_decl
16107 && CLASS_TYPE_P (t)
16108 && CLASSTYPE_IS_TEMPLATE (t))
16110 error ("redeclaration of %qT as a non-template", t);
16111 inform (location_of (t), "previous declaration %qD", t);
16112 return error_mark_node;
16115 if (modules_p ()
16116 && how == TAG_how::CURRENT_ONLY)
16118 tree decl = TYPE_NAME (t);
16119 if (!module_may_redeclare (decl))
16121 error ("cannot declare %qD in a different module", decl);
16122 inform (DECL_SOURCE_LOCATION (decl), "declared here");
16123 return error_mark_node;
16126 tree maybe_tmpl = decl;
16127 if (CLASS_TYPE_P (t) && CLASSTYPE_IS_TEMPLATE (t))
16128 maybe_tmpl = CLASSTYPE_TI_TEMPLATE (t);
16130 if (DECL_LANG_SPECIFIC (decl)
16131 && DECL_MODULE_IMPORT_P (decl)
16132 && TREE_CODE (CP_DECL_CONTEXT (decl)) == NAMESPACE_DECL)
16134 /* Push it into this TU's symbol slot. */
16135 gcc_checking_assert (current_namespace == CP_DECL_CONTEXT (decl));
16136 if (maybe_tmpl != decl)
16137 /* We're in the template parm binding level.
16138 Pushtag has logic to slide under that, but we're
16139 not pushing a *new* type. */
16140 push_nested_namespace (CP_DECL_CONTEXT (decl));
16142 pushdecl (maybe_tmpl);
16143 if (maybe_tmpl != decl)
16144 pop_nested_namespace (CP_DECL_CONTEXT (decl));
16147 set_instantiating_module (maybe_tmpl);
16151 return t;
16154 /* Create the binfo hierarchy for REF with (possibly NULL) base list
16155 BASE_LIST. For each element on BASE_LIST the TREE_PURPOSE is an
16156 access_* node, and the TREE_VALUE is the type of the base-class.
16157 Non-NULL TREE_TYPE indicates virtual inheritance. */
16159 void
16160 xref_basetypes (tree ref, tree base_list)
16162 tree *basep;
16163 tree binfo, base_binfo;
16164 unsigned max_vbases = 0; /* Maximum direct & indirect virtual bases. */
16165 unsigned max_bases = 0; /* Maximum direct bases. */
16166 unsigned max_dvbases = 0; /* Maximum direct virtual bases. */
16167 int i;
16168 tree default_access;
16169 tree igo_prev; /* Track Inheritance Graph Order. */
16171 if (ref == error_mark_node)
16172 return;
16174 /* The base of a derived class is private by default, all others are
16175 public. */
16176 default_access = (TREE_CODE (ref) == RECORD_TYPE
16177 && CLASSTYPE_DECLARED_CLASS (ref)
16178 ? access_private_node : access_public_node);
16180 /* First, make sure that any templates in base-classes are
16181 instantiated. This ensures that if we call ourselves recursively
16182 we do not get confused about which classes are marked and which
16183 are not. */
16184 basep = &base_list;
16185 while (*basep)
16187 tree basetype = TREE_VALUE (*basep);
16189 /* The dependent_type_p call below should really be dependent_scope_p
16190 so that we give a hard error about using an incomplete type as a
16191 base, but we allow it with a pedwarn for backward
16192 compatibility. */
16193 if (processing_template_decl
16194 && CLASS_TYPE_P (basetype) && TYPE_BEING_DEFINED (basetype))
16195 cxx_incomplete_type_diagnostic (NULL_TREE, basetype, DK_PEDWARN);
16196 if (!dependent_type_p (basetype)
16197 && !complete_type_or_else (basetype, NULL))
16198 /* An incomplete type. Remove it from the list. */
16199 *basep = TREE_CHAIN (*basep);
16200 else
16202 max_bases++;
16203 if (TREE_TYPE (*basep))
16204 max_dvbases++;
16205 if (CLASS_TYPE_P (basetype))
16206 max_vbases += vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
16207 basep = &TREE_CHAIN (*basep);
16210 max_vbases += max_dvbases;
16212 TYPE_MARKED_P (ref) = 1;
16214 /* The binfo slot should be empty, unless this is an (ill-formed)
16215 redefinition. */
16216 gcc_assert (!TYPE_BINFO (ref) || TYPE_SIZE (ref));
16218 gcc_assert (TYPE_MAIN_VARIANT (ref) == ref);
16220 binfo = make_tree_binfo (max_bases);
16222 TYPE_BINFO (ref) = binfo;
16223 BINFO_OFFSET (binfo) = size_zero_node;
16224 BINFO_TYPE (binfo) = ref;
16226 /* Apply base-class info set up to the variants of this type. */
16227 fixup_type_variants (ref);
16229 if (max_bases)
16231 vec_alloc (BINFO_BASE_ACCESSES (binfo), max_bases);
16232 /* A C++98 POD cannot have base classes. */
16233 CLASSTYPE_NON_LAYOUT_POD_P (ref) = true;
16235 if (TREE_CODE (ref) == UNION_TYPE)
16237 error ("derived union %qT invalid", ref);
16238 return;
16242 if (max_bases > 1)
16243 warning (OPT_Wmultiple_inheritance,
16244 "%qT defined with multiple direct bases", ref);
16246 if (max_vbases)
16248 /* An aggregate can't have virtual base classes. */
16249 CLASSTYPE_NON_AGGREGATE (ref) = true;
16251 vec_alloc (CLASSTYPE_VBASECLASSES (ref), max_vbases);
16253 if (max_dvbases)
16254 warning (OPT_Wvirtual_inheritance,
16255 "%qT defined with direct virtual base", ref);
16258 for (igo_prev = binfo; base_list; base_list = TREE_CHAIN (base_list))
16260 tree access = TREE_PURPOSE (base_list);
16261 int via_virtual = TREE_TYPE (base_list) != NULL_TREE;
16262 tree basetype = TREE_VALUE (base_list);
16264 if (access == access_default_node)
16265 access = default_access;
16267 /* Before C++17, an aggregate cannot have base classes. In C++17, an
16268 aggregate can't have virtual, private, or protected base classes. */
16269 if (cxx_dialect < cxx17
16270 || access != access_public_node
16271 || via_virtual)
16272 CLASSTYPE_NON_AGGREGATE (ref) = true;
16274 if (PACK_EXPANSION_P (basetype))
16275 basetype = PACK_EXPANSION_PATTERN (basetype);
16276 if (TREE_CODE (basetype) == TYPE_DECL)
16277 basetype = TREE_TYPE (basetype);
16278 if (!MAYBE_CLASS_TYPE_P (basetype) || TREE_CODE (basetype) == UNION_TYPE)
16280 error ("base type %qT fails to be a struct or class type",
16281 basetype);
16282 goto dropped_base;
16285 base_binfo = NULL_TREE;
16286 if (CLASS_TYPE_P (basetype) && !dependent_scope_p (basetype))
16288 base_binfo = TYPE_BINFO (basetype);
16289 /* The original basetype could have been a typedef'd type. */
16290 basetype = BINFO_TYPE (base_binfo);
16292 /* Inherit flags from the base. */
16293 TYPE_HAS_NEW_OPERATOR (ref)
16294 |= TYPE_HAS_NEW_OPERATOR (basetype);
16295 TYPE_HAS_ARRAY_NEW_OPERATOR (ref)
16296 |= TYPE_HAS_ARRAY_NEW_OPERATOR (basetype);
16297 TYPE_GETS_DELETE (ref) |= TYPE_GETS_DELETE (basetype);
16298 TYPE_HAS_CONVERSION (ref) |= TYPE_HAS_CONVERSION (basetype);
16299 CLASSTYPE_DIAMOND_SHAPED_P (ref)
16300 |= CLASSTYPE_DIAMOND_SHAPED_P (basetype);
16301 CLASSTYPE_REPEATED_BASE_P (ref)
16302 |= CLASSTYPE_REPEATED_BASE_P (basetype);
16305 /* We must do this test after we've seen through a typedef
16306 type. */
16307 if (TYPE_MARKED_P (basetype))
16309 if (basetype == ref)
16310 error ("recursive type %qT undefined", basetype);
16311 else
16312 error ("duplicate base type %qT invalid", basetype);
16313 goto dropped_base;
16316 if (PACK_EXPANSION_P (TREE_VALUE (base_list)))
16317 /* Regenerate the pack expansion for the bases. */
16318 basetype = make_pack_expansion (basetype);
16320 TYPE_MARKED_P (basetype) = 1;
16322 base_binfo = copy_binfo (base_binfo, basetype, ref,
16323 &igo_prev, via_virtual);
16324 if (!BINFO_INHERITANCE_CHAIN (base_binfo))
16325 BINFO_INHERITANCE_CHAIN (base_binfo) = binfo;
16327 BINFO_BASE_APPEND (binfo, base_binfo);
16328 BINFO_BASE_ACCESS_APPEND (binfo, access);
16329 continue;
16331 dropped_base:
16332 /* Update max_vbases to reflect the reality that we are dropping
16333 this base: if it reaches zero we want to undo the vec_alloc
16334 above to avoid inconsistencies during error-recovery: eg, in
16335 build_special_member_call, CLASSTYPE_VBASECLASSES non null
16336 and vtt null (c++/27952). */
16337 if (via_virtual)
16338 max_vbases--;
16339 if (CLASS_TYPE_P (basetype))
16340 max_vbases
16341 -= vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
16344 if (CLASSTYPE_VBASECLASSES (ref)
16345 && max_vbases == 0)
16346 vec_free (CLASSTYPE_VBASECLASSES (ref));
16348 if (vec_safe_length (CLASSTYPE_VBASECLASSES (ref)) < max_vbases)
16349 /* If we didn't get max_vbases vbases, we must have shared at
16350 least one of them, and are therefore diamond shaped. */
16351 CLASSTYPE_DIAMOND_SHAPED_P (ref) = 1;
16353 /* Unmark all the types. */
16354 for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
16355 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
16356 TYPE_MARKED_P (ref) = 0;
16358 /* Now see if we have a repeated base type. */
16359 if (!CLASSTYPE_REPEATED_BASE_P (ref))
16361 for (base_binfo = binfo; base_binfo;
16362 base_binfo = TREE_CHAIN (base_binfo))
16364 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
16366 CLASSTYPE_REPEATED_BASE_P (ref) = 1;
16367 break;
16369 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 1;
16371 for (base_binfo = binfo; base_binfo;
16372 base_binfo = TREE_CHAIN (base_binfo))
16373 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
16374 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
16375 else
16376 break;
16381 /* Copies the enum-related properties from type SRC to type DST.
16382 Used with the underlying type of an enum and the enum itself. */
16383 static void
16384 copy_type_enum (tree dst, tree src)
16386 tree t;
16387 for (t = dst; t; t = TYPE_NEXT_VARIANT (t))
16389 TYPE_MIN_VALUE (t) = TYPE_MIN_VALUE (src);
16390 TYPE_MAX_VALUE (t) = TYPE_MAX_VALUE (src);
16391 TYPE_SIZE (t) = TYPE_SIZE (src);
16392 TYPE_SIZE_UNIT (t) = TYPE_SIZE_UNIT (src);
16393 SET_TYPE_MODE (dst, TYPE_MODE (src));
16394 TYPE_PRECISION (t) = TYPE_PRECISION (src);
16395 unsigned valign = TYPE_ALIGN (src);
16396 if (TYPE_USER_ALIGN (t))
16397 valign = MAX (valign, TYPE_ALIGN (t));
16398 else
16399 TYPE_USER_ALIGN (t) = TYPE_USER_ALIGN (src);
16400 SET_TYPE_ALIGN (t, valign);
16401 TYPE_UNSIGNED (t) = TYPE_UNSIGNED (src);
16405 /* Begin compiling the definition of an enumeration type.
16406 NAME is its name,
16408 if ENUMTYPE is not NULL_TREE then the type has alredy been found.
16410 UNDERLYING_TYPE is the type that will be used as the storage for
16411 the enumeration type. This should be NULL_TREE if no storage type
16412 was specified.
16414 ATTRIBUTES are any attributes specified after the enum-key.
16416 SCOPED_ENUM_P is true if this is a scoped enumeration type.
16418 if IS_NEW is not NULL, gets TRUE iff a new type is created.
16420 Returns the type object, as yet incomplete.
16421 Also records info about it so that build_enumerator
16422 may be used to declare the individual values as they are read. */
16424 tree
16425 start_enum (tree name, tree enumtype, tree underlying_type,
16426 tree attributes, bool scoped_enum_p, bool *is_new)
16428 tree prevtype = NULL_TREE;
16429 gcc_assert (identifier_p (name));
16431 if (is_new)
16432 *is_new = false;
16433 /* [C++0x dcl.enum]p5:
16435 If not explicitly specified, the underlying type of a scoped
16436 enumeration type is int. */
16437 if (!underlying_type && scoped_enum_p)
16438 underlying_type = integer_type_node;
16440 if (underlying_type)
16441 underlying_type = cv_unqualified (underlying_type);
16443 /* If this is the real definition for a previous forward reference,
16444 fill in the contents in the same object that used to be the
16445 forward reference. */
16446 if (!enumtype)
16447 enumtype = lookup_and_check_tag (enum_type, name,
16448 /*tag_scope=*/TAG_how::CURRENT_ONLY,
16449 /*template_header_p=*/false);
16451 /* In case of a template_decl, the only check that should be deferred
16452 to instantiation time is the comparison of underlying types. */
16453 if (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE)
16455 if (scoped_enum_p != SCOPED_ENUM_P (enumtype))
16457 error_at (input_location, "scoped/unscoped mismatch "
16458 "in enum %q#T", enumtype);
16459 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16460 "previous definition here");
16461 enumtype = error_mark_node;
16463 else if (ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) != !! underlying_type)
16465 error_at (input_location, "underlying type mismatch "
16466 "in enum %q#T", enumtype);
16467 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16468 "previous definition here");
16469 enumtype = error_mark_node;
16471 else if (underlying_type && ENUM_UNDERLYING_TYPE (enumtype)
16472 && !same_type_p (underlying_type,
16473 ENUM_UNDERLYING_TYPE (enumtype)))
16475 error_at (input_location, "different underlying type "
16476 "in enum %q#T", enumtype);
16477 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16478 "previous definition here");
16479 underlying_type = NULL_TREE;
16482 if (modules_p ())
16484 if (!module_may_redeclare (TYPE_NAME (enumtype)))
16486 error ("cannot define %qD in different module",
16487 TYPE_NAME (enumtype));
16488 inform (DECL_SOURCE_LOCATION (TYPE_NAME (enumtype)),
16489 "declared here");
16490 enumtype = error_mark_node;
16492 set_instantiating_module (TYPE_NAME (enumtype));
16496 if (!enumtype || TREE_CODE (enumtype) != ENUMERAL_TYPE
16497 || processing_template_decl)
16499 /* In case of error, make a dummy enum to allow parsing to
16500 continue. */
16501 if (enumtype == error_mark_node)
16503 name = make_anon_name ();
16504 enumtype = NULL_TREE;
16507 /* enumtype may be an ENUMERAL_TYPE if this is a redefinition
16508 of an opaque enum, or an opaque enum of an already defined
16509 enumeration (C++11).
16510 In any other case, it'll be NULL_TREE. */
16511 if (!enumtype)
16513 if (is_new)
16514 *is_new = true;
16516 prevtype = enumtype;
16518 /* Do not push the decl more than once. */
16519 if (!enumtype
16520 || TREE_CODE (enumtype) != ENUMERAL_TYPE)
16522 enumtype = cxx_make_type (ENUMERAL_TYPE);
16523 enumtype = pushtag (name, enumtype);
16525 /* std::byte aliases anything. */
16526 if (enumtype != error_mark_node
16527 && TYPE_CONTEXT (enumtype) == std_node
16528 && !strcmp ("byte", TYPE_NAME_STRING (enumtype)))
16529 TYPE_ALIAS_SET (enumtype) = 0;
16531 else
16532 enumtype = xref_tag (enum_type, name);
16534 if (enumtype == error_mark_node)
16535 return error_mark_node;
16537 /* The enum is considered opaque until the opening '{' of the
16538 enumerator list. */
16539 SET_OPAQUE_ENUM_P (enumtype, true);
16540 ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) = !! underlying_type;
16543 SET_SCOPED_ENUM_P (enumtype, scoped_enum_p);
16545 cplus_decl_attributes (&enumtype, attributes, (int)ATTR_FLAG_TYPE_IN_PLACE);
16547 if (underlying_type)
16549 if (ENUM_UNDERLYING_TYPE (enumtype))
16550 /* We already checked that it matches, don't change it to a different
16551 typedef variant. */;
16552 else if (CP_INTEGRAL_TYPE_P (underlying_type))
16554 copy_type_enum (enumtype, underlying_type);
16555 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
16557 else if (dependent_type_p (underlying_type))
16558 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
16559 else
16561 error ("underlying type %qT of %qT must be an integral type",
16562 underlying_type, enumtype);
16563 ENUM_UNDERLYING_TYPE (enumtype) = integer_type_node;
16567 /* If into a template class, the returned enum is always the first
16568 declaration (opaque or not) seen. This way all the references to
16569 this type will be to the same declaration. The following ones are used
16570 only to check for definition errors. */
16571 if (prevtype && processing_template_decl)
16572 return prevtype;
16573 else
16574 return enumtype;
16577 /* After processing and defining all the values of an enumeration type,
16578 install their decls in the enumeration type.
16579 ENUMTYPE is the type object. */
16581 void
16582 finish_enum_value_list (tree enumtype)
16584 tree values;
16585 tree underlying_type;
16586 tree decl;
16587 tree value;
16588 tree minnode, maxnode;
16589 tree t;
16591 bool fixed_underlying_type_p
16592 = ENUM_UNDERLYING_TYPE (enumtype) != NULL_TREE;
16594 /* We built up the VALUES in reverse order. */
16595 TYPE_VALUES (enumtype) = nreverse (TYPE_VALUES (enumtype));
16597 /* For an enum defined in a template, just set the type of the values;
16598 all further processing is postponed until the template is
16599 instantiated. We need to set the type so that tsubst of a CONST_DECL
16600 works. */
16601 if (processing_template_decl)
16603 for (values = TYPE_VALUES (enumtype);
16604 values;
16605 values = TREE_CHAIN (values))
16606 TREE_TYPE (TREE_VALUE (values)) = enumtype;
16607 return;
16610 /* Determine the minimum and maximum values of the enumerators. */
16611 if (TYPE_VALUES (enumtype))
16613 minnode = maxnode = NULL_TREE;
16615 for (values = TYPE_VALUES (enumtype);
16616 values;
16617 values = TREE_CHAIN (values))
16619 decl = TREE_VALUE (values);
16621 /* [dcl.enum]: Following the closing brace of an enum-specifier,
16622 each enumerator has the type of its enumeration. Prior to the
16623 closing brace, the type of each enumerator is the type of its
16624 initializing value. */
16625 TREE_TYPE (decl) = enumtype;
16627 /* Update the minimum and maximum values, if appropriate. */
16628 value = DECL_INITIAL (decl);
16629 if (TREE_CODE (value) != INTEGER_CST)
16630 value = integer_zero_node;
16631 /* Figure out what the minimum and maximum values of the
16632 enumerators are. */
16633 if (!minnode)
16634 minnode = maxnode = value;
16635 else if (tree_int_cst_lt (maxnode, value))
16636 maxnode = value;
16637 else if (tree_int_cst_lt (value, minnode))
16638 minnode = value;
16641 else
16642 /* [dcl.enum]
16644 If the enumerator-list is empty, the underlying type is as if
16645 the enumeration had a single enumerator with value 0. */
16646 minnode = maxnode = integer_zero_node;
16648 if (!fixed_underlying_type_p)
16650 /* Compute the number of bits require to represent all values of the
16651 enumeration. We must do this before the type of MINNODE and
16652 MAXNODE are transformed, since tree_int_cst_min_precision relies
16653 on the TREE_TYPE of the value it is passed. */
16654 signop sgn = tree_int_cst_sgn (minnode) >= 0 ? UNSIGNED : SIGNED;
16655 int lowprec = tree_int_cst_min_precision (minnode, sgn);
16656 int highprec = tree_int_cst_min_precision (maxnode, sgn);
16657 int precision = MAX (lowprec, highprec);
16658 unsigned int itk;
16659 bool use_short_enum;
16661 /* Determine the underlying type of the enumeration.
16663 [dcl.enum]
16665 The underlying type of an enumeration is an integral type that
16666 can represent all the enumerator values defined in the
16667 enumeration. It is implementation-defined which integral type is
16668 used as the underlying type for an enumeration except that the
16669 underlying type shall not be larger than int unless the value of
16670 an enumerator cannot fit in an int or unsigned int.
16672 We use "int" or an "unsigned int" as the underlying type, even if
16673 a smaller integral type would work, unless the user has
16674 explicitly requested that we use the smallest possible type. The
16675 user can request that for all enumerations with a command line
16676 flag, or for just one enumeration with an attribute. */
16678 use_short_enum = flag_short_enums
16679 || lookup_attribute ("packed", TYPE_ATTRIBUTES (enumtype));
16681 /* If the precision of the type was specified with an attribute and it
16682 was too small, give an error. Otherwise, use it. */
16683 if (TYPE_PRECISION (enumtype))
16685 if (precision > TYPE_PRECISION (enumtype))
16686 error ("specified mode too small for enumerated values");
16687 else
16689 use_short_enum = true;
16690 precision = TYPE_PRECISION (enumtype);
16694 for (itk = (use_short_enum ? itk_char : itk_int);
16695 itk != itk_none;
16696 itk++)
16698 underlying_type = integer_types[itk];
16699 if (underlying_type != NULL_TREE
16700 && TYPE_PRECISION (underlying_type) >= precision
16701 && TYPE_SIGN (underlying_type) == sgn)
16702 break;
16704 if (itk == itk_none)
16706 /* DR 377
16708 IF no integral type can represent all the enumerator values, the
16709 enumeration is ill-formed. */
16710 error ("no integral type can represent all of the enumerator values "
16711 "for %qT", enumtype);
16712 precision = TYPE_PRECISION (long_long_integer_type_node);
16713 underlying_type = integer_types[itk_unsigned_long_long];
16716 /* [dcl.enum]
16718 The value of sizeof() applied to an enumeration type, an object
16719 of an enumeration type, or an enumerator, is the value of sizeof()
16720 applied to the underlying type. */
16721 copy_type_enum (enumtype, underlying_type);
16723 /* Compute the minimum and maximum values for the type.
16725 [dcl.enum]
16727 For an enumeration where emin is the smallest enumerator and emax
16728 is the largest, the values of the enumeration are the values of the
16729 underlying type in the range bmin to bmax, where bmin and bmax are,
16730 respectively, the smallest and largest values of the smallest bit-
16731 field that can store emin and emax. */
16733 /* The middle-end currently assumes that types with TYPE_PRECISION
16734 narrower than their underlying type are suitably zero or sign
16735 extended to fill their mode. Similarly, it assumes that the front
16736 end assures that a value of a particular type must be within
16737 TYPE_MIN_VALUE and TYPE_MAX_VALUE.
16739 We used to set these fields based on bmin and bmax, but that led
16740 to invalid assumptions like optimizing away bounds checking. So
16741 now we just set the TYPE_PRECISION, TYPE_MIN_VALUE, and
16742 TYPE_MAX_VALUE to the values for the mode above and only restrict
16743 the ENUM_UNDERLYING_TYPE for the benefit of diagnostics. */
16744 ENUM_UNDERLYING_TYPE (enumtype)
16745 = build_distinct_type_copy (underlying_type);
16746 TYPE_PRECISION (ENUM_UNDERLYING_TYPE (enumtype)) = precision;
16747 set_min_and_max_values_for_integral_type
16748 (ENUM_UNDERLYING_TYPE (enumtype), precision, sgn);
16750 /* If -fstrict-enums, still constrain TYPE_MIN/MAX_VALUE. */
16751 if (flag_strict_enums)
16752 set_min_and_max_values_for_integral_type (enumtype, precision, sgn);
16754 else
16755 underlying_type = ENUM_UNDERLYING_TYPE (enumtype);
16757 /* If the enum is exported, mark the consts too. */
16758 bool export_p = (UNSCOPED_ENUM_P (enumtype)
16759 && DECL_MODULE_EXPORT_P (TYPE_STUB_DECL (enumtype))
16760 && at_namespace_scope_p ());
16762 /* Convert each of the enumerators to the type of the underlying
16763 type of the enumeration. */
16764 for (values = TYPE_VALUES (enumtype); values; values = TREE_CHAIN (values))
16766 decl = TREE_VALUE (values);
16767 iloc_sentinel ils (DECL_SOURCE_LOCATION (decl));
16768 if (fixed_underlying_type_p)
16769 /* If the enumeration type has a fixed underlying type, we
16770 already checked all of the enumerator values. */
16771 value = DECL_INITIAL (decl);
16772 else
16773 value = perform_implicit_conversion (underlying_type,
16774 DECL_INITIAL (decl),
16775 tf_warning_or_error);
16776 /* Do not clobber shared ints. */
16777 if (value != error_mark_node)
16779 value = copy_node (value);
16781 TREE_TYPE (value) = enumtype;
16783 DECL_INITIAL (decl) = value;
16784 if (export_p)
16785 DECL_MODULE_EXPORT_P (decl) = true;
16788 /* Fix up all variant types of this enum type. */
16789 for (t = TYPE_MAIN_VARIANT (enumtype); t; t = TYPE_NEXT_VARIANT (t))
16790 TYPE_VALUES (t) = TYPE_VALUES (enumtype);
16792 if (at_class_scope_p ()
16793 && COMPLETE_TYPE_P (current_class_type)
16794 && UNSCOPED_ENUM_P (enumtype))
16796 insert_late_enum_def_bindings (current_class_type, enumtype);
16797 /* TYPE_FIELDS needs fixup. */
16798 fixup_type_variants (current_class_type);
16801 /* Finish debugging output for this type. */
16802 rest_of_type_compilation (enumtype, namespace_bindings_p ());
16804 /* Each enumerator now has the type of its enumeration. Clear the cache
16805 so that this change in types doesn't confuse us later on. */
16806 clear_cv_and_fold_caches ();
16809 /* Finishes the enum type. This is called only the first time an
16810 enumeration is seen, be it opaque or odinary.
16811 ENUMTYPE is the type object. */
16813 void
16814 finish_enum (tree enumtype)
16816 if (processing_template_decl)
16818 if (at_function_scope_p ())
16819 add_stmt (build_min (TAG_DEFN, enumtype));
16820 return;
16823 /* If this is a forward declaration, there should not be any variants,
16824 though we can get a variant in the middle of an enum-specifier with
16825 wacky code like 'enum E { e = sizeof(const E*) };' */
16826 gcc_assert (enumtype == TYPE_MAIN_VARIANT (enumtype)
16827 && (TYPE_VALUES (enumtype)
16828 || !TYPE_NEXT_VARIANT (enumtype)));
16831 /* Build and install a CONST_DECL for an enumeration constant of the
16832 enumeration type ENUMTYPE whose NAME and VALUE (if any) are provided.
16833 Apply ATTRIBUTES if available. LOC is the location of NAME.
16834 Assignment of sequential values by default is handled here. */
16836 tree
16837 build_enumerator (tree name, tree value, tree enumtype, tree attributes,
16838 location_t loc)
16840 tree decl;
16841 tree context;
16842 tree type;
16844 /* scalar_constant_value will pull out this expression, so make sure
16845 it's folded as appropriate. */
16846 if (processing_template_decl)
16847 value = fold_non_dependent_expr (value);
16849 /* If the VALUE was erroneous, pretend it wasn't there; that will
16850 result in the enum being assigned the next value in sequence. */
16851 if (value == error_mark_node)
16852 value = NULL_TREE;
16854 /* Remove no-op casts from the value. */
16855 if (value)
16856 STRIP_TYPE_NOPS (value);
16858 if (! processing_template_decl)
16860 /* Validate and default VALUE. */
16861 if (value != NULL_TREE)
16863 if (!ENUM_UNDERLYING_TYPE (enumtype))
16865 tree tmp_value = build_expr_type_conversion (WANT_INT | WANT_ENUM,
16866 value, true);
16867 if (tmp_value)
16868 value = tmp_value;
16870 else if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
16871 (TREE_TYPE (value)))
16872 value = perform_implicit_conversion_flags
16873 (ENUM_UNDERLYING_TYPE (enumtype), value, tf_warning_or_error,
16874 LOOKUP_IMPLICIT | LOOKUP_NO_NARROWING);
16876 if (value == error_mark_node)
16877 value = NULL_TREE;
16879 if (value != NULL_TREE)
16881 if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
16882 (TREE_TYPE (value)))
16884 error_at (cp_expr_loc_or_input_loc (value),
16885 "enumerator value for %qD must have integral or "
16886 "unscoped enumeration type", name);
16887 value = NULL_TREE;
16889 else
16891 value = cxx_constant_value (value);
16893 if (TREE_CODE (value) != INTEGER_CST)
16895 error ("enumerator value for %qD is not an integer "
16896 "constant", name);
16897 value = NULL_TREE;
16903 /* Default based on previous value. */
16904 if (value == NULL_TREE)
16906 if (TYPE_VALUES (enumtype))
16908 tree prev_value;
16910 /* C++03 7.2/4: If no initializer is specified for the first
16911 enumerator, the type is an unspecified integral
16912 type. Otherwise the type is the same as the type of the
16913 initializing value of the preceding enumerator unless the
16914 incremented value is not representable in that type, in
16915 which case the type is an unspecified integral type
16916 sufficient to contain the incremented value. */
16917 prev_value = DECL_INITIAL (TREE_VALUE (TYPE_VALUES (enumtype)));
16918 if (TREE_CODE (prev_value) != INTEGER_CST)
16919 value = error_mark_node;
16920 else
16922 wi::overflow_type overflowed;
16923 tree type = TREE_TYPE (prev_value);
16924 signop sgn = TYPE_SIGN (type);
16925 widest_int wi = wi::add (wi::to_widest (prev_value), 1, sgn,
16926 &overflowed);
16927 if (!overflowed)
16929 bool pos = !wi::neg_p (wi, sgn);
16930 if (!wi::fits_to_tree_p (wi, type))
16932 unsigned int itk;
16933 for (itk = itk_int; itk != itk_none; itk++)
16935 type = integer_types[itk];
16936 if (type != NULL_TREE
16937 && (pos || !TYPE_UNSIGNED (type))
16938 && wi::fits_to_tree_p (wi, type))
16939 break;
16941 if (type && cxx_dialect < cxx11
16942 && itk > itk_unsigned_long)
16943 pedwarn (input_location, OPT_Wlong_long,
16944 pos ? G_("\
16945 incremented enumerator value is too large for %<unsigned long%>") : G_("\
16946 incremented enumerator value is too large for %<long%>"));
16948 if (type == NULL_TREE)
16949 overflowed = wi::OVF_UNKNOWN;
16950 else
16951 value = wide_int_to_tree (type, wi);
16954 if (overflowed)
16956 error ("overflow in enumeration values at %qD", name);
16957 value = error_mark_node;
16961 else
16962 value = integer_zero_node;
16965 /* Remove no-op casts from the value. */
16966 STRIP_TYPE_NOPS (value);
16968 /* If the underlying type of the enum is fixed, check whether
16969 the enumerator values fits in the underlying type. If it
16970 does not fit, the program is ill-formed [C++0x dcl.enum]. */
16971 if (ENUM_UNDERLYING_TYPE (enumtype)
16972 && value
16973 && TREE_CODE (value) == INTEGER_CST)
16975 if (!int_fits_type_p (value, ENUM_UNDERLYING_TYPE (enumtype)))
16976 error ("enumerator value %qE is outside the range of underlying "
16977 "type %qT", value, ENUM_UNDERLYING_TYPE (enumtype));
16979 /* Convert the value to the appropriate type. */
16980 value = fold_convert (ENUM_UNDERLYING_TYPE (enumtype), value);
16984 /* C++ associates enums with global, function, or class declarations. */
16985 context = current_scope ();
16987 /* Build the actual enumeration constant. Note that the enumeration
16988 constants have the underlying type of the enum (if it is fixed)
16989 or the type of their initializer (if the underlying type of the
16990 enum is not fixed):
16992 [ C++0x dcl.enum ]
16994 If the underlying type is fixed, the type of each enumerator
16995 prior to the closing brace is the underlying type; if the
16996 initializing value of an enumerator cannot be represented by
16997 the underlying type, the program is ill-formed. If the
16998 underlying type is not fixed, the type of each enumerator is
16999 the type of its initializing value.
17001 If the underlying type is not fixed, it will be computed by
17002 finish_enum and we will reset the type of this enumerator. Of
17003 course, if we're processing a template, there may be no value. */
17004 type = value ? TREE_TYPE (value) : NULL_TREE;
17006 decl = build_decl (loc, CONST_DECL, name, type);
17008 DECL_CONTEXT (decl) = enumtype;
17009 TREE_CONSTANT (decl) = 1;
17010 TREE_READONLY (decl) = 1;
17011 DECL_INITIAL (decl) = value;
17013 if (attributes)
17014 cplus_decl_attributes (&decl, attributes, 0);
17016 if (context && context == current_class_type && !SCOPED_ENUM_P (enumtype))
17018 /* In something like `struct S { enum E { i = 7 }; };' we put `i'
17019 on the TYPE_FIELDS list for `S'. (That's so that you can say
17020 things like `S::i' later.) */
17022 /* The enumerator may be getting declared outside of its enclosing
17023 class, like so:
17025 class S { public: enum E : int; }; enum S::E : int { i = 7; };
17027 For which case we need to make sure that the access of `S::i'
17028 matches the access of `S::E'. */
17029 auto cas = make_temp_override (current_access_specifier);
17030 set_current_access_from_decl (TYPE_NAME (enumtype));
17031 finish_member_declaration (decl);
17033 else
17034 pushdecl (decl);
17036 /* Add this enumeration constant to the list for this type. */
17037 TYPE_VALUES (enumtype) = tree_cons (name, decl, TYPE_VALUES (enumtype));
17039 return decl;
17042 /* Look for an enumerator with the given NAME within the enumeration
17043 type ENUMTYPE. This routine is used primarily for qualified name
17044 lookup into an enumerator in C++0x, e.g.,
17046 enum class Color { Red, Green, Blue };
17048 Color color = Color::Red;
17050 Returns the value corresponding to the enumerator, or
17051 NULL_TREE if no such enumerator was found. */
17052 tree
17053 lookup_enumerator (tree enumtype, tree name)
17055 tree e;
17056 gcc_assert (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE);
17058 e = purpose_member (name, TYPE_VALUES (enumtype));
17059 return e? TREE_VALUE (e) : NULL_TREE;
17062 /* Implement LANG_HOOKS_SIMULATE_ENUM_DECL. */
17064 tree
17065 cxx_simulate_enum_decl (location_t loc, const char *name,
17066 vec<string_int_pair> *values)
17068 location_t saved_loc = input_location;
17069 input_location = loc;
17071 tree enumtype = start_enum (get_identifier (name), NULL_TREE, NULL_TREE,
17072 NULL_TREE, false, NULL);
17073 if (!OPAQUE_ENUM_P (enumtype))
17075 error_at (loc, "multiple definition of %q#T", enumtype);
17076 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
17077 "previous definition here");
17078 return enumtype;
17080 SET_OPAQUE_ENUM_P (enumtype, false);
17081 DECL_SOURCE_LOCATION (TYPE_NAME (enumtype)) = loc;
17083 for (const string_int_pair &value : values)
17084 build_enumerator (get_identifier (value.first),
17085 build_int_cst (integer_type_node, value.second),
17086 enumtype, NULL_TREE, loc);
17088 finish_enum_value_list (enumtype);
17089 finish_enum (enumtype);
17091 input_location = saved_loc;
17092 return enumtype;
17095 /* Implement LANG_HOOKS_SIMULATE_RECORD_DECL. */
17097 tree
17098 cxx_simulate_record_decl (location_t loc, const char *name,
17099 array_slice<const tree> fields)
17101 iloc_sentinel ils (loc);
17103 tree ident = get_identifier (name);
17104 tree type = xref_tag (/*tag_code=*/record_type, ident);
17105 if (type != error_mark_node
17106 && (TREE_CODE (type) != RECORD_TYPE || COMPLETE_TYPE_P (type)))
17108 error ("redefinition of %q#T", type);
17109 type = error_mark_node;
17111 if (type == error_mark_node)
17112 return lhd_simulate_record_decl (loc, name, fields);
17114 xref_basetypes (type, NULL_TREE);
17115 type = begin_class_definition (type);
17116 if (type == error_mark_node)
17117 return lhd_simulate_record_decl (loc, name, fields);
17119 for (tree field : fields)
17120 finish_member_declaration (field);
17122 type = finish_struct (type, NULL_TREE);
17124 tree decl = build_decl (loc, TYPE_DECL, ident, type);
17125 set_underlying_type (decl);
17126 lang_hooks.decls.pushdecl (decl);
17128 return type;
17131 /* We're defining DECL. Make sure that its type is OK. */
17133 static void
17134 check_function_type (tree decl, tree current_function_parms)
17136 tree fntype = TREE_TYPE (decl);
17137 tree return_type = complete_type (TREE_TYPE (fntype));
17139 /* In a function definition, arg types must be complete. */
17140 require_complete_types_for_parms (current_function_parms);
17142 if (dependent_type_p (return_type)
17143 || type_uses_auto (return_type))
17144 return;
17145 if (!COMPLETE_OR_VOID_TYPE_P (return_type))
17147 tree args = TYPE_ARG_TYPES (fntype);
17149 error ("return type %q#T is incomplete", return_type);
17151 /* Make it return void instead. */
17152 if (TREE_CODE (fntype) == METHOD_TYPE)
17153 fntype = build_method_type_directly (TREE_TYPE (TREE_VALUE (args)),
17154 void_type_node,
17155 TREE_CHAIN (args));
17156 else
17157 fntype = build_function_type (void_type_node, args);
17158 fntype = (cp_build_type_attribute_variant
17159 (fntype, TYPE_ATTRIBUTES (TREE_TYPE (decl))));
17160 fntype = cxx_copy_lang_qualifiers (fntype, TREE_TYPE (decl));
17161 TREE_TYPE (decl) = fntype;
17163 else
17165 abstract_virtuals_error (decl, TREE_TYPE (fntype));
17166 maybe_warn_parm_abi (TREE_TYPE (fntype),
17167 DECL_SOURCE_LOCATION (decl));
17171 /* True iff FN is an implicitly-defined default constructor. */
17173 static bool
17174 implicit_default_ctor_p (tree fn)
17176 return (DECL_CONSTRUCTOR_P (fn)
17177 && !user_provided_p (fn)
17178 && sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (fn)));
17181 /* Clobber the contents of *this to let the back end know that the object
17182 storage is dead when we enter the constructor or leave the destructor. */
17184 static tree
17185 build_clobber_this ()
17187 /* Clobbering an empty base is pointless, and harmful if its one byte
17188 TYPE_SIZE overlays real data. */
17189 if (is_empty_class (current_class_type))
17190 return void_node;
17192 /* If we have virtual bases, clobber the whole object, but only if we're in
17193 charge. If we don't have virtual bases, clobber the as-base type so we
17194 don't mess with tail padding. */
17195 bool vbases = CLASSTYPE_VBASECLASSES (current_class_type);
17197 tree ctype = current_class_type;
17198 if (!vbases)
17199 ctype = CLASSTYPE_AS_BASE (ctype);
17201 tree clobber = build_clobber (ctype);
17203 tree thisref = current_class_ref;
17204 if (ctype != current_class_type)
17206 thisref = build_nop (build_reference_type (ctype), current_class_ptr);
17207 thisref = convert_from_reference (thisref);
17210 tree exprstmt = build2 (MODIFY_EXPR, void_type_node, thisref, clobber);
17211 if (vbases)
17212 exprstmt = build_if_in_charge (exprstmt);
17214 return exprstmt;
17217 /* Create the FUNCTION_DECL for a function definition.
17218 DECLSPECS and DECLARATOR are the parts of the declaration;
17219 they describe the function's name and the type it returns,
17220 but twisted together in a fashion that parallels the syntax of C.
17222 FLAGS is a bitwise or of SF_PRE_PARSED (indicating that the
17223 DECLARATOR is really the DECL for the function we are about to
17224 process and that DECLSPECS should be ignored), SF_INCLASS_INLINE
17225 indicating that the function is an inline defined in-class.
17227 This function creates a binding context for the function body
17228 as well as setting up the FUNCTION_DECL in current_function_decl.
17230 For C++, we must first check whether that datum makes any sense.
17231 For example, "class A local_a(1,2);" means that variable local_a
17232 is an aggregate of type A, which should have a constructor
17233 applied to it with the argument list [1, 2].
17235 On entry, DECL_INITIAL (decl1) should be NULL_TREE or error_mark_node,
17236 or may be a BLOCK if the function has been defined previously
17237 in this translation unit. On exit, DECL_INITIAL (decl1) will be
17238 error_mark_node if the function has never been defined, or
17239 a BLOCK if the function has been defined somewhere. */
17241 bool
17242 start_preparsed_function (tree decl1, tree attrs, int flags)
17244 tree ctype = NULL_TREE;
17245 bool doing_friend = false;
17247 /* Sanity check. */
17248 gcc_assert (VOID_TYPE_P (TREE_VALUE (void_list_node)));
17249 gcc_assert (TREE_CHAIN (void_list_node) == NULL_TREE);
17251 tree fntype = TREE_TYPE (decl1);
17252 if (TREE_CODE (fntype) == METHOD_TYPE)
17253 ctype = TYPE_METHOD_BASETYPE (fntype);
17254 else
17256 ctype = DECL_FRIEND_CONTEXT (decl1);
17258 if (ctype)
17259 doing_friend = true;
17262 if (DECL_DECLARED_INLINE_P (decl1)
17263 && lookup_attribute ("noinline", attrs))
17264 warning_at (DECL_SOURCE_LOCATION (decl1), 0,
17265 "inline function %qD given attribute %qs", decl1, "noinline");
17267 /* Handle gnu_inline attribute. */
17268 if (GNU_INLINE_P (decl1))
17270 DECL_EXTERNAL (decl1) = 1;
17271 DECL_NOT_REALLY_EXTERN (decl1) = 0;
17272 DECL_INTERFACE_KNOWN (decl1) = 1;
17273 DECL_DISREGARD_INLINE_LIMITS (decl1) = 1;
17276 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl1))
17277 /* This is a constructor, we must ensure that any default args
17278 introduced by this definition are propagated to the clones
17279 now. The clones are used directly in overload resolution. */
17280 adjust_clone_args (decl1);
17282 /* Sometimes we don't notice that a function is a static member, and
17283 build a METHOD_TYPE for it. Fix that up now. */
17284 gcc_assert (!(ctype != NULL_TREE && DECL_STATIC_FUNCTION_P (decl1)
17285 && TREE_CODE (TREE_TYPE (decl1)) == METHOD_TYPE));
17287 /* Set up current_class_type, and enter the scope of the class, if
17288 appropriate. */
17289 if (ctype)
17290 push_nested_class (ctype);
17291 else if (DECL_STATIC_FUNCTION_P (decl1))
17292 push_nested_class (DECL_CONTEXT (decl1));
17294 /* Now that we have entered the scope of the class, we must restore
17295 the bindings for any template parameters surrounding DECL1, if it
17296 is an inline member template. (Order is important; consider the
17297 case where a template parameter has the same name as a field of
17298 the class.) It is not until after this point that
17299 PROCESSING_TEMPLATE_DECL is guaranteed to be set up correctly. */
17300 if (flags & SF_INCLASS_INLINE)
17301 maybe_begin_member_template_processing (decl1);
17303 /* Effective C++ rule 15. */
17304 if (warn_ecpp
17305 && DECL_ASSIGNMENT_OPERATOR_P (decl1)
17306 && DECL_OVERLOADED_OPERATOR_IS (decl1, NOP_EXPR)
17307 && VOID_TYPE_P (TREE_TYPE (fntype)))
17308 warning (OPT_Weffc__,
17309 "%<operator=%> should return a reference to %<*this%>");
17311 /* Make the init_value nonzero so pushdecl knows this is not tentative.
17312 error_mark_node is replaced below (in poplevel) with the BLOCK. */
17313 if (!DECL_INITIAL (decl1))
17314 DECL_INITIAL (decl1) = error_mark_node;
17316 /* This function exists in static storage.
17317 (This does not mean `static' in the C sense!) */
17318 TREE_STATIC (decl1) = 1;
17320 /* We must call push_template_decl after current_class_type is set
17321 up. (If we are processing inline definitions after exiting a
17322 class scope, current_class_type will be NULL_TREE until set above
17323 by push_nested_class.) */
17324 if (processing_template_decl)
17326 tree newdecl1 = push_template_decl (decl1, doing_friend);
17327 if (newdecl1 == error_mark_node)
17329 if (ctype || DECL_STATIC_FUNCTION_P (decl1))
17330 pop_nested_class ();
17331 return false;
17333 decl1 = newdecl1;
17336 /* Make sure the parameter and return types are reasonable. When
17337 you declare a function, these types can be incomplete, but they
17338 must be complete when you define the function. */
17339 check_function_type (decl1, DECL_ARGUMENTS (decl1));
17341 /* Build the return declaration for the function. */
17342 tree restype = TREE_TYPE (fntype);
17344 if (DECL_RESULT (decl1) == NULL_TREE)
17346 /* In a template instantiation, copy the return type location. When
17347 parsing, the location will be set in grokdeclarator. */
17348 location_t loc = input_location;
17349 if (DECL_TEMPLATE_INSTANTIATION (decl1))
17351 tree tmpl = template_for_substitution (decl1);
17352 if (tree res = DECL_RESULT (DECL_TEMPLATE_RESULT (tmpl)))
17353 loc = DECL_SOURCE_LOCATION (res);
17356 tree resdecl = build_decl (loc, RESULT_DECL, 0, restype);
17357 DECL_ARTIFICIAL (resdecl) = 1;
17358 DECL_IGNORED_P (resdecl) = 1;
17359 DECL_RESULT (decl1) = resdecl;
17361 cp_apply_type_quals_to_decl (cp_type_quals (restype), resdecl);
17364 /* Record the decl so that the function name is defined.
17365 If we already have a decl for this name, and it is a FUNCTION_DECL,
17366 use the old decl. */
17367 if (!processing_template_decl && !(flags & SF_PRE_PARSED))
17369 /* A specialization is not used to guide overload resolution. */
17370 if (!DECL_FUNCTION_MEMBER_P (decl1)
17371 && !(DECL_USE_TEMPLATE (decl1) &&
17372 PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl1))))
17374 tree olddecl = pushdecl (decl1);
17376 if (olddecl == error_mark_node)
17377 /* If something went wrong when registering the declaration,
17378 use DECL1; we have to have a FUNCTION_DECL to use when
17379 parsing the body of the function. */
17381 else
17383 /* Otherwise, OLDDECL is either a previous declaration
17384 of the same function or DECL1 itself. */
17386 if (warn_missing_declarations
17387 && olddecl == decl1
17388 && !DECL_MAIN_P (decl1)
17389 && TREE_PUBLIC (decl1)
17390 && !DECL_DECLARED_INLINE_P (decl1))
17392 tree context;
17394 /* Check whether DECL1 is in an anonymous
17395 namespace. */
17396 for (context = DECL_CONTEXT (decl1);
17397 context;
17398 context = DECL_CONTEXT (context))
17400 if (TREE_CODE (context) == NAMESPACE_DECL
17401 && DECL_NAME (context) == NULL_TREE)
17402 break;
17405 if (context == NULL)
17406 warning_at (DECL_SOURCE_LOCATION (decl1),
17407 OPT_Wmissing_declarations,
17408 "no previous declaration for %qD", decl1);
17411 decl1 = olddecl;
17414 else
17416 /* We need to set the DECL_CONTEXT. */
17417 if (!DECL_CONTEXT (decl1) && DECL_TEMPLATE_INFO (decl1))
17418 DECL_CONTEXT (decl1) = DECL_CONTEXT (DECL_TI_TEMPLATE (decl1));
17420 fntype = TREE_TYPE (decl1);
17421 restype = TREE_TYPE (fntype);
17423 /* If #pragma weak applies, mark the decl appropriately now.
17424 The pragma only applies to global functions. Because
17425 determining whether or not the #pragma applies involves
17426 computing the mangled name for the declaration, we cannot
17427 apply the pragma until after we have merged this declaration
17428 with any previous declarations; if the original declaration
17429 has a linkage specification, that specification applies to
17430 the definition as well, and may affect the mangled name. */
17431 if (DECL_FILE_SCOPE_P (decl1))
17432 maybe_apply_pragma_weak (decl1);
17435 /* We are now in the scope of the function being defined. */
17436 current_function_decl = decl1;
17438 /* Save the parm names or decls from this function's declarator
17439 where store_parm_decls will find them. */
17440 tree current_function_parms = DECL_ARGUMENTS (decl1);
17442 /* Let the user know we're compiling this function. */
17443 announce_function (decl1);
17445 gcc_assert (DECL_INITIAL (decl1));
17447 /* This function may already have been parsed, in which case just
17448 return; our caller will skip over the body without parsing. */
17449 if (DECL_INITIAL (decl1) != error_mark_node)
17450 return true;
17452 /* Initialize RTL machinery. We cannot do this until
17453 CURRENT_FUNCTION_DECL and DECL_RESULT are set up. We do this
17454 even when processing a template; this is how we get
17455 CFUN set up, and our per-function variables initialized.
17456 FIXME factor out the non-RTL stuff. */
17457 cp_binding_level *bl = current_binding_level;
17458 allocate_struct_function (decl1, processing_template_decl);
17460 /* Initialize the language data structures. Whenever we start
17461 a new function, we destroy temporaries in the usual way. */
17462 cfun->language = ggc_cleared_alloc<language_function> ();
17463 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
17464 current_binding_level = bl;
17466 /* If we are (erroneously) defining a function that we have already
17467 defined before, wipe out what we knew before. */
17468 gcc_checking_assert (!DECL_PENDING_INLINE_P (decl1));
17469 FNDECL_USED_AUTO (decl1) = false;
17470 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = NULL;
17472 if (!processing_template_decl && type_uses_auto (restype))
17474 FNDECL_USED_AUTO (decl1) = true;
17475 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = restype;
17478 /* Start the statement-tree, start the tree now. */
17479 DECL_SAVED_TREE (decl1) = push_stmt_list ();
17481 if (ctype && !doing_friend && !DECL_STATIC_FUNCTION_P (decl1))
17483 /* We know that this was set up by `grokclassfn'. We do not
17484 wait until `store_parm_decls', since evil parse errors may
17485 never get us to that point. Here we keep the consistency
17486 between `current_class_type' and `current_class_ptr'. */
17487 tree t = DECL_ARGUMENTS (decl1);
17489 gcc_assert (t != NULL_TREE && TREE_CODE (t) == PARM_DECL);
17490 gcc_assert (TYPE_PTR_P (TREE_TYPE (t)));
17492 cp_function_chain->x_current_class_ref
17493 = cp_build_fold_indirect_ref (t);
17494 /* Set this second to avoid shortcut in cp_build_indirect_ref. */
17495 cp_function_chain->x_current_class_ptr = t;
17497 /* Constructors and destructors need to know whether they're "in
17498 charge" of initializing virtual base classes. */
17499 t = DECL_CHAIN (t);
17500 if (DECL_HAS_IN_CHARGE_PARM_P (decl1))
17502 current_in_charge_parm = t;
17503 t = DECL_CHAIN (t);
17505 if (DECL_HAS_VTT_PARM_P (decl1))
17507 gcc_assert (DECL_NAME (t) == vtt_parm_identifier);
17508 current_vtt_parm = t;
17512 bool honor_interface = (!DECL_TEMPLATE_INSTANTIATION (decl1)
17513 /* Implicitly-defined methods (like the
17514 destructor for a class in which no destructor
17515 is explicitly declared) must not be defined
17516 until their definition is needed. So, we
17517 ignore interface specifications for
17518 compiler-generated functions. */
17519 && !DECL_ARTIFICIAL (decl1));
17520 struct c_fileinfo *finfo
17521 = get_fileinfo (LOCATION_FILE (DECL_SOURCE_LOCATION (decl1)));
17523 if (processing_template_decl)
17524 /* Don't mess with interface flags. */;
17525 else if (DECL_INTERFACE_KNOWN (decl1))
17527 tree ctx = decl_function_context (decl1);
17529 if (DECL_NOT_REALLY_EXTERN (decl1))
17530 DECL_EXTERNAL (decl1) = 0;
17532 if (ctx != NULL_TREE && vague_linkage_p (ctx))
17533 /* This is a function in a local class in an extern inline
17534 or template function. */
17535 comdat_linkage (decl1);
17537 /* If this function belongs to an interface, it is public.
17538 If it belongs to someone else's interface, it is also external.
17539 This only affects inlines and template instantiations. */
17540 else if (!finfo->interface_unknown && honor_interface)
17542 if (DECL_DECLARED_INLINE_P (decl1)
17543 || DECL_TEMPLATE_INSTANTIATION (decl1))
17545 DECL_EXTERNAL (decl1)
17546 = (finfo->interface_only
17547 || (DECL_DECLARED_INLINE_P (decl1)
17548 && ! flag_implement_inlines
17549 && !DECL_VINDEX (decl1)));
17551 /* For WIN32 we also want to put these in linkonce sections. */
17552 maybe_make_one_only (decl1);
17554 else
17555 DECL_EXTERNAL (decl1) = 0;
17556 DECL_INTERFACE_KNOWN (decl1) = 1;
17557 /* If this function is in an interface implemented in this file,
17558 make sure that the back end knows to emit this function
17559 here. */
17560 if (!DECL_EXTERNAL (decl1))
17561 mark_needed (decl1);
17563 else if (finfo->interface_unknown && finfo->interface_only
17564 && honor_interface)
17566 /* If MULTIPLE_SYMBOL_SPACES is defined and we saw a #pragma
17567 interface, we will have both finfo->interface_unknown and
17568 finfo->interface_only set. In that case, we don't want to
17569 use the normal heuristics because someone will supply a
17570 #pragma implementation elsewhere, and deducing it here would
17571 produce a conflict. */
17572 comdat_linkage (decl1);
17573 DECL_EXTERNAL (decl1) = 0;
17574 DECL_INTERFACE_KNOWN (decl1) = 1;
17575 DECL_DEFER_OUTPUT (decl1) = 1;
17577 else
17579 /* This is a definition, not a reference.
17580 So clear DECL_EXTERNAL, unless this is a GNU extern inline. */
17581 if (!GNU_INLINE_P (decl1))
17582 DECL_EXTERNAL (decl1) = 0;
17584 if ((DECL_DECLARED_INLINE_P (decl1)
17585 || DECL_TEMPLATE_INSTANTIATION (decl1))
17586 && ! DECL_INTERFACE_KNOWN (decl1))
17587 DECL_DEFER_OUTPUT (decl1) = 1;
17588 else
17589 DECL_INTERFACE_KNOWN (decl1) = 1;
17592 /* Determine the ELF visibility attribute for the function. We must not
17593 do this before calling "pushdecl", as we must allow "duplicate_decls"
17594 to merge any attributes appropriately. We also need to wait until
17595 linkage is set. */
17596 if (!DECL_CLONED_FUNCTION_P (decl1))
17597 determine_visibility (decl1);
17599 if (!processing_template_decl)
17600 maybe_instantiate_noexcept (decl1);
17602 begin_scope (sk_function_parms, decl1);
17604 ++function_depth;
17606 start_fname_decls ();
17608 store_parm_decls (current_function_parms);
17610 start_function_contracts (decl1);
17612 if (!processing_template_decl
17613 && (flag_lifetime_dse > 1)
17614 && DECL_CONSTRUCTOR_P (decl1)
17615 && !DECL_CLONED_FUNCTION_P (decl1)
17616 /* Clobbering an empty base is harmful if it overlays real data. */
17617 && !is_empty_class (current_class_type)
17618 /* We can't clobber safely for an implicitly-defined default constructor
17619 because part of the initialization might happen before we enter the
17620 constructor, via AGGR_INIT_ZERO_FIRST (c++/68006). */
17621 && !implicit_default_ctor_p (decl1))
17622 finish_expr_stmt (build_clobber_this ());
17624 if (!processing_template_decl
17625 && DECL_CONSTRUCTOR_P (decl1)
17626 && sanitize_flags_p (SANITIZE_VPTR)
17627 && !DECL_CLONED_FUNCTION_P (decl1)
17628 && !implicit_default_ctor_p (decl1))
17629 cp_ubsan_maybe_initialize_vtbl_ptrs (current_class_ptr);
17631 if (!DECL_OMP_DECLARE_REDUCTION_P (decl1))
17632 start_lambda_scope (decl1);
17634 return true;
17638 /* Like start_preparsed_function, except that instead of a
17639 FUNCTION_DECL, this function takes DECLSPECS and DECLARATOR.
17641 Returns true on success. If the DECLARATOR is not suitable
17642 for a function, we return false, which tells the parser to
17643 skip the entire function. */
17645 bool
17646 start_function (cp_decl_specifier_seq *declspecs,
17647 const cp_declarator *declarator,
17648 tree attrs)
17650 tree decl1;
17652 decl1 = grokdeclarator (declarator, declspecs, FUNCDEF, 1, &attrs);
17653 invoke_plugin_callbacks (PLUGIN_START_PARSE_FUNCTION, decl1);
17654 if (decl1 == error_mark_node)
17655 return false;
17657 if (DECL_MAIN_P (decl1))
17658 /* main must return int. grokfndecl should have corrected it
17659 (and issued a diagnostic) if the user got it wrong. */
17660 gcc_assert (same_type_p (TREE_TYPE (TREE_TYPE (decl1)),
17661 integer_type_node));
17663 return start_preparsed_function (decl1, attrs, /*flags=*/SF_DEFAULT);
17666 /* Returns true iff an EH_SPEC_BLOCK should be created in the body of
17667 FN. */
17669 static bool
17670 use_eh_spec_block (tree fn)
17672 return (flag_exceptions && flag_enforce_eh_specs
17673 && !processing_template_decl
17674 /* We insert the EH_SPEC_BLOCK only in the original
17675 function; then, it is copied automatically to the
17676 clones. */
17677 && !DECL_CLONED_FUNCTION_P (fn)
17678 /* Implicitly-generated constructors and destructors have
17679 exception specifications. However, those specifications
17680 are the union of the possible exceptions specified by the
17681 constructors/destructors for bases and members, so no
17682 unallowed exception will ever reach this function. By
17683 not creating the EH_SPEC_BLOCK we save a little memory,
17684 and we avoid spurious warnings about unreachable
17685 code. */
17686 && !DECL_DEFAULTED_FN (fn)
17687 && !type_throw_all_p (TREE_TYPE (fn)));
17690 /* Helper function to push ARGS into the current lexical scope. DECL
17691 is the function declaration. NONPARMS is used to handle enum
17692 constants. */
17694 void
17695 do_push_parm_decls (tree decl, tree args, tree *nonparms)
17697 /* If we're doing semantic analysis, then we'll call pushdecl
17698 for each of these. We must do them in reverse order so that
17699 they end in the correct forward order. */
17700 args = nreverse (args);
17702 tree next;
17703 for (tree parm = args; parm; parm = next)
17705 next = DECL_CHAIN (parm);
17706 if (TREE_CODE (parm) == PARM_DECL)
17707 pushdecl (parm);
17708 else if (nonparms)
17710 /* If we find an enum constant or a type tag, put it aside for
17711 the moment. */
17712 TREE_CHAIN (parm) = NULL_TREE;
17713 *nonparms = chainon (*nonparms, parm);
17717 /* Get the decls in their original chain order and record in the
17718 function. This is all and only the PARM_DECLs that were
17719 pushed into scope by the loop above. */
17720 DECL_ARGUMENTS (decl) = get_local_decls ();
17723 /* Store the parameter declarations into the current function declaration.
17724 This is called after parsing the parameter declarations, before
17725 digesting the body of the function.
17727 Also install to binding contour return value identifier, if any. */
17729 static void
17730 store_parm_decls (tree current_function_parms)
17732 tree fndecl = current_function_decl;
17734 /* This is a chain of any other decls that came in among the parm
17735 declarations. If a parm is declared with enum {foo, bar} x;
17736 then CONST_DECLs for foo and bar are put here. */
17737 tree nonparms = NULL_TREE;
17739 if (current_function_parms)
17741 /* This case is when the function was defined with an ANSI prototype.
17742 The parms already have decls, so we need not do anything here
17743 except record them as in effect
17744 and complain if any redundant old-style parm decls were written. */
17746 tree specparms = current_function_parms;
17748 /* Must clear this because it might contain TYPE_DECLs declared
17749 at class level. */
17750 current_binding_level->names = NULL;
17752 do_push_parm_decls (fndecl, specparms, &nonparms);
17754 else
17755 DECL_ARGUMENTS (fndecl) = NULL_TREE;
17757 /* Now store the final chain of decls for the arguments
17758 as the decl-chain of the current lexical scope.
17759 Put the enumerators in as well, at the front so that
17760 DECL_ARGUMENTS is not modified. */
17761 current_binding_level->names = chainon (nonparms, DECL_ARGUMENTS (fndecl));
17763 if (use_eh_spec_block (current_function_decl))
17764 current_eh_spec_block = begin_eh_spec_block ();
17768 /* Set the return value of the [cd]tor if the ABI wants that. */
17770 void
17771 maybe_return_this (void)
17773 if (targetm.cxx.cdtor_returns_this ())
17775 /* Return the address of the object. */
17776 tree val = DECL_ARGUMENTS (current_function_decl);
17777 suppress_warning (val, OPT_Wuse_after_free);
17778 val = fold_convert (TREE_TYPE (DECL_RESULT (current_function_decl)), val);
17779 val = build2 (MODIFY_EXPR, TREE_TYPE (val),
17780 DECL_RESULT (current_function_decl), val);
17781 tree exprstmt = build_stmt (input_location, RETURN_EXPR, val);
17782 add_stmt (exprstmt);
17786 /* Do all the processing for the beginning of a destructor; set up the
17787 vtable pointers and cleanups for bases and members. */
17789 static void
17790 begin_destructor_body (void)
17792 tree compound_stmt;
17794 /* If the CURRENT_CLASS_TYPE is incomplete, we will have already
17795 issued an error message. We still want to try to process the
17796 body of the function, but initialize_vtbl_ptrs will crash if
17797 TYPE_BINFO is NULL. */
17798 if (COMPLETE_TYPE_P (current_class_type))
17800 compound_stmt = begin_compound_stmt (0);
17801 /* Make all virtual function table pointers in non-virtual base
17802 classes point to CURRENT_CLASS_TYPE's virtual function
17803 tables. */
17804 initialize_vtbl_ptrs (current_class_ptr);
17805 finish_compound_stmt (compound_stmt);
17807 if (flag_lifetime_dse
17808 /* Clobbering an empty base is harmful if it overlays real data. */
17809 && !is_empty_class (current_class_type))
17811 if (sanitize_flags_p (SANITIZE_VPTR)
17812 && (flag_sanitize_recover & SANITIZE_VPTR) == 0
17813 && TYPE_CONTAINS_VPTR_P (current_class_type))
17815 tree binfo = TYPE_BINFO (current_class_type);
17816 tree ref
17817 = cp_build_fold_indirect_ref (current_class_ptr);
17819 tree vtbl_ptr = build_vfield_ref (ref, TREE_TYPE (binfo));
17820 tree vtbl = build_zero_cst (TREE_TYPE (vtbl_ptr));
17821 tree stmt = cp_build_modify_expr (input_location, vtbl_ptr,
17822 NOP_EXPR, vtbl,
17823 tf_warning_or_error);
17824 /* If the vptr is shared with some virtual nearly empty base,
17825 don't clear it if not in charge, the dtor of the virtual
17826 nearly empty base will do that later. */
17827 if (CLASSTYPE_VBASECLASSES (current_class_type))
17829 tree c = current_class_type;
17830 while (CLASSTYPE_PRIMARY_BINFO (c))
17832 if (BINFO_VIRTUAL_P (CLASSTYPE_PRIMARY_BINFO (c)))
17834 stmt = convert_to_void (stmt, ICV_STATEMENT,
17835 tf_warning_or_error);
17836 stmt = build_if_in_charge (stmt);
17837 break;
17839 c = BINFO_TYPE (CLASSTYPE_PRIMARY_BINFO (c));
17842 finish_decl_cleanup (NULL_TREE, stmt);
17844 else
17845 finish_decl_cleanup (NULL_TREE, build_clobber_this ());
17848 /* And insert cleanups for our bases and members so that they
17849 will be properly destroyed if we throw. */
17850 push_base_cleanups ();
17854 /* Do the necessary processing for the beginning of a function body, which
17855 in this case includes member-initializers, but not the catch clauses of
17856 a function-try-block. Currently, this means opening a binding level
17857 for the member-initializers (in a ctor), member cleanups (in a dtor),
17858 and capture proxies (in a lambda operator()). */
17860 tree
17861 begin_function_body (void)
17863 if (! FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
17864 return NULL_TREE;
17866 if (processing_template_decl)
17867 /* Do nothing now. */;
17868 else
17869 /* Always keep the BLOCK node associated with the outermost pair of
17870 curly braces of a function. These are needed for correct
17871 operation of dwarfout.c. */
17872 keep_next_level (true);
17874 tree stmt = begin_compound_stmt (BCS_FN_BODY);
17876 if (processing_template_decl)
17877 /* Do nothing now. */;
17878 else if (DECL_DESTRUCTOR_P (current_function_decl))
17879 begin_destructor_body ();
17881 return stmt;
17884 /* Do the processing for the end of a function body. Currently, this means
17885 closing out the cleanups for fully-constructed bases and members, and in
17886 the case of the destructor, deleting the object if desired. Again, this
17887 is only meaningful for [cd]tors, since they are the only functions where
17888 there is a significant distinction between the main body and any
17889 function catch clauses. Handling, say, main() return semantics here
17890 would be wrong, as flowing off the end of a function catch clause for
17891 main() would also need to return 0. */
17893 void
17894 finish_function_body (tree compstmt)
17896 if (compstmt == NULL_TREE)
17897 return;
17899 /* Close the block. */
17900 finish_compound_stmt (compstmt);
17902 if (processing_template_decl)
17903 /* Do nothing now. */;
17904 else if (DECL_CONSTRUCTOR_P (current_function_decl)
17905 || DECL_DESTRUCTOR_P (current_function_decl))
17906 maybe_return_this ();
17909 /* Given a function, returns the BLOCK corresponding to the outermost level
17910 of curly braces, skipping the artificial block created for constructor
17911 initializers. */
17913 tree
17914 outer_curly_brace_block (tree fndecl)
17916 tree block = DECL_INITIAL (fndecl);
17917 if (BLOCK_OUTER_CURLY_BRACE_P (block))
17918 return block;
17919 block = BLOCK_SUBBLOCKS (block);
17920 if (BLOCK_OUTER_CURLY_BRACE_P (block))
17921 return block;
17922 block = BLOCK_SUBBLOCKS (block);
17923 gcc_assert (BLOCK_OUTER_CURLY_BRACE_P (block));
17924 return block;
17927 /* If FNDECL is a class's key method, add the class to the list of
17928 keyed classes that should be emitted. */
17930 static void
17931 record_key_method_defined (tree fndecl)
17933 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
17934 && DECL_VIRTUAL_P (fndecl)
17935 && !processing_template_decl)
17937 tree fnclass = DECL_CONTEXT (fndecl);
17938 if (fndecl == CLASSTYPE_KEY_METHOD (fnclass))
17939 vec_safe_push (keyed_classes, fnclass);
17943 /* Attempt to add a fix-it hint to RICHLOC suggesting the insertion
17944 of "return *this;" immediately before its location, using FNDECL's
17945 first statement (if any) to give the indentation, if appropriate. */
17947 static void
17948 add_return_star_this_fixit (gcc_rich_location *richloc, tree fndecl)
17950 location_t indent = UNKNOWN_LOCATION;
17951 tree stmts = expr_first (DECL_SAVED_TREE (fndecl));
17952 if (stmts)
17953 indent = EXPR_LOCATION (stmts);
17954 richloc->add_fixit_insert_formatted ("return *this;",
17955 richloc->get_loc (),
17956 indent);
17959 /* This function carries out the subset of finish_function operations needed
17960 to emit the compiler-generated outlined helper functions used by the
17961 coroutines implementation. */
17963 static void
17964 emit_coro_helper (tree helper)
17966 /* This is a partial set of the operations done by finish_function()
17967 plus emitting the result. */
17968 set_cfun (NULL);
17969 current_function_decl = helper;
17970 begin_scope (sk_function_parms, NULL);
17971 store_parm_decls (DECL_ARGUMENTS (helper));
17972 announce_function (helper);
17973 allocate_struct_function (helper, false);
17974 cfun->language = ggc_cleared_alloc<language_function> ();
17975 poplevel (1, 0, 1);
17976 maybe_save_constexpr_fundef (helper);
17977 /* We must start each function with a clear fold cache. */
17978 clear_fold_cache ();
17979 cp_fold_function (helper);
17980 DECL_CONTEXT (DECL_RESULT (helper)) = helper;
17981 BLOCK_SUPERCONTEXT (DECL_INITIAL (helper)) = helper;
17982 /* This function has coroutine IFNs that we should handle in middle
17983 end lowering. */
17984 cfun->coroutine_component = true;
17985 cp_genericize (helper);
17986 expand_or_defer_fn (helper);
17989 /* Finish up a function declaration and compile that function
17990 all the way to assembler language output. The free the storage
17991 for the function definition. INLINE_P is TRUE if we just
17992 finished processing the body of an in-class inline function
17993 definition. (This processing will have taken place after the
17994 class definition is complete.) */
17996 tree
17997 finish_function (bool inline_p)
17999 tree fndecl = current_function_decl;
18000 tree fntype, ctype = NULL_TREE;
18001 tree resumer = NULL_TREE, destroyer = NULL_TREE;
18002 bool coro_p = flag_coroutines
18003 && !processing_template_decl
18004 && DECL_COROUTINE_P (fndecl);
18005 bool coro_emit_helpers = false;
18007 /* When we get some parse errors, we can end up without a
18008 current_function_decl, so cope. */
18009 if (fndecl == NULL_TREE)
18010 return error_mark_node;
18012 if (!DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18013 finish_lambda_scope ();
18015 if (c_dialect_objc ())
18016 objc_finish_function ();
18018 record_key_method_defined (fndecl);
18020 fntype = TREE_TYPE (fndecl);
18022 /* TREE_READONLY (fndecl) = 1;
18023 This caused &foo to be of type ptr-to-const-function
18024 which then got a warning when stored in a ptr-to-function variable. */
18026 gcc_assert (building_stmt_list_p ());
18027 /* The current function is being defined, so its DECL_INITIAL should
18028 be set, and unless there's a multiple definition, it should be
18029 error_mark_node. */
18030 gcc_assert (DECL_INITIAL (fndecl) == error_mark_node);
18032 if (coro_p)
18034 /* Only try to emit the coroutine outlined helper functions if the
18035 transforms succeeded. Otherwise, treat errors in the same way as
18036 a regular function. */
18037 coro_emit_helpers = morph_fn_to_coro (fndecl, &resumer, &destroyer);
18039 /* We should handle coroutine IFNs in middle end lowering. */
18040 cfun->coroutine_component = true;
18042 /* Do not try to process the ramp's EH unless outlining succeeded. */
18043 if (coro_emit_helpers && use_eh_spec_block (fndecl))
18044 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
18045 (TREE_TYPE (fndecl)),
18046 current_eh_spec_block);
18048 else
18049 /* For a cloned function, we've already got all the code we need;
18050 there's no need to add any extra bits. */
18051 if (!DECL_CLONED_FUNCTION_P (fndecl))
18053 /* Make it so that `main' always returns 0 by default. */
18054 if (DECL_MAIN_FREESTANDING_P (current_function_decl)
18055 && !TREE_THIS_VOLATILE (current_function_decl))
18056 finish_return_stmt (integer_zero_node);
18058 if (use_eh_spec_block (current_function_decl))
18059 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
18060 (TREE_TYPE (current_function_decl)),
18061 current_eh_spec_block);
18064 /* If we're saving up tree structure, tie off the function now. */
18065 DECL_SAVED_TREE (fndecl) = pop_stmt_list (DECL_SAVED_TREE (fndecl));
18067 finish_fname_decls ();
18069 /* This must come after expand_function_end because cleanups might
18070 have declarations (from inline functions) that need to go into
18071 this function's blocks. */
18073 /* If the current binding level isn't the outermost binding level
18074 for this function, either there is a bug, or we have experienced
18075 syntax errors and the statement tree is malformed. */
18076 if (current_binding_level->kind != sk_function_parms)
18078 /* Make sure we have already experienced errors. */
18079 gcc_assert (errorcount);
18081 /* Throw away the broken statement tree and extra binding
18082 levels. */
18083 DECL_SAVED_TREE (fndecl) = alloc_stmt_list ();
18085 while (current_binding_level->kind != sk_function_parms)
18087 if (current_binding_level->kind == sk_class)
18088 pop_nested_class ();
18089 else
18090 poplevel (0, 0, 0);
18093 poplevel (1, 0, 1);
18095 /* Statements should always be full-expressions at the outermost set
18096 of curly braces for a function. */
18097 gcc_assert (stmts_are_full_exprs_p ());
18099 /* If there are no return statements in a function with auto return type,
18100 the return type is void. But if the declared type is something like
18101 auto*, this is an error. */
18102 if (!processing_template_decl && FNDECL_USED_AUTO (fndecl)
18103 && TREE_TYPE (fntype) == DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
18105 if (is_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
18106 && !current_function_returns_value
18107 && !current_function_returns_null)
18109 /* We haven't applied return type deduction because we haven't
18110 seen any return statements. Do that now. */
18111 tree node = type_uses_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
18112 do_auto_deduction (DECL_SAVED_AUTO_RETURN_TYPE (fndecl),
18113 void_node, node, tf_warning_or_error,
18114 adc_return_type);
18116 apply_deduced_return_type (fndecl, void_type_node);
18117 fntype = TREE_TYPE (fndecl);
18119 else if (!current_function_returns_value
18120 && !current_function_returns_null)
18122 error ("no return statements in function returning %qT",
18123 DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
18124 inform (input_location, "only plain %<auto%> return type can be "
18125 "deduced to %<void%>");
18129 /* Remember that we were in class scope. */
18130 if (current_class_name)
18131 ctype = current_class_type;
18133 if (DECL_DELETED_FN (fndecl))
18135 DECL_INITIAL (fndecl) = error_mark_node;
18136 DECL_SAVED_TREE (fndecl) = NULL_TREE;
18137 goto cleanup;
18140 // If this is a concept, check that the definition is reasonable.
18141 if (DECL_DECLARED_CONCEPT_P (fndecl))
18142 check_function_concept (fndecl);
18144 if (flag_openmp)
18145 if (tree attr = lookup_attribute ("omp declare variant base",
18146 DECL_ATTRIBUTES (fndecl)))
18147 omp_declare_variant_finalize (fndecl, attr);
18149 /* Complain if there's just no return statement. */
18150 if ((warn_return_type
18151 || (cxx_dialect >= cxx14
18152 && DECL_DECLARED_CONSTEXPR_P (fndecl)))
18153 && !VOID_TYPE_P (TREE_TYPE (fntype))
18154 && !dependent_type_p (TREE_TYPE (fntype))
18155 && !current_function_returns_value && !current_function_returns_null
18156 /* Don't complain if we abort or throw. */
18157 && !current_function_returns_abnormally
18158 /* Don't complain if there's an infinite loop. */
18159 && !current_function_infinite_loop
18160 /* Don't complain if we are declared noreturn. */
18161 && !TREE_THIS_VOLATILE (fndecl)
18162 && !DECL_NAME (DECL_RESULT (fndecl))
18163 && !warning_suppressed_p (fndecl, OPT_Wreturn_type)
18164 /* Structor return values (if any) are set by the compiler. */
18165 && !DECL_CONSTRUCTOR_P (fndecl)
18166 && !DECL_DESTRUCTOR_P (fndecl)
18167 && targetm.warn_func_return (fndecl))
18169 gcc_rich_location richloc (input_location);
18170 /* Potentially add a "return *this;" fix-it hint for
18171 assignment operators. */
18172 if (IDENTIFIER_ASSIGN_OP_P (DECL_NAME (fndecl)))
18174 tree valtype = TREE_TYPE (DECL_RESULT (fndecl));
18175 if (TREE_CODE (valtype) == REFERENCE_TYPE
18176 && current_class_ref
18177 && same_type_ignoring_top_level_qualifiers_p
18178 (TREE_TYPE (valtype), TREE_TYPE (current_class_ref))
18179 && global_dc->option_enabled (OPT_Wreturn_type,
18180 global_dc->lang_mask,
18181 global_dc->option_state))
18182 add_return_star_this_fixit (&richloc, fndecl);
18184 if (cxx_dialect >= cxx14
18185 && DECL_DECLARED_CONSTEXPR_P (fndecl))
18186 error_at (&richloc, "no return statement in %<constexpr%> function "
18187 "returning non-void");
18188 else if (warning_at (&richloc, OPT_Wreturn_type,
18189 "no return statement in function returning "
18190 "non-void"))
18191 suppress_warning (fndecl, OPT_Wreturn_type);
18194 /* Lambda closure members are implicitly constexpr if possible. */
18195 if (cxx_dialect >= cxx17
18196 && LAMBDA_TYPE_P (CP_DECL_CONTEXT (fndecl)))
18197 DECL_DECLARED_CONSTEXPR_P (fndecl)
18198 = ((processing_template_decl
18199 || is_valid_constexpr_fn (fndecl, /*complain*/false))
18200 && potential_constant_expression (DECL_SAVED_TREE (fndecl)));
18202 /* Save constexpr function body before it gets munged by
18203 the NRV transformation. */
18204 maybe_save_constexpr_fundef (fndecl);
18206 /* Invoke the pre-genericize plugin before we start munging things. */
18207 if (!processing_template_decl)
18208 invoke_plugin_callbacks (PLUGIN_PRE_GENERICIZE, fndecl);
18210 /* Perform delayed folding before NRV transformation. */
18211 if (!processing_template_decl
18212 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
18213 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18214 cp_fold_function (fndecl);
18216 /* Set up the named return value optimization, if we can. Candidate
18217 variables are selected in check_return_expr. */
18218 if (current_function_return_value)
18220 tree r = current_function_return_value;
18221 tree outer;
18223 if (r != error_mark_node
18224 /* This is only worth doing for fns that return in memory--and
18225 simpler, since we don't have to worry about promoted modes. */
18226 && aggregate_value_p (TREE_TYPE (TREE_TYPE (fndecl)), fndecl)
18227 /* Only allow this for variables declared in the outer scope of
18228 the function so we know that their lifetime always ends with a
18229 return; see g++.dg/opt/nrv6.C. We could be more flexible if
18230 we were to do this optimization in tree-ssa. */
18231 && (outer = outer_curly_brace_block (fndecl))
18232 && chain_member (r, BLOCK_VARS (outer)))
18233 finalize_nrv (&DECL_SAVED_TREE (fndecl), r, DECL_RESULT (fndecl));
18235 current_function_return_value = NULL_TREE;
18238 /* Must mark the RESULT_DECL as being in this function. */
18239 DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
18241 /* Set the BLOCK_SUPERCONTEXT of the outermost function scope to point
18242 to the FUNCTION_DECL node itself. */
18243 BLOCK_SUPERCONTEXT (DECL_INITIAL (fndecl)) = fndecl;
18245 /* Store the end of the function, so that we get good line number
18246 info for the epilogue. */
18247 cfun->function_end_locus = input_location;
18249 /* Complain about parameters that are only set, but never otherwise used. */
18250 if (warn_unused_but_set_parameter
18251 && !processing_template_decl
18252 && errorcount == unused_but_set_errorcount
18253 && !DECL_CLONED_FUNCTION_P (fndecl))
18255 tree decl;
18257 for (decl = DECL_ARGUMENTS (fndecl);
18258 decl;
18259 decl = DECL_CHAIN (decl))
18260 if (TREE_USED (decl)
18261 && TREE_CODE (decl) == PARM_DECL
18262 && !DECL_READ_P (decl)
18263 && DECL_NAME (decl)
18264 && !DECL_ARTIFICIAL (decl)
18265 && !warning_suppressed_p (decl,OPT_Wunused_but_set_parameter)
18266 && !DECL_IN_SYSTEM_HEADER (decl)
18267 && TREE_TYPE (decl) != error_mark_node
18268 && !TYPE_REF_P (TREE_TYPE (decl))
18269 && (!CLASS_TYPE_P (TREE_TYPE (decl))
18270 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl))))
18271 warning_at (DECL_SOURCE_LOCATION (decl),
18272 OPT_Wunused_but_set_parameter,
18273 "parameter %qD set but not used", decl);
18274 unused_but_set_errorcount = errorcount;
18277 /* Complain about locally defined typedefs that are not used in this
18278 function. */
18279 maybe_warn_unused_local_typedefs ();
18281 /* Possibly warn about unused parameters. */
18282 if (warn_unused_parameter
18283 && !processing_template_decl
18284 && !DECL_CLONED_FUNCTION_P (fndecl))
18285 do_warn_unused_parameter (fndecl);
18287 /* Genericize before inlining. */
18288 if (!processing_template_decl
18289 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
18290 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
18291 cp_genericize (fndecl);
18293 /* If this function can't throw any exceptions, remember that. */
18294 if (!processing_template_decl
18295 && !cp_function_chain->can_throw
18296 && !flag_non_call_exceptions
18297 && !decl_replaceable_p (fndecl,
18298 opt_for_fn (fndecl, flag_semantic_interposition)))
18299 TREE_NOTHROW (fndecl) = 1;
18301 /* Emit the resumer and destroyer functions now, providing that we have
18302 not encountered some fatal error. */
18303 if (coro_emit_helpers)
18305 emit_coro_helper (resumer);
18306 emit_coro_helper (destroyer);
18309 cleanup:
18310 /* We're leaving the context of this function, so zap cfun. It's still in
18311 DECL_STRUCT_FUNCTION, and we'll restore it in tree_rest_of_compilation. */
18312 set_cfun (NULL);
18313 current_function_decl = NULL;
18315 /* If this is an in-class inline definition, we may have to pop the
18316 bindings for the template parameters that we added in
18317 maybe_begin_member_template_processing when start_function was
18318 called. */
18319 if (inline_p)
18320 maybe_end_member_template_processing ();
18322 /* Leave the scope of the class. */
18323 if (ctype)
18324 pop_nested_class ();
18326 --function_depth;
18328 /* Clean up. */
18329 current_function_decl = NULL_TREE;
18331 invoke_plugin_callbacks (PLUGIN_FINISH_PARSE_FUNCTION, fndecl);
18333 finish_function_contracts (fndecl);
18335 return fndecl;
18338 /* Create the FUNCTION_DECL for a function definition.
18339 DECLSPECS and DECLARATOR are the parts of the declaration;
18340 they describe the return type and the name of the function,
18341 but twisted together in a fashion that parallels the syntax of C.
18343 This function creates a binding context for the function body
18344 as well as setting up the FUNCTION_DECL in current_function_decl.
18346 Returns a FUNCTION_DECL on success.
18348 If the DECLARATOR is not suitable for a function (it defines a datum
18349 instead), we return 0, which tells yyparse to report a parse error.
18351 May return void_type_node indicating that this method is actually
18352 a friend. See grokfield for more details.
18354 Came here with a `.pushlevel' .
18356 DO NOT MAKE ANY CHANGES TO THIS CODE WITHOUT MAKING CORRESPONDING
18357 CHANGES TO CODE IN `grokfield'. */
18359 tree
18360 grokmethod (cp_decl_specifier_seq *declspecs,
18361 const cp_declarator *declarator, tree attrlist)
18363 tree fndecl = grokdeclarator (declarator, declspecs, MEMFUNCDEF, 0,
18364 &attrlist);
18366 if (fndecl == error_mark_node)
18367 return error_mark_node;
18369 if (attrlist)
18370 cplus_decl_attributes (&fndecl, attrlist, 0);
18372 /* Pass friends other than inline friend functions back. */
18373 if (fndecl == void_type_node)
18374 return fndecl;
18376 if (DECL_IN_AGGR_P (fndecl))
18378 if (DECL_CLASS_SCOPE_P (fndecl))
18379 error ("%qD is already defined in class %qT", fndecl,
18380 DECL_CONTEXT (fndecl));
18381 return error_mark_node;
18384 check_template_shadow (fndecl);
18386 /* p1779 ABI-Isolation makes inline not a default for in-class
18387 definitions in named module purview. If the user explicitly
18388 made it inline, grokdeclarator will already have done the right
18389 things. */
18390 if ((!named_module_purview_p ()
18391 || flag_module_implicit_inline
18392 /* Lambda's operator function remains inline. */
18393 || LAMBDA_TYPE_P (DECL_CONTEXT (fndecl)))
18394 /* If the user explicitly asked for this to be inline, we don't
18395 need to do more, but more importantly we want to warn if we
18396 can't inline it. */
18397 && !DECL_DECLARED_INLINE_P (fndecl))
18399 if (TREE_PUBLIC (fndecl))
18400 DECL_COMDAT (fndecl) = 1;
18401 DECL_DECLARED_INLINE_P (fndecl) = 1;
18402 /* It's ok if we can't inline this. */
18403 DECL_NO_INLINE_WARNING_P (fndecl) = 1;
18406 /* We process method specializations in finish_struct_1. */
18407 if (processing_template_decl && !DECL_TEMPLATE_SPECIALIZATION (fndecl))
18409 /* Avoid calling decl_spec_seq... until we have to. */
18410 bool friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
18411 fndecl = push_template_decl (fndecl, friendp);
18412 if (fndecl == error_mark_node)
18413 return fndecl;
18416 if (DECL_CHAIN (fndecl) && !decl_spec_seq_has_spec_p (declspecs, ds_friend))
18418 fndecl = copy_node (fndecl);
18419 TREE_CHAIN (fndecl) = NULL_TREE;
18422 cp_finish_decl (fndecl, NULL_TREE, false, NULL_TREE, 0);
18424 DECL_IN_AGGR_P (fndecl) = 1;
18425 return fndecl;
18429 /* VAR is a VAR_DECL. If its type is incomplete, remember VAR so that
18430 we can lay it out later, when and if its type becomes complete.
18432 Also handle constexpr variables where the initializer involves
18433 an unlowered PTRMEM_CST because the class isn't complete yet. */
18435 void
18436 maybe_register_incomplete_var (tree var)
18438 gcc_assert (VAR_P (var));
18440 /* Keep track of variables with incomplete types. */
18441 if (!processing_template_decl && TREE_TYPE (var) != error_mark_node
18442 && DECL_EXTERNAL (var))
18444 tree inner_type = TREE_TYPE (var);
18446 while (TREE_CODE (inner_type) == ARRAY_TYPE)
18447 inner_type = TREE_TYPE (inner_type);
18448 inner_type = TYPE_MAIN_VARIANT (inner_type);
18450 if ((!COMPLETE_TYPE_P (inner_type) && CLASS_TYPE_P (inner_type))
18451 /* RTTI TD entries are created while defining the type_info. */
18452 || (TYPE_LANG_SPECIFIC (inner_type)
18453 && TYPE_BEING_DEFINED (inner_type)))
18455 incomplete_var iv = {var, inner_type};
18456 vec_safe_push (incomplete_vars, iv);
18458 else if (!(DECL_LANG_SPECIFIC (var) && DECL_TEMPLATE_INFO (var))
18459 && decl_constant_var_p (var)
18460 && (TYPE_PTRMEM_P (inner_type) || CLASS_TYPE_P (inner_type)))
18462 /* When the outermost open class is complete we can resolve any
18463 pointers-to-members. */
18464 tree context = outermost_open_class ();
18465 incomplete_var iv = {var, context};
18466 vec_safe_push (incomplete_vars, iv);
18471 /* Called when a class type (given by TYPE) is defined. If there are
18472 any existing VAR_DECLs whose type has been completed by this
18473 declaration, update them now. */
18475 void
18476 complete_vars (tree type)
18478 unsigned ix;
18479 incomplete_var *iv;
18481 for (ix = 0; vec_safe_iterate (incomplete_vars, ix, &iv); )
18483 if (same_type_p (type, iv->incomplete_type))
18485 tree var = iv->decl;
18486 tree type = TREE_TYPE (var);
18488 if (type != error_mark_node
18489 && (TYPE_MAIN_VARIANT (strip_array_types (type))
18490 == iv->incomplete_type))
18492 /* Complete the type of the variable. */
18493 complete_type (type);
18494 cp_apply_type_quals_to_decl (cp_type_quals (type), var);
18495 if (COMPLETE_TYPE_P (type))
18496 layout_var_decl (var);
18499 /* Remove this entry from the list. */
18500 incomplete_vars->unordered_remove (ix);
18502 else
18503 ix++;
18507 /* If DECL is of a type which needs a cleanup, build and return an
18508 expression to perform that cleanup here. Return NULL_TREE if no
18509 cleanup need be done. DECL can also be a _REF when called from
18510 split_nonconstant_init_1. */
18512 tree
18513 cxx_maybe_build_cleanup (tree decl, tsubst_flags_t complain)
18515 tree type;
18516 tree attr;
18517 tree cleanup;
18519 /* Assume no cleanup is required. */
18520 cleanup = NULL_TREE;
18522 if (error_operand_p (decl))
18523 return cleanup;
18525 /* Handle "__attribute__((cleanup))". We run the cleanup function
18526 before the destructor since the destructor is what actually
18527 terminates the lifetime of the object. */
18528 if (DECL_P (decl))
18529 attr = lookup_attribute ("cleanup", DECL_ATTRIBUTES (decl));
18530 else
18531 attr = NULL_TREE;
18532 if (attr)
18534 tree id;
18535 tree fn;
18536 tree arg;
18538 /* Get the name specified by the user for the cleanup function. */
18539 id = TREE_VALUE (TREE_VALUE (attr));
18540 /* Look up the name to find the cleanup function to call. It is
18541 important to use lookup_name here because that is what is
18542 used in c-common.cc:handle_cleanup_attribute when performing
18543 initial checks on the attribute. Note that those checks
18544 include ensuring that the function found is not an overloaded
18545 function, or an object with an overloaded call operator,
18546 etc.; we can rely on the fact that the function found is an
18547 ordinary FUNCTION_DECL. */
18548 fn = lookup_name (id);
18549 arg = build_address (decl);
18550 if (!mark_used (decl, complain) && !(complain & tf_error))
18551 return error_mark_node;
18552 cleanup = cp_build_function_call_nary (fn, complain, arg, NULL_TREE);
18553 if (cleanup == error_mark_node)
18554 return error_mark_node;
18556 /* Handle ordinary C++ destructors. */
18557 type = TREE_TYPE (decl);
18558 if (type_build_dtor_call (type))
18560 int flags = LOOKUP_NORMAL|LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR;
18561 tree addr;
18562 tree call;
18564 if (TREE_CODE (type) == ARRAY_TYPE)
18565 addr = decl;
18566 else
18567 addr = build_address (decl);
18569 call = build_delete (input_location, TREE_TYPE (addr), addr,
18570 sfk_complete_destructor, flags, 0, complain);
18571 if (call == error_mark_node)
18572 cleanup = error_mark_node;
18573 else if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
18574 /* Discard the call. */;
18575 else if (decl_maybe_constant_destruction (decl, type)
18576 && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
18577 cxx_constant_dtor (call, decl);
18578 else if (cleanup)
18579 cleanup = cp_build_compound_expr (cleanup, call, complain);
18580 else
18581 cleanup = call;
18584 /* build_delete sets the location of the destructor call to the
18585 current location, even though the destructor is going to be
18586 called later, at the end of the current scope. This can lead to
18587 a "jumpy" behavior for users of debuggers when they step around
18588 the end of the block. So let's unset the location of the
18589 destructor call instead. */
18590 protected_set_expr_location (cleanup, UNKNOWN_LOCATION);
18591 if (cleanup && CONVERT_EXPR_P (cleanup))
18592 protected_set_expr_location (TREE_OPERAND (cleanup, 0), UNKNOWN_LOCATION);
18594 if (cleanup
18595 && DECL_P (decl)
18596 && !lookup_attribute ("warn_unused", TYPE_ATTRIBUTES (TREE_TYPE (decl)))
18597 /* Treat objects with destructors as used; the destructor may do
18598 something substantive. */
18599 && !mark_used (decl, complain) && !(complain & tf_error))
18600 return error_mark_node;
18602 if (cleanup && cfun && !processing_template_decl
18603 && !expr_noexcept_p (cleanup, tf_none))
18604 cp_function_chain->throwing_cleanup = true;
18606 return cleanup;
18610 /* Return the FUNCTION_TYPE that corresponds to MEMFNTYPE, which can be a
18611 FUNCTION_DECL, METHOD_TYPE, FUNCTION_TYPE, pointer or reference to
18612 METHOD_TYPE or FUNCTION_TYPE, or pointer to member function. */
18614 tree
18615 static_fn_type (tree memfntype)
18617 tree fntype;
18618 tree args;
18620 if (TYPE_PTRMEMFUNC_P (memfntype))
18621 memfntype = TYPE_PTRMEMFUNC_FN_TYPE (memfntype);
18622 if (INDIRECT_TYPE_P (memfntype)
18623 || TREE_CODE (memfntype) == FUNCTION_DECL)
18624 memfntype = TREE_TYPE (memfntype);
18625 if (TREE_CODE (memfntype) == FUNCTION_TYPE)
18626 return memfntype;
18627 gcc_assert (TREE_CODE (memfntype) == METHOD_TYPE);
18628 args = TYPE_ARG_TYPES (memfntype);
18629 fntype = build_function_type (TREE_TYPE (memfntype), TREE_CHAIN (args));
18630 fntype = apply_memfn_quals (fntype, type_memfn_quals (memfntype));
18631 fntype = (cp_build_type_attribute_variant
18632 (fntype, TYPE_ATTRIBUTES (memfntype)));
18633 fntype = cxx_copy_lang_qualifiers (fntype, memfntype);
18634 return fntype;
18637 /* DECL was originally constructed as a non-static member function,
18638 but turned out to be static. Update it accordingly. */
18640 void
18641 revert_static_member_fn (tree decl)
18643 tree stype = static_fn_type (decl);
18644 cp_cv_quals quals = type_memfn_quals (stype);
18645 cp_ref_qualifier rqual = type_memfn_rqual (stype);
18647 if (quals != TYPE_UNQUALIFIED || rqual != REF_QUAL_NONE)
18648 stype = apply_memfn_quals (stype, TYPE_UNQUALIFIED, REF_QUAL_NONE);
18650 TREE_TYPE (decl) = stype;
18652 if (DECL_ARGUMENTS (decl))
18653 DECL_ARGUMENTS (decl) = DECL_CHAIN (DECL_ARGUMENTS (decl));
18654 DECL_STATIC_FUNCTION_P (decl) = 1;
18657 /* Return which tree structure is used by T, or TS_CP_GENERIC if T is
18658 one of the language-independent trees. */
18660 enum cp_tree_node_structure_enum
18661 cp_tree_node_structure (union lang_tree_node * t)
18663 switch (TREE_CODE (&t->generic))
18665 case ARGUMENT_PACK_SELECT: return TS_CP_ARGUMENT_PACK_SELECT;
18666 case BASELINK: return TS_CP_BASELINK;
18667 case CONSTRAINT_INFO: return TS_CP_CONSTRAINT_INFO;
18668 case DEFERRED_NOEXCEPT: return TS_CP_DEFERRED_NOEXCEPT;
18669 case DEFERRED_PARSE: return TS_CP_DEFERRED_PARSE;
18670 case IDENTIFIER_NODE: return TS_CP_IDENTIFIER;
18671 case LAMBDA_EXPR: return TS_CP_LAMBDA_EXPR;
18672 case BINDING_VECTOR: return TS_CP_BINDING_VECTOR;
18673 case OVERLOAD: return TS_CP_OVERLOAD;
18674 case PTRMEM_CST: return TS_CP_PTRMEM;
18675 case STATIC_ASSERT: return TS_CP_STATIC_ASSERT;
18676 case TEMPLATE_DECL: return TS_CP_TEMPLATE_DECL;
18677 case TEMPLATE_INFO: return TS_CP_TEMPLATE_INFO;
18678 case TEMPLATE_PARM_INDEX: return TS_CP_TPI;
18679 case TRAIT_EXPR: return TS_CP_TRAIT_EXPR;
18680 case USERDEF_LITERAL: return TS_CP_USERDEF_LITERAL;
18681 default: return TS_CP_GENERIC;
18685 bool
18686 cp_missing_noreturn_ok_p (tree decl)
18688 /* A missing noreturn is ok for the `main' function. */
18689 return DECL_MAIN_P (decl);
18692 /* Return the decl used to identify the COMDAT group into which DECL should
18693 be placed. */
18695 tree
18696 cxx_comdat_group (tree decl)
18698 /* Virtual tables, construction virtual tables, and virtual table
18699 tables all go in a single COMDAT group, named after the primary
18700 virtual table. */
18701 if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
18702 decl = CLASSTYPE_VTABLES (DECL_CONTEXT (decl));
18703 /* For all other DECLs, the COMDAT group is the mangled name of the
18704 declaration itself. */
18705 else
18707 while (DECL_THUNK_P (decl))
18709 /* If TARGET_USE_LOCAL_THUNK_ALIAS_P, use_thunk puts the thunk
18710 into the same section as the target function. In that case
18711 we must return target's name. */
18712 tree target = THUNK_TARGET (decl);
18713 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (target)
18714 && DECL_SECTION_NAME (target) != NULL
18715 && DECL_ONE_ONLY (target))
18716 decl = target;
18717 else
18718 break;
18722 return decl;
18725 /* Returns the return type for FN as written by the user, which may include
18726 a placeholder for a deduced return type. */
18728 tree
18729 fndecl_declared_return_type (tree fn)
18731 fn = STRIP_TEMPLATE (fn);
18732 if (FNDECL_USED_AUTO (fn))
18733 return DECL_SAVED_AUTO_RETURN_TYPE (fn);
18735 return TREE_TYPE (TREE_TYPE (fn));
18738 /* Returns true iff DECL is a variable or function declared with an auto type
18739 that has not yet been deduced to a real type. */
18741 bool
18742 undeduced_auto_decl (tree decl)
18744 if (cxx_dialect < cxx11)
18745 return false;
18746 STRIP_ANY_LOCATION_WRAPPER (decl);
18747 return ((VAR_OR_FUNCTION_DECL_P (decl)
18748 || TREE_CODE (decl) == TEMPLATE_DECL)
18749 && type_uses_auto (TREE_TYPE (decl)));
18752 /* Complain if DECL has an undeduced return type. */
18754 bool
18755 require_deduced_type (tree decl, tsubst_flags_t complain)
18757 if (undeduced_auto_decl (decl))
18759 if (TREE_CODE (decl) == FUNCTION_DECL
18760 && fndecl_built_in_p (decl, BUILT_IN_FRONTEND)
18761 && DECL_FE_FUNCTION_CODE (decl) == CP_BUILT_IN_SOURCE_LOCATION)
18763 /* Set the return type of __builtin_source_location. */
18764 tree type = get_source_location_impl_type ();
18765 if (type == error_mark_node)
18767 inform (input_location, "using %qs", "__builtin_source_location");
18768 return false;
18770 type = cp_build_qualified_type (type, TYPE_QUAL_CONST);
18771 type = build_pointer_type (type);
18772 apply_deduced_return_type (decl, type);
18773 return true;
18776 if (warning_suppressed_p (decl) && seen_error ())
18777 /* We probably already complained about deduction failure. */;
18778 else if (complain & tf_error)
18779 error ("use of %qD before deduction of %<auto%>", decl);
18780 note_failed_type_completion_for_satisfaction (decl);
18781 return false;
18783 return true;
18786 /* Create a representation of the explicit-specifier with
18787 constant-expression of EXPR. COMPLAIN is as for tsubst. */
18789 tree
18790 build_explicit_specifier (tree expr, tsubst_flags_t complain)
18792 if (check_for_bare_parameter_packs (expr))
18793 return error_mark_node;
18795 if (instantiation_dependent_expression_p (expr))
18796 /* Wait for instantiation, tsubst_function_decl will handle it. */
18797 return expr;
18799 expr = build_converted_constant_bool_expr (expr, complain);
18800 expr = instantiate_non_dependent_expr (expr, complain);
18801 expr = cxx_constant_value (expr, complain);
18802 return expr;
18805 #include "gt-cp-decl.h"